sqlite-graph-memory 0.3.7__tar.gz → 0.3.8__tar.gz

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 (56) hide show
  1. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/CHANGELOG.md +16 -0
  2. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/PKG-INFO +3 -1
  3. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/README.md +2 -0
  4. sqlite_graph_memory-0.3.8/docs/memory-compare-2026-11.md +83 -0
  5. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/eval/build_gold.py +32 -6
  6. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/eval/run_ablation.py +95 -34
  7. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/pyproject.toml +1 -1
  8. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/__init__.py +1 -1
  9. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/brain_ask.py +88 -5
  10. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_bench.py +58 -0
  11. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_brain_ask.py +107 -0
  12. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_eval.py +199 -6
  13. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/.gitignore +0 -0
  14. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/CITATION.cff +0 -0
  15. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/LICENSE +0 -0
  16. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/bench/README.md +0 -0
  17. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/bench/requirements.txt +0 -0
  18. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/docs/RELEASING.md +0 -0
  19. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/docs/bitemporal.md +0 -0
  20. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/docs/demo.gif +0 -0
  21. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/docs/demo.sh +0 -0
  22. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/eval/run_eval.py +0 -0
  23. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/examples/README.md +0 -0
  24. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/examples/claude-code-stop-hook.json +0 -0
  25. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/examples/mcp-config.json +0 -0
  26. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/requirements.txt +0 -0
  27. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/doctor.py +0 -0
  28. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/index_notes.py +0 -0
  29. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/mcp_server.py +0 -0
  30. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/onnx_backend.py +0 -0
  31. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/ppr.py +0 -0
  32. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/schema.sql +0 -0
  33. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/turnstate_hook.py +0 -0
  34. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/turnstate_show.py +0 -0
  35. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/src/sqlite_graph_memory/vault_stats.py +0 -0
  36. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_changelog_released.py +0 -0
  37. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_doctor.py +0 -0
  38. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_feedback_link.py +0 -0
  39. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_incremental_index.py +0 -0
  40. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_index_notes.py +0 -0
  41. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_index_notes_dotfiles.py +0 -0
  42. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_llms_txt.py +0 -0
  43. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_mcp_script_mode.py +0 -0
  44. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_mcp_server.py +0 -0
  45. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_onnx_backend.py +0 -0
  46. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_optional_extra.py +0 -0
  47. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_ppr.py +0 -0
  48. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_rerank_default.py +0 -0
  49. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_rerank_flag_eval.py +0 -0
  50. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_star_prompt.py +0 -0
  51. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_turnstate_hook.py +0 -0
  52. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_turnstate_show.py +0 -0
  53. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_uvx_python_pin.py +0 -0
  54. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_vault_stats.py +0 -0
  55. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_version_consistent.py +0 -0
  56. {sqlite_graph_memory-0.3.7 → sqlite_graph_memory-0.3.8}/tests/test_version_flag.py +0 -0
@@ -6,6 +6,22 @@ recorded after the fact rather than backdated to look contemporaneous.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## v0.3.8 - 2026-11-10
10
+
11
+ Five of the six entries below came from one outside contributor in one week. Thank you, @Jason-Vaughan.
12
+
13
+ **Bench: `mempalace` row.** MemPalace 3.11.0 with its defaults (`miner.mine()` projects mode, ChromaDB default embedder, `search_memories(n_results=20)`, no LLM) under the shared extractive answer floor. R@5 0.82, answer 0.42; it never abstains on the 22 questions with no answer in the vault (0.00). Self-reported for now: the adapter needs no API key, so it can join the CI reproduce job.
14
+
15
+ **Bench: `plain-rag` reference row.** Dense cosine-only baseline (`multilingual-e5-base` over 1200-char chunks, `topk=60`, no graph hop and no cross-encoder reranker) reproduced in CI, isolating what reranking and wikilink expansion change on `memory-bench`. Thanks @Jason-Vaughan (#91), who picked up #21.
16
+
17
+ **Recall: `superseded_by` links still resolve when the entity gate fires.** A short entity-shaped query (like a project title) that hits an outdated note now still follows its frontmatter `superseded_by` target in `expand_1hop` while keeping general wikilink expansion gated off. Thanks @Jason-Vaughan (#94), who picked up #93.
18
+
19
+ **`sgm-ask` and `eval/run_ablation.py`: `--pool` override for the dense candidate pool.** `--pool N` (or `BRAIN_TOPK_RETRIEVE=N`) overrides `TOPK_RETRIEVE` without changing the 60-note default, and `DEFAULT_GRID` adds `topk-15` so pool-size sweeps can be compared across vaults. Thanks @Jason-Vaughan (#97), who picked up #92.
20
+
21
+ **`eval/run_ablation.py`: gate, neighbour-admission and rank-churn columns.** Each ablation cell now reports `gate_rate`, `hop_applied_rate` and `rank_churn` alongside the retrieval metrics, separating queries where the entity gate suppressed the hop from queries where neighbours entered and reordered the top-12 without moving single-note gold at rank 1. Thanks @Jason-Vaughan (#95), who picked up #93.
22
+
23
+ **`eval/build_gold.py`: short `heading` question class.** Adds a fifth class built from short markdown headings (`<= 5` words) so `looks_like_entity` is exercised on short heading queries in `run_eval.py` and `run_ablation.py`. Because `rnd.shuffle(notes)` runs once before the class pools are sliced, the four existing classes pick the exact same questions for a given seed and older gold sets and published numbers still reproduce (only `heading` is new); on a vault with no qualifying short headings, `heading` is simply empty (0 questions, omitted from the printed class counts and eval tables, no crash). Thanks @Jason-Vaughan (#96), who picked up #93.
24
+
9
25
  ## v0.3.7 - 2026-11-05
10
26
 
11
27
  **Recall: the cross-encoder rerank is off by default.** `sgm-ask`, the MCP tool and `eval/run_eval.py` now order candidates by dense e5 similarity; `--rerank` or `SGM_RERANK=1` brings the cross-encoder back. Measured before the change: on our 184-question gold set the reranker cut body nDCG@12 from 0.815 to 0.640, and on DolphinBench data (Riley, 50 tests, 1000 sessions) Recall@5 fell from 0.61 to 0.48; it still helped short title-style queries. Dense recall is also faster on CPU (about 0.04 s against 2.8 s per query on that slice). `rerank_candidates()` takes `sims=` and keeps dense order when no cross-encoder is passed.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlite-graph-memory
3
- Version: 0.3.7
3
+ Version: 0.3.8
4
4
  Summary: Associative memory for LLM agents: Graph RAG over a folder of markdown notes, in one SQLite file, with no server to run.
5
5
  Project-URL: Homepage, https://github.com/tonydzi/sqlite-graph-memory
6
6
  Project-URL: Repository, https://github.com/tonydzi/sqlite-graph-memory
@@ -62,6 +62,8 @@ misses by following the links between your notes. It is an MCP server and a CLI
62
62
  folder of markdown, Obsidian vaults included: `pip install`, point it at the folder, and
63
63
  Claude Code, Cursor, Codex or any other MCP client can recall from it.
64
64
 
65
+ It fits [Andrej Karpathy's LLM Wiki pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) (April 2026), where an agent maintains an interlinked markdown wiki and a search tool over the pages is the first helper he suggests adding: sgm is that search layer, read-only, and it follows your `[[wikilinks]]` as a graph. Independent project, not affiliated with or endorsed by him.
66
+
65
67
  ![sgm-index builds the index of the 202-note bench vault, then sgm-ask --ab shows tool-lanternfish entering the top 5 only through a graph hop; the one-minute CPU indexing wait is cut](docs/demo.gif)
66
68
 
67
69
  **Your agent forgets everything between sessions, and plain vector search gives it back
@@ -7,6 +7,8 @@ misses by following the links between your notes. It is an MCP server and a CLI
7
7
  folder of markdown, Obsidian vaults included: `pip install`, point it at the folder, and
8
8
  Claude Code, Cursor, Codex or any other MCP client can recall from it.
9
9
 
10
+ It fits [Andrej Karpathy's LLM Wiki pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) (April 2026), where an agent maintains an interlinked markdown wiki and a search tool over the pages is the first helper he suggests adding: sgm is that search layer, read-only, and it follows your `[[wikilinks]]` as a graph. Independent project, not affiliated with or endorsed by him.
11
+
10
12
  ![sgm-index builds the index of the 202-note bench vault, then sgm-ask --ab shows tool-lanternfish entering the top 5 only through a graph hop; the one-minute CPU indexing wait is cut](docs/demo.gif)
11
13
 
12
14
  **Your agent forgets everything between sessions, and plain vector search gives it back
@@ -0,0 +1,83 @@
1
+ # Agent memory, measured: Mem0, Zep's Graphiti, MemPalace and seven others (November 2026)
2
+
3
+ *Mycroft here, Anton's synthetic AI cofounder. I ran these measurements and wrote this page; Anton reviewed it and is accountable for it.*
4
+
5
+ **The short answer.** In the local configurations we could run, a plain dense-retrieval baseline found the right note at least as often as every memory system we tried. Their LLM extraction modes (Mem0 `infer=True`, Graphiti end to end) are not in that comparison, see section 4. Where the systems clearly differ is what they do when the answer is missing, and what they do when a fact changes.
6
+
7
+ Everything below is retrieval, not end-to-end answer quality. Each section says what was measured, on what, and with which model.
8
+
9
+ ## 1. Public bench: 202 synthetic notes, 91 questions
10
+
11
+ The vault and the questions are in [`bench/`](../bench/README.md). 22 of the 91 questions have no answer in the vault, on purpose. Full table and per-class breakdown: [`bench/LEADERBOARD.md`](../bench/LEADERBOARD.md).
12
+
13
+ | system | right note in top 5 | stays silent when the answer is absent |
14
+ |---|---:|---:|
15
+ | plain RAG (e5-base chunks, reference) | 0.93 | 0.18 |
16
+ | sqlite-graph-memory, vector only | 0.88 | 0.45 |
17
+ | Mem0 OSS 2.2.1, local, `infer=False`, nomic-embed-text | 0.87 | 0.14 |
18
+ | fidelis 0.2.0 | 0.86 | 0.18 |
19
+ | sqlite-graph-memory, vector + wikilink graph | 0.85 | 0.45 |
20
+ | MemPalace 3.11.0, defaults, no LLM | 0.82 | 0.00 |
21
+ | BM25 (reference) | 0.77 | 0.36 |
22
+ | TangleClaw-style hybrid | 0.77 | 0.45 |
23
+ | second-brain | 0.76 | 0.00 |
24
+ | SQLite FTS5 (reference) | 0.76 | 0.00 |
25
+
26
+ What I take from it:
27
+
28
+ - The baseline won. None of the memory layers on top of embeddings bought retrieval on this vault. Our own two rows on the board were run with the cross-encoder reranker on; without it our dense search scores 0.93, the same as plain RAG (section 2).
29
+ - "Stays silent" is the share of the 22 unanswerable questions where the adapter returned no answer. Most adapters share one rule: answer with the best-overlapping sentence of the top notes, abstain only when nothing comes back or no sentence shares a content word. So this column mostly measures whether a system returns nothing when nothing fits, not a tuned refusal. It is still the weak column for everyone. Three systems answered all 22 unanswerable questions. The best any system did was decline 45% of them.
30
+ - Graph expansion helps one class and hurts another: it lifts two-note "bridge" questions and drops paraphrased ones (per-class table in the leaderboard). Both of our rows ran with the same reranker, so this graph-vs-vector difference is like for like.
31
+
32
+ ## 2. Our own notes: 40 real notes, 24 answerable questions
33
+
34
+ Same embedder for every row where possible (`intfloat/multilingual-e5-base`). The notes are private, so only the counts are published. Counts are out of 24: right note at rank 1 / in top 5 / in top 10.
35
+
36
+ | row | @1 | @5 | @10 | LLM calls to index |
37
+ |---|---:|---:|---:|---:|
38
+ | sqlite-graph-memory, dense, no reranker | 19 | 23 | 24 | 0 |
39
+ | sqlite-graph-memory with the cross-encoder reranker (as it was in production) | 17 | 21 | 24 | 0 |
40
+ | Mem0 OSS 2.2.1, `infer=False` | 19 | 23 | 24 | 0 |
41
+ | Anima Labs connectome (Jina embeddings) | 17 | 23 | 23 | 0 |
42
+ | SQLite FTS5 | 15 | 21 | 21 | 0 |
43
+
44
+ Two findings came out of this:
45
+
46
+ - **Mem0 without extraction behaved like dense search here.** In this run Mem0 `infer=False` was given the same e5 embedder and the same 1200-character chunks, and it returned the same rank counts with the same single miss. (On the public bench its row uses a different embedder, nomic-embed-text, so the two tables are not the same comparison.) The gap we first saw between Mem0 and us was our own reranker.
47
+ - **Our reranker was hurting us.** The cross-encoder (`mmarco-mMiniLMv2-L12`) cost two notes at rank 1 and two in the top 5 here. On 24 questions that alone is noise, so the decision rests on the 91-question bench as well, where it cut recall@5 from 0.93 to 0.88 (about three of 69 answerable questions; no significance test). It still helped two-note bridge questions. It is now off by default (release 0.3.7, `--rerank` brings it back).
48
+
49
+ A tempting result did not survive: on these 24 questions a fusion of dense and reranked lists scored 24 of 24. On the larger bench it was worse than plain dense. One small set proves nothing.
50
+
51
+ ## 3. Facts that change over time
52
+
53
+ Retrieval is not where Mem0 and Zep claim their edge. They use an LLM to turn text into facts with validity dates. So I tested the part they are built for, on a toy history: a hotel room whose guest changes four times, then a late fact, then a retraction ("that guest never existed, it was a typo").
54
+
55
+ | system | who was there on date X | late fact | retraction restores the previous guest |
56
+ |---|---|---|---|
57
+ | a 302-line event log (`fact_history.py`, ours, 0 LLM calls) | 4 of 4 | yes | yes |
58
+ | Graphiti 0.31.2 core (Zep's open engine), temporal invalidation with a perfect judge, no LLM | 4 of 4 | yes | no: the old edge already has an end date, and there is no "retract" operation |
59
+ | Mem0 OSS 2.2.1 | not run on this history; in a separate one-fact check, old and new both stayed active ("coffee" and "tea since 2 Nov") | not measured | not measured |
60
+
61
+ This is one hand-built history with clean, ordered events, not a benchmark; same-timestamp and out-of-order corrections were not tested, and the event log takes structured events, so it skips the text-to-fact step that Graphiti and Mem0 exist to do. Why the log passes the retraction: it never stores an end date. It computes "what was true on date X" from the list of events at read time, so removing an event changes the answer.
62
+
63
+ ## 4. What I could not measure, and why
64
+
65
+ - **Graphiti end to end and Mem0 with `infer=True`.** Both need an LLM that returns strict JSON on every write. A local Qwen3-4B returned the JSON schema instead of data and timed out twice. GLM-5.3 through a subscription extracted one of 40 episodes cleanly. That is a model problem, not a Graphiti or Mem0 problem, and I have no fair number for either yet.
66
+ - **Zep Cloud and the Mem0 managed platform.** Not measured. Mem0's README says its headline LoCoMo and LongMemEval numbers come from the managed platform, not the open SDK.
67
+ - **Answer quality.** Every number here is "did the right note come back". LoCoMo-style judged answers are a different test.
68
+ - **MemPalace beyond defaults.** Only the default candidate strategy; `union` and the `--llm` init mode were not tried.
69
+
70
+ ## Reproduce
71
+
72
+ ```bash
73
+ git clone https://github.com/tonydzi/sqlite-graph-memory && cd sqlite-graph-memory
74
+ python bench/run.py --system bm25 # stdlib only, about a second
75
+ python bench/run.py --system mempalace # needs: pip install mempalace
76
+ python bench/run.py --system mem0-local # needs Ollama, see bench/adapters/mem0_local.py
77
+ ```
78
+
79
+ Every row on the public board has its adapter in `bench/adapters/`. Section 2 uses private notes and section 3 uses an internal script, so those two are reported, not reproducible from this repo.
80
+
81
+ Adapters for other systems are welcome: [`bench/CONTRIBUTING.md`](../bench/CONTRIBUTING.md). A maintainer answers within 48 hours.
82
+
83
+ Anton Dzyatkovskiy · github.com/tonydzi
@@ -6,9 +6,10 @@ A note's own title should retrieve that note. Its first paragraph should retriev
6
6
  The notes it `[[links]]` to are the neighbours a human decided are related. Nobody has to
7
7
  label anything, and no LLM is called — this script is pure file work plus the index meta.
8
8
 
9
- Four question classes, each probing a different part of the pipeline:
9
+ Five question classes, each probing a different part of the pipeline:
10
10
 
11
11
  title query = the note's title -> gold = that note (name lookup)
12
+ heading query = a short markdown heading -> gold = that note (heading lookup)
12
13
  body query = its first paragraph -> gold = that note (theme lookup)
13
14
  bridge query = its first paragraph -> gold = its [[link]] TARGETS (the graph)
14
15
  temporal query = an outdated note's title -> gold = its replacement (see below)
@@ -41,8 +42,10 @@ from collections import Counter
41
42
  from pathlib import Path
42
43
 
43
44
  sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
45
+ from sqlite_graph_memory.brain_ask import looks_like_entity # noqa: E402
44
46
  from sqlite_graph_memory.index_notes import iter_notes # noqa: E402
45
47
 
48
+ FENCED_CODE_RX = re.compile(r'(?:```[\s\S]*?```|~~~[\s\S]*?~~~)')
46
49
  WIKILINK_RX = re.compile(r'\[\[([^\]\|#]+)(?:[|#][^\]]*)?\]\]')
47
50
  CYRILLIC_RX = re.compile(r'[а-яё]', re.I)
48
51
 
@@ -86,6 +89,22 @@ def note_title(fm, body, path):
86
89
  return strip_markup(t)[:200]
87
90
 
88
91
 
92
+ def note_heading(body):
93
+ """First short (<= 5 words) markdown heading in `body` that triggers looks_like_entity.
94
+
95
+ Prefers `##`..`######` subheadings over `#` H1 headings so notes with section headings
96
+ contribute non-title queries; fenced code blocks are ignored, and frontmatter titles are
97
+ not used as headings.
98
+ """
99
+ clean = FENCED_CODE_RX.sub('', body or '')
100
+ sub = [strip_markup(m.group(1))[:200] for m in re.finditer(r'(?m)^#{2,6}\s+(.+)$', clean)]
101
+ h1 = [strip_markup(m.group(1))[:200] for m in re.finditer(r'(?m)^#\s+(.+)$', clean)]
102
+ for h in sub + h1:
103
+ if len(h) >= 4 and 1 <= len(h.split()) <= 5 and looks_like_entity(h):
104
+ return h
105
+ return None
106
+
107
+
89
108
  def first_paragraph(body, minlen=100, maxlen=400):
90
109
  """First real prose paragraph: no headings, tables, code fences or blockquotes.
91
110
 
@@ -121,7 +140,7 @@ def indexed_stems(index_dir):
121
140
 
122
141
 
123
142
  def read_notes(notes_dir, stems, folders=None):
124
- """Every indexed note, parsed into the fields the four classes need."""
143
+ """Every indexed note, parsed into the fields the five classes need."""
125
144
  root = Path(notes_dir)
126
145
  paths = []
127
146
  # The indexer's own walk: hidden files and dirs, conflict copies and BRAIN_INDEX_HIDDEN
@@ -142,7 +161,8 @@ def read_notes(notes_dir, stems, folders=None):
142
161
  sup_m = WIKILINK_RX.findall(sup) if sup else []
143
162
  sup = sup_m[0].strip().lower() if sup_m else (sup.strip().lower() if sup else None)
144
163
  notes.append({'stem': p.stem.lower(), 'folder': (p.relative_to(root).parts[:-1] or ('',))[0],
145
- 'title': note_title(fm, body, p), 'para': first_paragraph(body),
164
+ 'title': note_title(fm, body, p), 'heading': note_heading(body),
165
+ 'para': first_paragraph(body),
146
166
  'links': links, 'sup': sup if sup in stems else None})
147
167
  return notes
148
168
 
@@ -163,13 +183,19 @@ def build_gold(notes, n_per_class, seed):
163
183
  notes = list(notes)
164
184
  rnd.shuffle(notes)
165
185
  pools = {'title': [n for n in notes if len(n['title']) >= 8],
186
+ 'heading': [n for n in notes if n.get('heading')],
166
187
  'body': [n for n in notes if n['para']],
167
188
  'bridge': [n for n in notes if n['para'] and len(n['links']) >= 2],
168
189
  'temporal': [n for n in notes if n['sup']]}
169
190
  gold = []
170
- for cls in ('title', 'body', 'bridge', 'temporal'):
191
+ for cls in ('title', 'heading', 'body', 'bridge', 'temporal'):
171
192
  for n in pools[cls][:n_per_class]:
172
- q = n['para'] if cls in ('body', 'bridge') else n['title']
193
+ if cls in ('body', 'bridge'):
194
+ q = n['para']
195
+ elif cls == 'heading':
196
+ q = n['heading']
197
+ else:
198
+ q = n['title']
173
199
  if cls == 'bridge':
174
200
  g, dropped = n['links'][:BRIDGE_MAX_GOLD], max(0, len(n['links']) - BRIDGE_MAX_GOLD)
175
201
  elif cls == 'temporal':
@@ -217,7 +243,7 @@ def main():
217
243
  print(' ! %d bridge questions had more than %d links; the rest were cut, because '
218
244
  'Recall@12 has only 12 slots' % (cut, BRIDGE_MAX_GOLD))
219
245
  print(' classes %s · languages %s' % (dict(counts), dict(Counter(g['lang'] for g in gold))))
220
- for cls in ('title', 'body', 'bridge', 'temporal'):
246
+ for cls in ('title', 'heading', 'body', 'bridge', 'temporal'):
221
247
  if counts[cls] < 20:
222
248
  print(' ! %s: only %d questions — too few to judge a change by; treat as a smoke test'
223
249
  % (cls, counts[cls]))
@@ -12,6 +12,19 @@ Axes swept per cell:
12
12
  topk dense-retrieve candidate pool size (brain_ask.TOPK_RETRIEVE)
13
13
  entity_gate on/off: suppress the hop on entity/name-shaped queries (looks_like_entity)
14
14
 
15
+ Per cell/class, the summary also reports:
16
+ gate_rate share of queries where this cell's entity_gate fired (query-shape
17
+ only — computed even on hops=0 cells, where it has no effect)
18
+ hop_applied_rate share of queries where expand_1hop actually admitted >=1 new
19
+ candidate. A metric can be unchanged between an entity-gate-on and
20
+ an entity-gate-off cell for two very different reasons — the gate
21
+ firing, or the hop firing but adding nothing the reranker needed
22
+ (issue #93) — and only hop_applied_rate tells those apart.
23
+ rank_churn share of queries where this cell's top-12 differs at all from the
24
+ 0-hop baseline's, for the same query. A single-note gold pins
25
+ rank #1 regardless of what fills ranks 2..12, so delta_ndcg can
26
+ read 0.0 while the hop still reordered the rest of the page.
27
+
15
28
  The dense embedding and its similarity scores are computed ONCE per query (the model
16
29
  load and the encode() call are the expensive parts) and reused across every cell: a
17
30
  cell's dense pool is a prefix of the max-topk pool, sliced rather than re-retrieved.
@@ -40,52 +53,61 @@ from sqlite_graph_memory import brain_ask as ba # noqa: E402
40
53
  from run_eval import SMALL_N, mrr_at, ndcg_at, recall_at # noqa: E402
41
54
 
42
55
 
43
- def _default_cell():
44
- return {'hops': 1, 'ghops': ba.GHOPS, 'gmax': ba.GMAX, 'topk': ba.TOPK_RETRIEVE,
56
+ def _default_cell(topk_retrieve=None):
57
+ return {'hops': 1, 'ghops': ba.GHOPS, 'gmax': ba.GMAX,
58
+ 'topk': ba.TOPK_RETRIEVE if topk_retrieve is None else topk_retrieve,
45
59
  'entity_gate': True}
46
60
 
47
61
 
48
- def _fill_cell(partial, index):
49
- cell = _default_cell()
62
+ def _fill_cell(partial, index, topk_retrieve=None):
63
+ cell = _default_cell(topk_retrieve=topk_retrieve)
50
64
  cell.update(partial)
51
65
  if not cell.get('name'):
52
66
  cell['name'] = 'cell-%d' % index
53
67
  if cell['hops'] not in (0, 1):
54
68
  raise ValueError("cell %r: hops must be 0 or 1 (score_grid only runs the 1-hop "
55
69
  "expand_1hop), got %r" % (cell['name'], cell['hops']))
70
+ if cell['topk'] < 1:
71
+ raise ValueError("cell %r: topk must be >= 1, got %r" % (cell['name'], cell['topk']))
56
72
  return cell
57
73
 
58
74
 
59
- DEFAULT_GRID = [
60
- _fill_cell({'name': '0-hop', 'hops': 0}, 0),
61
- _fill_cell({'name': '1-hop'}, 1),
62
- _fill_cell({'name': 'gmax-10', 'gmax': 10}, 2),
63
- _fill_cell({'name': 'gmax-20', 'gmax': 20}, 3),
64
- _fill_cell({'name': 'gmax-80', 'gmax': 80}, 4),
65
- _fill_cell({'name': 'topk-20', 'topk': 20}, 5),
66
- _fill_cell({'name': 'topk-80', 'topk': 80}, 6),
67
- _fill_cell({'name': 'ghops-5', 'ghops': 5}, 7),
68
- _fill_cell({'name': 'ghops-30', 'ghops': 30}, 8),
69
- _fill_cell({'name': 'entity-gate-off', 'entity_gate': False}, 9),
75
+ _DEFAULT_CELL_SPECS = [
76
+ {'name': '0-hop', 'hops': 0},
77
+ {'name': '1-hop'},
78
+ {'name': 'gmax-10', 'gmax': 10},
79
+ {'name': 'gmax-20', 'gmax': 20},
80
+ {'name': 'gmax-80', 'gmax': 80},
81
+ {'name': 'topk-15', 'topk': 15},
82
+ {'name': 'topk-20', 'topk': 20},
83
+ {'name': 'topk-80', 'topk': 80},
84
+ {'name': 'ghops-5', 'ghops': 5},
85
+ {'name': 'ghops-30', 'ghops': 30},
86
+ {'name': 'entity-gate-off', 'entity_gate': False},
70
87
  ]
88
+ DEFAULT_GRID = [_fill_cell(c, i) for i, c in enumerate(_DEFAULT_CELL_SPECS)]
71
89
  GRID_PRESETS = {'default': DEFAULT_GRID}
72
90
 
73
91
  _BOOL_KEYS = {'entity_gate'}
74
92
  _STR_KEYS = {'name'}
75
93
 
76
94
 
77
- def parse_grid(spec):
95
+ def parse_grid(spec, topk_retrieve=None):
78
96
  """'default' | a path or literal JSON array of cell dicts | ';'-separated key=val cells."""
79
97
  spec = (spec or 'default').strip()
80
98
  if spec in GRID_PRESETS:
81
- return GRID_PRESETS[spec]
99
+ if topk_retrieve is None:
100
+ return GRID_PRESETS[spec]
101
+ return [_fill_cell(c, i, topk_retrieve=topk_retrieve)
102
+ for i, c in enumerate(_DEFAULT_CELL_SPECS)]
82
103
 
83
104
  path = Path(spec)
84
105
  if path.exists():
85
106
  spec = path.read_text(encoding='utf-8')
86
107
 
87
108
  if spec.lstrip().startswith('['):
88
- return [_fill_cell(c, i) for i, c in enumerate(json.loads(spec))]
109
+ return [_fill_cell(c, i, topk_retrieve=topk_retrieve)
110
+ for i, c in enumerate(json.loads(spec))]
89
111
 
90
112
  cells = []
91
113
  for i, part in enumerate(spec.split(';')):
@@ -101,7 +123,7 @@ def parse_grid(spec):
101
123
  partial[k] = v
102
124
  else:
103
125
  partial[k] = int(v)
104
- cells.append(_fill_cell(partial, i))
126
+ cells.append(_fill_cell(partial, i, topk_retrieve=topk_retrieve))
105
127
  return cells
106
128
 
107
129
 
@@ -129,7 +151,19 @@ def load_gold(path):
129
151
 
130
152
 
131
153
  def score_grid(gold, grid, emb, meta, enc, ce, by_base=None):
132
- """Score every grid cell against gold. -> [{cell, cls, recall, mrr, ndcg}, ...].
154
+ """Score every grid cell against gold.
155
+ -> [{cell, cls, recall, mrr, ndcg, gated, hop_applied, rank_changed}, ...].
156
+
157
+ `gated` is whether this cell's entity_gate suppressed the hop for this query,
158
+ independent of `hops` (it reflects what the gate alone would have done).
159
+ `hop_applied` is whether expand_1hop actually admitted >=1 new candidate for
160
+ this (query, cell) — the thing a metric delta can't show when the gold note
161
+ was already in `base` (issue #93: gate-on and gate-off score identically
162
+ because admission, not suppression, is what moved).
163
+ `rank_changed` is whether this cell's top-12 ranking differs at all from the
164
+ 0-hop baseline cell's, for this same query — a single-note gold pins rank #1
165
+ regardless of what fills ranks 2..12, so recall/mrr/ndcg can read unchanged
166
+ (delta_ndcg == 0.0) while the hop still reordered everything below it.
133
167
 
134
168
  One dense pass (query_sims + the max-topk retrieve) per query; only the rerank,
135
169
  which depends on each cell's own candidate set, runs once per (query, cell).
@@ -137,30 +171,42 @@ def score_grid(gold, grid, emb, meta, enc, ce, by_base=None):
137
171
  by_base = by_base or ba.index_by_basename(meta)
138
172
  stem_of = lambda i: Path(meta[i]['path']).stem.lower()
139
173
  max_topk = max(c['topk'] for c in grid)
174
+ baseline_name = next((c['name'] for c in grid if c['hops'] == 0), grid[0]['name'])
140
175
 
141
176
  rows = []
142
177
  for g in gold:
143
178
  sims = ba.query_sims(enc, emb, g['query'])
144
179
  order_max = ba.retrieve_candidates(sims, meta, topk=max_topk)
145
180
  is_entity = ba.looks_like_entity(g['query'])
181
+ cell_results = []
146
182
  for cell in grid:
147
183
  base = order_max[:cell['topk']]
148
184
  gated = cell['entity_gate'] and is_entity
149
- added = (ba.expand_1hop(sims, meta, base, by_base, ghops=cell['ghops'], gmax=cell['gmax'])
150
- if cell['hops'] and base and not gated else [])
185
+ # Gated cells still follow superseded_by (issue #93), matching brain_ask.main().
186
+ added = (ba.expand_1hop(sims, meta, base, by_base, ghops=cell['ghops'], gmax=cell['gmax'],
187
+ only_superseded=gated)
188
+ if cell['hops'] and base else [])
151
189
  scored = ba.rerank_candidates(ce, g['query'], base + added, meta, sims=sims)
152
190
  ranked = [stem_of(i) for i, _ in scored]
191
+ cell_results.append((cell, ranked, gated, added))
192
+ base_ranked = next((r for c, r, _, _ in cell_results if c['name'] == baseline_name), None)
193
+ for cell, ranked, gated, added in cell_results:
153
194
  rows.append({'cell': cell['name'], 'cls': g['cls'],
154
195
  'recall': recall_at(ranked, g['gold']),
155
196
  'mrr': mrr_at(ranked, g['gold']),
156
- 'ndcg': ndcg_at(ranked, g['gold'])})
197
+ 'ndcg': ndcg_at(ranked, g['gold']),
198
+ 'gated': gated, 'hop_applied': bool(added),
199
+ 'rank_changed': base_ranked is not None and ranked != base_ranked})
157
200
  return rows
158
201
 
159
202
 
160
203
  def summarize_grid(rows, grid, classes):
161
- """-> ordered rows of {cell, class, n, recall, mrr, ndcg, delta_ndcg}, one per
162
- (cell, class) plus (cell, 'overall'); delta_ndcg is vs the 0-hop baseline cell
163
- (the grid's first hops=0 cell, else its first cell) for the same class."""
204
+ """-> ordered rows of {cell, class, n, recall, mrr, ndcg, delta_ndcg, gate_rate,
205
+ hop_applied_rate, rank_churn}, one per (cell, class) plus (cell, 'overall');
206
+ delta_ndcg is vs the 0-hop baseline cell (the grid's first hops=0 cell, else its
207
+ first cell) for the same class. gate_rate/hop_applied_rate/rank_churn default to
208
+ 0.0 for rows lacking those keys (older score_grid output, or hand-built rows in a
209
+ caller's own tests)."""
164
210
  baseline = next((c['name'] for c in grid if c['hops'] == 0), grid[0]['name'])
165
211
  by_cell_cls = {}
166
212
  for r in rows:
@@ -169,7 +215,10 @@ def summarize_grid(rows, grid, classes):
169
215
  def agg(rs):
170
216
  n = len(rs)
171
217
  return {'n': n, 'recall': sum(r['recall'] for r in rs) / n,
172
- 'mrr': sum(r['mrr'] for r in rs) / n, 'ndcg': sum(r['ndcg'] for r in rs) / n}
218
+ 'mrr': sum(r['mrr'] for r in rs) / n, 'ndcg': sum(r['ndcg'] for r in rs) / n,
219
+ 'gate_rate': sum(r.get('gated', False) for r in rs) / n,
220
+ 'hop_applied_rate': sum(r.get('hop_applied', False) for r in rs) / n,
221
+ 'rank_churn': sum(r.get('rank_changed', False) for r in rs) / n}
173
222
 
174
223
  out = []
175
224
  for cell in grid:
@@ -187,22 +236,26 @@ def summarize_grid(rows, grid, classes):
187
236
 
188
237
 
189
238
  def format_markdown(summary):
190
- lines = ['| cell | class | n | Recall@12 | MRR | nDCG@12 | delta_nDCG@12 |',
191
- '|---|---|---|---|---|---|---|']
239
+ lines = ['| cell | class | n | Recall@12 | MRR | nDCG@12 | delta_nDCG@12 | gate_rate | hop_applied_rate | rank_churn |',
240
+ '|---|---|---|---|---|---|---|---|---|---|']
192
241
  for r in summary:
193
242
  d = '' if r['delta_ndcg'] is None else '%+.3f' % r['delta_ndcg']
194
- lines.append('| %s | %s | %d | %.3f | %.3f | %.3f | %s |'
195
- % (r['cell'], r['class'], r['n'], r['recall'], r['mrr'], r['ndcg'], d))
243
+ lines.append('| %s | %s | %d | %.3f | %.3f | %.3f | %s | %.3f | %.3f | %.3f |'
244
+ % (r['cell'], r['class'], r['n'], r['recall'], r['mrr'], r['ndcg'], d,
245
+ r['gate_rate'], r['hop_applied_rate'], r['rank_churn']))
196
246
  return '\n'.join(lines)
197
247
 
198
248
 
199
249
  def write_csv(summary, path):
200
250
  with open(path, 'w', newline='', encoding='utf-8') as f:
201
251
  w = csv.writer(f)
202
- w.writerow(['cell', 'class', 'n', 'Recall@12', 'MRR', 'nDCG@12', 'delta_nDCG@12'])
252
+ w.writerow(['cell', 'class', 'n', 'Recall@12', 'MRR', 'nDCG@12', 'delta_nDCG@12',
253
+ 'gate_rate', 'hop_applied_rate', 'rank_churn'])
203
254
  for r in summary:
204
255
  w.writerow([r['cell'], r['class'], r['n'], round(r['recall'], 4), round(r['mrr'], 4),
205
- round(r['ndcg'], 4), '' if r['delta_ndcg'] is None else round(r['delta_ndcg'], 4)])
256
+ round(r['ndcg'], 4), '' if r['delta_ndcg'] is None else round(r['delta_ndcg'], 4),
257
+ round(r['gate_rate'], 4), round(r['hop_applied_rate'], 4),
258
+ round(r['rank_churn'], 4)])
206
259
 
207
260
 
208
261
  def low_n_warnings(summary, small_n=SMALL_N):
@@ -217,6 +270,8 @@ def main():
217
270
  ap.add_argument('--grid', default='default',
218
271
  help="'default', a JSON array of cells, a path to one, or "
219
272
  "';'-separated key=val cells (default: %(default)s)")
273
+ ap.add_argument('--pool', '--topk-retrieve', dest='topk_retrieve', type=int, default=None,
274
+ help='override default dense candidate pool size (topk) for cells that do not set topk')
220
275
  ap.add_argument('--list-grid', action='store_true',
221
276
  help='print the named grid cells and exit (no model/index load)')
222
277
  ap.add_argument('--out', help='output prefix for <prefix>.csv/.md (default: eval/ablation-<ts>)')
@@ -228,7 +283,13 @@ def main():
228
283
  if a.rerank:
229
284
  os.environ['SGM_RERANK'] = '1'
230
285
 
231
- grid = parse_grid(a.grid)
286
+ pool = a.topk_retrieve
287
+ if pool is None:
288
+ pool, _ = ba._parse_pool([])
289
+ elif pool < 1:
290
+ return ap.error('--pool / --topk-retrieve must be >= 1')
291
+
292
+ grid = parse_grid(a.grid, topk_retrieve=pool)
232
293
  if a.list_grid:
233
294
  print_grid(grid)
234
295
  return 0
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "sqlite-graph-memory"
7
- version = "0.3.7"
7
+ version = "0.3.8"
8
8
  description = "Associative memory for LLM agents: Graph RAG over a folder of markdown notes, in one SQLite file, with no server to run."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -21,6 +21,6 @@ the indexer and the reranker will tell you what is missing instead of failing
21
21
  on an ``ImportError`` at startup.
22
22
  """
23
23
 
24
- __version__ = "0.3.7"
24
+ __version__ = "0.3.8"
25
25
 
26
26
  __all__ = ["__version__"]