sqlite-graph-memory 0.3.6__py3-none-any.whl → 0.3.7__py3-none-any.whl
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.
- sqlite_graph_memory/__init__.py +1 -1
- sqlite_graph_memory/brain_ask.py +117 -18
- sqlite_graph_memory/index_notes.py +162 -42
- sqlite_graph_memory/mcp_server.py +1 -1
- sqlite_graph_memory/vault_stats.py +17 -3
- {sqlite_graph_memory-0.3.6.dist-info → sqlite_graph_memory-0.3.7.dist-info}/METADATA +75 -22
- sqlite_graph_memory-0.3.7.dist-info/RECORD +16 -0
- sqlite_graph_memory-0.3.6.dist-info/RECORD +0 -16
- {sqlite_graph_memory-0.3.6.dist-info → sqlite_graph_memory-0.3.7.dist-info}/WHEEL +0 -0
- {sqlite_graph_memory-0.3.6.dist-info → sqlite_graph_memory-0.3.7.dist-info}/entry_points.txt +0 -0
- {sqlite_graph_memory-0.3.6.dist-info → sqlite_graph_memory-0.3.7.dist-info}/licenses/LICENSE +0 -0
sqlite_graph_memory/__init__.py
CHANGED
sqlite_graph_memory/brain_ask.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"""brain_ask.py — vector retrieval + graph expansion + A/B harness over a markdown vault.
|
|
3
3
|
|
|
4
4
|
Pipeline: e5-base dense retrieve (top-60, dedup by file) -> optional 1-hop wikilink
|
|
5
|
-
graph expansion -> cross-encoder rerank -> top-12.
|
|
5
|
+
graph expansion -> dense order (cross-encoder rerank only with --rerank) -> top-12.
|
|
6
6
|
|
|
7
7
|
USAGE:
|
|
8
8
|
python brain_ask.py "question" # vector-only (Direct memory)
|
|
@@ -10,6 +10,7 @@ USAGE:
|
|
|
10
10
|
python brain_ask.py --ab "question" # run BOTH, diff, log to SQLite (ab_recall)
|
|
11
11
|
python brain_ask.py --ask "question" # emit a context bundle for an LLM agent
|
|
12
12
|
python brain_ask.py --ppr --graph "question" # + PageRank lane in the ORDERING (see ppr.py)
|
|
13
|
+
python brain_ask.py --rerank "question" # opt in to the cross-encoder rerank (off by default)
|
|
13
14
|
|
|
14
15
|
Config (env, all optional):
|
|
15
16
|
BRAIN_INDEX_DIR dir holding the embedding index (default: ./index)
|
|
@@ -18,6 +19,9 @@ Config (env, all optional):
|
|
|
18
19
|
BRAIN_AB_JSON if set, --ab also writes a structured JSON diff to this path
|
|
19
20
|
SGM_PPR=1 same as --ppr: fuse personalized PageRank over [[wikilinks]] with the
|
|
20
21
|
reranker by RRF, reranker top 5 protected (off by default)
|
|
22
|
+
SGM_RERANK=1 same as --rerank. Off by default since 0.3.7: the mmarco cross-encoder
|
|
23
|
+
lowered recall on long queries (DolphinBench Riley slice, 1000 sessions:
|
|
24
|
+
R@5 0.61 dense vs 0.48 reranked); it still wins some short title queries.
|
|
21
25
|
SGM_NO_STAR_PROMPT=1 never print the one-time GitHub star line after --ab
|
|
22
26
|
SGM_CONFIG_DIR where that line's once-per-machine marker lives
|
|
23
27
|
(default: $XDG_CONFIG_HOME or ~/.config, /sqlite-graph-memory)
|
|
@@ -159,6 +163,17 @@ def load_index(emb_path=None, meta_path=None):
|
|
|
159
163
|
return emb, meta
|
|
160
164
|
|
|
161
165
|
|
|
166
|
+
FALLBACK_NOTES = [] # filled by _try_onnx, printed at the top of the answer by _with_notes
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _with_notes(text):
|
|
170
|
+
"""Put fallback notes at the top of the answer. Through MCP the agent sees only the
|
|
171
|
+
answer, never stderr, so a silent fallback would hide the slow torch path (#89)."""
|
|
172
|
+
if not FALLBACK_NOTES:
|
|
173
|
+
return text
|
|
174
|
+
return '\n'.join(FALLBACK_NOTES) + '\n\n' + text
|
|
175
|
+
|
|
176
|
+
|
|
162
177
|
def _try_onnx(kind):
|
|
163
178
|
"""The ONNX model, or None to fall back to torch.
|
|
164
179
|
|
|
@@ -177,8 +192,10 @@ def _try_onnx(kind):
|
|
|
177
192
|
import sentence_transformers # noqa: F401
|
|
178
193
|
except ImportError:
|
|
179
194
|
raise exc
|
|
180
|
-
|
|
181
|
-
|
|
195
|
+
why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
|
|
196
|
+
sys.stderr.write('ONNX %s unavailable (%s); using torch\n' % (kind, why))
|
|
197
|
+
FALLBACK_NOTES.append('NOTE: the light ONNX %s failed to load (%s), so this recall ran '
|
|
198
|
+
'on torch and was slower. Run sgm-doctor to see why.' % (kind, why))
|
|
182
199
|
return None
|
|
183
200
|
|
|
184
201
|
|
|
@@ -218,15 +235,78 @@ def retrieve_candidates(sims, meta, topk=TOPK_RETRIEVE):
|
|
|
218
235
|
return order
|
|
219
236
|
|
|
220
237
|
|
|
238
|
+
def _normalize_target(tgt):
|
|
239
|
+
"""Normalize a wikilink target: backslashes to /, strip leading/trailing slashes and .md, lowercase."""
|
|
240
|
+
s = (tgt or '').strip().replace('\\', '/').strip('/')
|
|
241
|
+
if s.lower().endswith('.md'):
|
|
242
|
+
s = s[:-3].strip()
|
|
243
|
+
return s.lower()
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class _BasenameIndex(dict):
|
|
247
|
+
"""Dict mapping lowercase filename stem -> chunk indices, with precomputed vault `root`."""
|
|
248
|
+
__slots__ = ('root',)
|
|
249
|
+
|
|
250
|
+
def __init__(self, *args, root='', **kwargs):
|
|
251
|
+
super().__init__(*args, **kwargs)
|
|
252
|
+
self.root = root
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def vault_root(meta):
|
|
256
|
+
"""Common directory prefix of every chunk path in `meta`, computed once per index."""
|
|
257
|
+
paths = [Path(m['path']).as_posix() for m in meta]
|
|
258
|
+
try:
|
|
259
|
+
root = os.path.commonpath(paths) if len(paths) > 1 else ''
|
|
260
|
+
except ValueError:
|
|
261
|
+
root = ''
|
|
262
|
+
if root and any(p == root for p in paths):
|
|
263
|
+
root = Path(root).parent.as_posix()
|
|
264
|
+
if root == '.':
|
|
265
|
+
root = ''
|
|
266
|
+
return root
|
|
267
|
+
|
|
268
|
+
|
|
221
269
|
def index_by_basename(meta):
|
|
222
270
|
"""basename(no .md) -> meta indices, used to resolve [[wikilink]] targets to chunks."""
|
|
223
|
-
by_base =
|
|
271
|
+
by_base = _BasenameIndex(root=vault_root(meta))
|
|
224
272
|
for j, mm in enumerate(meta):
|
|
225
273
|
by_base.setdefault(Path(mm['path']).stem.lower(), []).append(j)
|
|
226
274
|
return by_base
|
|
227
275
|
|
|
228
276
|
|
|
229
|
-
def
|
|
277
|
+
def _resolve_target_chunks(tgt, by_base, meta, root=None):
|
|
278
|
+
"""Resolve a wikilink target (`[[name]]`, `[[name.md]]`, or `[[folder/name]]`) to chunk indices.
|
|
279
|
+
|
|
280
|
+
For folder-qualified targets (`/` in normalized target), prefers exact vault-relative path
|
|
281
|
+
matches (`sub/c`) before falling back to deeper path-suffix matches (`other/sub/c`), matching
|
|
282
|
+
`vault_stats.build_graph`.
|
|
283
|
+
"""
|
|
284
|
+
norm = _normalize_target(tgt)
|
|
285
|
+
if not norm:
|
|
286
|
+
return []
|
|
287
|
+
if '/' not in norm:
|
|
288
|
+
return by_base.get(norm, [])
|
|
289
|
+
stem = norm.rsplit('/', 1)[-1]
|
|
290
|
+
cands = by_base.get(stem, [])
|
|
291
|
+
if not cands:
|
|
292
|
+
return []
|
|
293
|
+
if root is None:
|
|
294
|
+
root = getattr(by_base, 'root', None)
|
|
295
|
+
if root is None:
|
|
296
|
+
root = vault_root(meta)
|
|
297
|
+
exact, suffix_matches = [], []
|
|
298
|
+
suffix = '/' + norm
|
|
299
|
+
for j in cands:
|
|
300
|
+
p = Path(meta[j]['path']).with_suffix('').as_posix()
|
|
301
|
+
rel = p[len(root):].lstrip('/').lower() if (root and p.startswith(root)) else p.lstrip('/').lower()
|
|
302
|
+
if rel == norm or p.lstrip('/').lower() == norm:
|
|
303
|
+
exact.append(j)
|
|
304
|
+
elif ('/' + rel).endswith(suffix) or ('/' + p.lower()).endswith(suffix):
|
|
305
|
+
suffix_matches.append(j)
|
|
306
|
+
return exact if exact else suffix_matches
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX, root=None):
|
|
230
310
|
"""Follow 1-hop OUTGOING wikilinks from the top vector hits and return the neighbour
|
|
231
311
|
chunks to ADD to the candidate set; the reranker decides whether they are relevant.
|
|
232
312
|
|
|
@@ -236,10 +316,14 @@ def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX):
|
|
|
236
316
|
if not base_order: return added
|
|
237
317
|
try:
|
|
238
318
|
by_base = by_base or index_by_basename(meta)
|
|
319
|
+
if root is None:
|
|
320
|
+
root = getattr(by_base, 'root', None)
|
|
321
|
+
if root is None:
|
|
322
|
+
root = vault_root(meta)
|
|
239
323
|
in_order = set(base_order)
|
|
240
324
|
for i in base_order[:ghops]:
|
|
241
325
|
for tgt in _links_in(meta[i]['path']):
|
|
242
|
-
idxs =
|
|
326
|
+
idxs = _resolve_target_chunks(tgt, by_base, meta, root=root)
|
|
243
327
|
if not idxs: continue
|
|
244
328
|
best = max(idxs, key=lambda j: sims[j]) # best chunk of neighbour for THIS query
|
|
245
329
|
if best in in_order: continue
|
|
@@ -252,11 +336,25 @@ def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX):
|
|
|
252
336
|
return added
|
|
253
337
|
|
|
254
338
|
|
|
255
|
-
def
|
|
256
|
-
"""
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
339
|
+
def rerank_enabled(env=None, argv=None):
|
|
340
|
+
"""True when the cross-encoder rerank is asked for (--rerank or SGM_RERANK=1). Default off."""
|
|
341
|
+
env = os.environ if env is None else env
|
|
342
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
343
|
+
return '--rerank' in argv or str(env.get('SGM_RERANK', '')).strip() == '1'
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def rerank_candidates(ce, query, cand, meta, topn=TOPN, sims=None):
|
|
347
|
+
"""Order candidate chunks -> [(chunk index, score)], best first.
|
|
348
|
+
ce=None (the default) keeps the dense e5 similarity from `sims`; a cross-encoder `ce`
|
|
349
|
+
rescores (query, title + snippet) pairs instead.
|
|
350
|
+
topn=None returns the whole list (the PPR fusion needs the tail)."""
|
|
351
|
+
if ce is None:
|
|
352
|
+
if sims is None:
|
|
353
|
+
raise ValueError('rerank_candidates: pass sims= when no cross-encoder is loaded')
|
|
354
|
+
sc = [float(sims[i]) for i in cand]
|
|
355
|
+
else:
|
|
356
|
+
pairs = [(query, meta[i]['title'] + '. ' + meta[i]['snippet']) for i in cand]
|
|
357
|
+
sc = ce.predict(pairs) if len(pairs) else []
|
|
260
358
|
return sorted(zip(cand, sc), key=lambda x: -x[1])[:topn]
|
|
261
359
|
|
|
262
360
|
|
|
@@ -359,7 +457,7 @@ def main():
|
|
|
359
457
|
return
|
|
360
458
|
ask = '--ask' in args
|
|
361
459
|
graph = '--graph' in args; ab = '--ab' in args
|
|
362
|
-
flags = {'--ask', '--graph', '--ab', '--ppr'}
|
|
460
|
+
flags = {'--ask', '--graph', '--ab', '--ppr', '--rerank'}
|
|
363
461
|
query = ' '.join(a for a in args if a not in flags)
|
|
364
462
|
if not query or not EMB.exists():
|
|
365
463
|
sys.stderr.write('need an embedding index (%s) and a query — run index_notes.py first\n' % EMB)
|
|
@@ -398,12 +496,12 @@ def main():
|
|
|
398
496
|
elif order and ('--ppr' in args or ppr_enabled()):
|
|
399
497
|
ppr_stems = ppr_lane(meta, sims, base_order)
|
|
400
498
|
|
|
401
|
-
#
|
|
402
|
-
ce = load_reranker(dev)
|
|
499
|
+
# dense order by default; the cross-encoder runs only when asked (--rerank / SGM_RERANK=1)
|
|
500
|
+
ce = load_reranker(dev) if rerank_enabled(argv=args) else None
|
|
403
501
|
def rerank(cand):
|
|
404
502
|
if not ppr_stems:
|
|
405
|
-
return rerank_candidates(ce, query, cand, meta)
|
|
406
|
-
full = rerank_candidates(ce, query, cand, meta, topn=None) # fusion needs the tail
|
|
503
|
+
return rerank_candidates(ce, query, cand, meta, sims=sims)
|
|
504
|
+
full = rerank_candidates(ce, query, cand, meta, topn=None, sims=sims) # fusion needs the tail
|
|
407
505
|
return fuse_ppr(full, meta, ppr_stems, TOPN)
|
|
408
506
|
|
|
409
507
|
# --ab: run BOTH paths in ONE process, diff, log. Answers "does graph REALLY help?"
|
|
@@ -456,6 +554,7 @@ def main():
|
|
|
456
554
|
except Exception:
|
|
457
555
|
pass
|
|
458
556
|
_out = Path(os.getenv('BRAIN_ANSWER_OUT', '_brain_answer.txt'))
|
|
557
|
+
text = _with_notes(text)
|
|
459
558
|
_out.write_text(text, encoding='utf-8'); print(text)
|
|
460
559
|
maybe_star_prompt()
|
|
461
560
|
return
|
|
@@ -467,7 +566,7 @@ def main():
|
|
|
467
566
|
order = graph_order if (graph and not gated) else base_order
|
|
468
567
|
reranked = rerank(order)
|
|
469
568
|
scope = 'all' + (' /graph+%d' % len(graph_set) if graph else '') + (' /ppr' if ppr_stems else '')
|
|
470
|
-
lines = [f'QUERY: {query}', f'(scope={scope}; e5 {len(order)} files -> rerank; {len(meta)} chunks)', '']
|
|
569
|
+
lines = [f'QUERY: {query}', f'(scope={scope}; e5 {len(order)} files -> {"rerank" if ce is not None else "dense"}; {len(meta)} chunks)', '']
|
|
471
570
|
if ask:
|
|
472
571
|
lines.append('=== CONTEXT BUNDLE (paste to your agent) ===\n')
|
|
473
572
|
for i, sc in reranked[:8]:
|
|
@@ -481,7 +580,7 @@ def main():
|
|
|
481
580
|
lines.append("%2d. [rr=%6.2f] [%s] %s%s" % (rank, float(sc), m.get('date', ''), m['title'], gmark))
|
|
482
581
|
lines.append(" %s" % m['snippet'][:140])
|
|
483
582
|
_out = Path(os.getenv('BRAIN_ANSWER_OUT', '_brain_answer.txt'))
|
|
484
|
-
_out.write_text('\n'.join(lines), encoding='utf-8')
|
|
583
|
+
_out.write_text(_with_notes('\n'.join(lines)), encoding='utf-8')
|
|
485
584
|
print(f'{len(reranked)} hits (scope={scope}) -> {_out}')
|
|
486
585
|
|
|
487
586
|
|
|
@@ -2,21 +2,28 @@
|
|
|
2
2
|
"""index_notes.py — minimal embedding indexer for a folder of markdown notes.
|
|
3
3
|
|
|
4
4
|
Builds the dense index that brain_ask.py retrieves from:
|
|
5
|
-
index/_brain_e5.npy
|
|
6
|
-
index/_brain_e5_meta.pkl
|
|
5
|
+
index/_brain_e5.npy float32 matrix, one row per chunk (L2-normalized)
|
|
6
|
+
index/_brain_e5_meta.pkl list of dicts: {path, title, snippet, date}
|
|
7
|
+
index/_brain_e5_manifest.json {path: {size, mtime, hash}} + a settings fingerprint
|
|
7
8
|
|
|
8
9
|
Chunking is deliberately simple (fixed-size windows over the note body) — the
|
|
9
10
|
cross-encoder reranker downstream forgives coarse chunk boundaries.
|
|
10
11
|
|
|
12
|
+
Re-running only re-embeds notes that are new or changed since the manifest was
|
|
13
|
+
written (size + mtime fast path, content sha256 truth); unchanged notes keep
|
|
14
|
+
their existing rows, and deleted notes lose theirs. Pass --full (or delete/corrupt
|
|
15
|
+
the manifest, or change one of the chunking settings below) to force a complete
|
|
16
|
+
rebuild.
|
|
17
|
+
|
|
11
18
|
USAGE:
|
|
12
|
-
python index_notes.py <notes_dir>
|
|
19
|
+
python index_notes.py <notes_dir> [--full]
|
|
13
20
|
Config (env, optional):
|
|
14
21
|
BRAIN_INDEX_DIR output dir (default: ./index)
|
|
15
22
|
BRAIN_INDEX_HIDDEN 1 = also index dot-files and dot-directories (default:
|
|
16
23
|
skip them, so .draft.md, .stversions/.obsidian/.git and
|
|
17
24
|
Syncthing conflict copies never enter the index)
|
|
18
25
|
"""
|
|
19
|
-
import os, re, sys, pickle
|
|
26
|
+
import argparse, hashlib, json, os, re, sys, pickle
|
|
20
27
|
from pathlib import Path
|
|
21
28
|
import numpy as np
|
|
22
29
|
|
|
@@ -27,8 +34,6 @@ SNIPPET_CHARS = 600
|
|
|
27
34
|
|
|
28
35
|
FM_RX = re.compile(r'^---\r?\n(.*?)\r?\n---\r?\n', re.S)
|
|
29
36
|
|
|
30
|
-
|
|
31
|
-
|
|
32
37
|
try:
|
|
33
38
|
from sqlite_graph_memory import brain_ask as _ba
|
|
34
39
|
except ImportError: # run as a loose script next to brain_ask.py
|
|
@@ -51,6 +56,7 @@ def _require_sentence_transformers():
|
|
|
51
56
|
raise SystemExit(_EMBEDDINGS_HINT) from exc
|
|
52
57
|
return sentence_transformers
|
|
53
58
|
|
|
59
|
+
|
|
54
60
|
def chunks_of(text):
|
|
55
61
|
step = CHUNK_CHARS - CHUNK_OVERLAP
|
|
56
62
|
for start in range(0, max(len(text), 1), step):
|
|
@@ -106,54 +112,168 @@ def read_note(path):
|
|
|
106
112
|
return None
|
|
107
113
|
|
|
108
114
|
|
|
115
|
+
def _file_hash(path):
|
|
116
|
+
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _settings_fingerprint():
|
|
120
|
+
return {'E5_MODEL': E5_MODEL, 'CHUNK_CHARS': CHUNK_CHARS,
|
|
121
|
+
'CHUNK_OVERLAP': CHUNK_OVERLAP, 'SNIPPET_CHARS': SNIPPET_CHARS}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _chunk_note(p):
|
|
125
|
+
"""-> (meta dicts, 'passage: '-prefixed texts) for one note's chunks."""
|
|
126
|
+
t = read_note(p)
|
|
127
|
+
if t is None:
|
|
128
|
+
return [], []
|
|
129
|
+
m = FM_RX.match(t)
|
|
130
|
+
fm = m.group(1) if m else ''
|
|
131
|
+
body = t[m.end():] if m else t
|
|
132
|
+
date = fm_date(fm)
|
|
133
|
+
title = p.stem
|
|
134
|
+
meta, texts = [], []
|
|
135
|
+
for c in chunks_of(body):
|
|
136
|
+
meta.append({'path': str(p), 'title': title,
|
|
137
|
+
'snippet': c[:SNIPPET_CHARS], 'date': date})
|
|
138
|
+
texts.append('passage: ' + c) # e5 expects the passage: prefix
|
|
139
|
+
return meta, texts
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _embed(encoder, texts):
|
|
143
|
+
"""encoder.encode(texts) if it has one, else encoder(texts); lazily loads
|
|
144
|
+
the default model via brain_ask.load_encoder() only when encoder is None,
|
|
145
|
+
and only when texts is non-empty (so an unchanged re-run never touches
|
|
146
|
+
the embedding stack)."""
|
|
147
|
+
if encoder is None:
|
|
148
|
+
encoder = _ba.load_encoder()
|
|
149
|
+
return np.asarray(
|
|
150
|
+
encoder.encode(texts, normalize_embeddings=True, convert_to_numpy=True,
|
|
151
|
+
batch_size=64, show_progress_bar=True),
|
|
152
|
+
dtype='float32',
|
|
153
|
+
)
|
|
154
|
+
result = encoder.encode(texts) if hasattr(encoder, 'encode') else encoder(texts)
|
|
155
|
+
return np.asarray(result, dtype='float32')
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def build_index(notes_dir, out_dir=None, encoder=None, full=False):
|
|
159
|
+
"""Index ``notes_dir`` into ``out_dir`` (default ``./index``).
|
|
160
|
+
|
|
161
|
+
Re-embeds only notes that are new or changed since the manifest was last
|
|
162
|
+
written; unchanged notes keep their rows, deleted notes lose theirs.
|
|
163
|
+
``full=True`` (or --full on the CLI) forces a complete rebuild, as does a
|
|
164
|
+
missing/corrupt manifest/index or a changed chunking setting.
|
|
165
|
+
``encoder``, when given, is called as ``encoder.encode(texts)`` or
|
|
166
|
+
``encoder(texts)`` — inject a fake in tests so no model ever loads.
|
|
167
|
+
Returns {'chunks': int, 'files': int, 'new_texts': int}.
|
|
168
|
+
"""
|
|
169
|
+
notes_dir = Path(notes_dir)
|
|
170
|
+
out_dir = Path(out_dir) if out_dir is not None else Path('index')
|
|
171
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
172
|
+
|
|
173
|
+
emb_path = out_dir / '_brain_e5.npy'
|
|
174
|
+
meta_path = out_dir / '_brain_e5_meta.pkl'
|
|
175
|
+
manifest_path = out_dir / '_brain_e5_manifest.json'
|
|
176
|
+
settings = _settings_fingerprint()
|
|
177
|
+
|
|
178
|
+
notes = iter_notes(notes_dir)
|
|
179
|
+
|
|
180
|
+
do_full = full
|
|
181
|
+
old_meta, old_emb, old_files = [], None, {}
|
|
182
|
+
if not do_full:
|
|
183
|
+
try:
|
|
184
|
+
manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
|
|
185
|
+
if not isinstance(manifest, dict) or not isinstance(manifest.get('files'), dict):
|
|
186
|
+
raise ValueError('manifest is not {settings, files: {...}}')
|
|
187
|
+
if manifest.get('settings') != settings:
|
|
188
|
+
do_full = True
|
|
189
|
+
else:
|
|
190
|
+
old_files = manifest['files']
|
|
191
|
+
if not all(isinstance(v, dict) for v in old_files.values()):
|
|
192
|
+
raise ValueError('manifest file record is not a dict')
|
|
193
|
+
old_meta = pickle.loads(meta_path.read_bytes())
|
|
194
|
+
old_emb = np.load(emb_path)
|
|
195
|
+
if (not isinstance(old_meta, list) or old_emb.ndim != 2
|
|
196
|
+
or old_emb.shape[0] != len(old_meta)):
|
|
197
|
+
raise ValueError('index/meta row count mismatch')
|
|
198
|
+
except Exception:
|
|
199
|
+
do_full = True
|
|
200
|
+
|
|
201
|
+
current_files = {}
|
|
202
|
+
for p in notes:
|
|
203
|
+
key = str(p)
|
|
204
|
+
st = p.stat()
|
|
205
|
+
prev = old_files.get(key) if not do_full else None
|
|
206
|
+
if (isinstance(prev, dict)
|
|
207
|
+
and prev.get('size') == st.st_size
|
|
208
|
+
and prev.get('mtime') == st.st_mtime
|
|
209
|
+
and isinstance(prev.get('hash'), str)
|
|
210
|
+
and prev.get('hash')):
|
|
211
|
+
file_hash = prev['hash']
|
|
212
|
+
else:
|
|
213
|
+
file_hash = _file_hash(p)
|
|
214
|
+
current_files[key] = {'size': st.st_size, 'mtime': st.st_mtime, 'hash': file_hash}
|
|
215
|
+
|
|
216
|
+
if do_full:
|
|
217
|
+
old_meta, old_emb, old_files = [], None, {}
|
|
218
|
+
changed_or_new = set(current_files)
|
|
219
|
+
else:
|
|
220
|
+
unchanged = {path for path, info in current_files.items()
|
|
221
|
+
if old_files.get(path, {}).get('hash') == info['hash']}
|
|
222
|
+
changed_or_new = set(current_files) - unchanged
|
|
223
|
+
kept_mask = [m['path'] in unchanged for m in old_meta]
|
|
224
|
+
old_meta = [m for m, keep in zip(old_meta, kept_mask) if keep]
|
|
225
|
+
old_emb = old_emb[np.array(kept_mask, dtype=bool)] if old_emb is not None else None
|
|
226
|
+
|
|
227
|
+
new_meta, new_texts = [], []
|
|
228
|
+
for p in notes:
|
|
229
|
+
if str(p) in changed_or_new:
|
|
230
|
+
m, t = _chunk_note(p)
|
|
231
|
+
new_meta.extend(m)
|
|
232
|
+
new_texts.extend(t)
|
|
233
|
+
|
|
234
|
+
new_emb = _embed(encoder, new_texts) if new_texts else None
|
|
235
|
+
|
|
236
|
+
meta = old_meta + new_meta
|
|
237
|
+
if old_emb is not None and new_emb is not None:
|
|
238
|
+
emb = np.vstack([old_emb, new_emb]).astype('float32')
|
|
239
|
+
elif new_emb is not None:
|
|
240
|
+
emb = new_emb.astype('float32')
|
|
241
|
+
elif old_emb is not None:
|
|
242
|
+
emb = old_emb.astype('float32')
|
|
243
|
+
else:
|
|
244
|
+
emb = np.zeros((0, 0), dtype='float32')
|
|
245
|
+
|
|
246
|
+
np.save(emb_path, emb)
|
|
247
|
+
meta_path.write_bytes(pickle.dumps(meta))
|
|
248
|
+
manifest_path.write_text(json.dumps({'settings': settings, 'files': current_files}, indent=2),
|
|
249
|
+
encoding='utf-8')
|
|
250
|
+
|
|
251
|
+
files = len({m['path'] for m in meta})
|
|
252
|
+
return {'chunks': len(meta), 'files': files, 'new_texts': len(new_texts)}
|
|
253
|
+
|
|
254
|
+
|
|
109
255
|
def main():
|
|
110
|
-
|
|
256
|
+
ap = argparse.ArgumentParser(add_help=False)
|
|
257
|
+
ap.add_argument('notes_dir', nargs='?')
|
|
258
|
+
ap.add_argument('--full', action='store_true',
|
|
259
|
+
help='force a complete rebuild, ignoring the manifest')
|
|
260
|
+
args = ap.parse_args()
|
|
261
|
+
if not args.notes_dir:
|
|
111
262
|
print(__doc__); return
|
|
112
|
-
notes_dir = Path(
|
|
263
|
+
notes_dir = Path(args.notes_dir)
|
|
113
264
|
out_dir = Path(os.getenv('BRAIN_INDEX_DIR', 'index'))
|
|
114
|
-
out_dir.mkdir(parents=True, exist_ok=True)
|
|
115
265
|
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
t = read_note(p)
|
|
119
|
-
if t is None:
|
|
120
|
-
continue
|
|
121
|
-
m = FM_RX.match(t)
|
|
122
|
-
fm = m.group(1) if m else ''
|
|
123
|
-
body = t[m.end():] if m else t
|
|
124
|
-
date = fm_date(fm)
|
|
125
|
-
title = p.stem
|
|
126
|
-
for c in chunks_of(body):
|
|
127
|
-
meta.append({'path': str(p), 'title': title,
|
|
128
|
-
'snippet': c[:SNIPPET_CHARS], 'date': date})
|
|
129
|
-
texts.append('passage: ' + c) # e5 expects the passage: prefix
|
|
130
|
-
if not texts:
|
|
266
|
+
result = build_index(notes_dir, out_dir=out_dir, full=args.full)
|
|
267
|
+
if result['chunks'] == 0:
|
|
131
268
|
print('no indexable .md notes found under', notes_dir); return
|
|
132
|
-
|
|
133
269
|
if _ba.backend() == 'onnx':
|
|
134
|
-
enc = _ba.load_encoder()
|
|
135
270
|
# Fetch the reranker too: otherwise the first recall from an MCP client is also
|
|
136
271
|
# a ~470 MB download and runs into the client's tool timeout.
|
|
137
272
|
try:
|
|
138
273
|
_ba._onnx().prefetch()
|
|
139
274
|
except Exception as exc: # offline: the first recall fetches it instead
|
|
140
275
|
print('reranker not prefetched (%s); the first recall will fetch it' % type(exc).__name__)
|
|
141
|
-
|
|
142
|
-
_require_sentence_transformers()
|
|
143
|
-
from sentence_transformers import SentenceTransformer
|
|
144
|
-
try:
|
|
145
|
-
import torch
|
|
146
|
-
dev = 'cuda' if torch.cuda.is_available() else 'cpu'
|
|
147
|
-
except Exception:
|
|
148
|
-
dev = 'cpu'
|
|
149
|
-
enc = SentenceTransformer(E5_MODEL, device=dev)
|
|
150
|
-
emb = enc.encode(texts, normalize_embeddings=True, convert_to_numpy=True,
|
|
151
|
-
batch_size=64, show_progress_bar=True).astype('float32')
|
|
152
|
-
|
|
153
|
-
np.save(out_dir / '_brain_e5.npy', emb)
|
|
154
|
-
(out_dir / '_brain_e5_meta.pkl').write_bytes(pickle.dumps(meta))
|
|
155
|
-
files = len({m['path'] for m in meta})
|
|
156
|
-
print('indexed %d chunks from %d files -> %s' % (len(meta), files, out_dir))
|
|
276
|
+
print('indexed %d chunks from %d files -> %s' % (result['chunks'], result['files'], out_dir))
|
|
157
277
|
|
|
158
278
|
|
|
159
279
|
if __name__ == '__main__':
|
|
@@ -70,7 +70,7 @@ TOOLS = [
|
|
|
70
70
|
"description": (
|
|
71
71
|
"Associative memory recall over linked markdown notes. "
|
|
72
72
|
"Retrieves relevant context using vector search, 1-hop [[wikilink]] graph expansion, "
|
|
73
|
-
"
|
|
73
|
+
"ordered by dense similarity (cross-encoder rerank is opt-in). Returns a formatted context bundle."
|
|
74
74
|
),
|
|
75
75
|
"inputSchema": {
|
|
76
76
|
"type": "object",
|
|
@@ -36,7 +36,7 @@ from collections import defaultdict
|
|
|
36
36
|
from pathlib import Path
|
|
37
37
|
|
|
38
38
|
from sqlite_graph_memory import __version__
|
|
39
|
-
from sqlite_graph_memory.brain_ask import _links_in
|
|
39
|
+
from sqlite_graph_memory.brain_ask import _links_in, _normalize_target
|
|
40
40
|
from sqlite_graph_memory.index_notes import FM_RX, iter_notes, read_note
|
|
41
41
|
|
|
42
42
|
DEFAULTS = {
|
|
@@ -61,15 +61,29 @@ def build_graph(notes_dir):
|
|
|
61
61
|
"""(pages, edges): pages = {relative path without .md: Path},
|
|
62
62
|
edges = {(src, dst)} between real pages."""
|
|
63
63
|
root = Path(notes_dir)
|
|
64
|
-
pages, by_stem = {}, defaultdict(list)
|
|
64
|
+
pages, by_path, by_stem = {}, defaultdict(list), defaultdict(list)
|
|
65
65
|
for p in iter_notes(root):
|
|
66
66
|
key = p.relative_to(root).with_suffix('').as_posix()
|
|
67
67
|
pages[key] = p
|
|
68
|
+
by_path[key.lower()].append(key)
|
|
68
69
|
by_stem[p.stem.lower()].append(key)
|
|
69
70
|
edges = set()
|
|
70
71
|
for src, path in pages.items():
|
|
71
72
|
for tgt in _links_in(path):
|
|
72
|
-
|
|
73
|
+
norm = _normalize_target(tgt)
|
|
74
|
+
if not norm:
|
|
75
|
+
continue
|
|
76
|
+
if '/' in norm:
|
|
77
|
+
dsts = by_path.get(norm, ())
|
|
78
|
+
if not dsts:
|
|
79
|
+
suffix = '/' + norm
|
|
80
|
+
dsts = [
|
|
81
|
+
k for k in by_stem.get(norm.rsplit('/', 1)[-1], ())
|
|
82
|
+
if ('/' + k.lower()).endswith(suffix)
|
|
83
|
+
]
|
|
84
|
+
else:
|
|
85
|
+
dsts = by_stem.get(norm, ())
|
|
86
|
+
for dst in dsts:
|
|
73
87
|
if dst != src:
|
|
74
88
|
edges.add((src, dst))
|
|
75
89
|
return pages, edges
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: sqlite-graph-memory
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.7
|
|
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
|
|
@@ -78,9 +78,13 @@ Already using your own agent rules and projects? The [Russian existing-setup gui
|
|
|
78
78
|
Build the index once (any folder of markdown; [`uv`](https://docs.astral.sh/uv/) gives you `uvx`):
|
|
79
79
|
|
|
80
80
|
```bash
|
|
81
|
-
BRAIN_INDEX_DIR=$HOME/.sgm-index uvx --from 'sqlite-graph-memory[
|
|
81
|
+
BRAIN_INDEX_DIR=$HOME/.sgm-index uvx --python 3.12 --from 'sqlite-graph-memory[lite]' sgm-index ~/notes
|
|
82
82
|
```
|
|
83
83
|
|
|
84
|
+
`--python 3.12` is deliberate. onnxruntime has no wheels for Python 3.14 on an Intel Mac, or on
|
|
85
|
+
Apple Silicon below macOS 14. On such a machine an unpinned `uvx` falls back to release 0.3.5,
|
|
86
|
+
which has no `[lite]`, and `sgm-index` then stops and asks for `[embeddings]`.
|
|
87
|
+
|
|
84
88
|
Then point your client at the server. Use the absolute path of that index folder.
|
|
85
89
|
|
|
86
90
|
**Cold-start timeout (0.3.5 and later).** The MCP server starts recall in a separate process with a default deadline of 180 seconds; a first call on a clean Windows install took 89 s, which the old fixed 60 s always cut off. Override with `BRAIN_RECALL_TIMEOUT` (integer seconds, 1 to 600; invalid values return an error). Your MCP client's own tool timeout must also allow the longer call. On 0.3.3 and earlier the deadline is a fixed 60 s: upgrade, or use `sgm-ask --ask` directly, and do not report MCP recall as verified merely because the CLI works.
|
|
@@ -88,7 +92,7 @@ Then point your client at the server. Use the absolute path of that index folder
|
|
|
88
92
|
**Claude Code**
|
|
89
93
|
|
|
90
94
|
```bash
|
|
91
|
-
claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --with 'sqlite-graph-memory[
|
|
95
|
+
claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --python 3.12 --with 'sqlite-graph-memory[lite]' sqlite-graph-memory
|
|
92
96
|
```
|
|
93
97
|
|
|
94
98
|
**Cursor** (`~/.cursor/mcp.json`; Claude Desktop, Zed and Windsurf take the same `mcpServers` block)
|
|
@@ -98,7 +102,7 @@ claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --
|
|
|
98
102
|
"mcpServers": {
|
|
99
103
|
"sqlite-graph-memory": {
|
|
100
104
|
"command": "uvx",
|
|
101
|
-
"args": ["--with", "sqlite-graph-memory[
|
|
105
|
+
"args": ["--python", "3.12", "--with", "sqlite-graph-memory[lite]", "sqlite-graph-memory"],
|
|
102
106
|
"env": { "BRAIN_INDEX_DIR": "/absolute/path/to/.sgm-index" }
|
|
103
107
|
}
|
|
104
108
|
}
|
|
@@ -113,7 +117,7 @@ claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --
|
|
|
113
117
|
"sqlite-graph-memory": {
|
|
114
118
|
"type": "stdio",
|
|
115
119
|
"command": "uvx",
|
|
116
|
-
"args": ["--with", "sqlite-graph-memory[
|
|
120
|
+
"args": ["--python", "3.12", "--with", "sqlite-graph-memory[lite]", "sqlite-graph-memory"],
|
|
117
121
|
"env": { "BRAIN_INDEX_DIR": "/absolute/path/to/.sgm-index" }
|
|
118
122
|
}
|
|
119
123
|
}
|
|
@@ -125,31 +129,37 @@ claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --
|
|
|
125
129
|
```toml
|
|
126
130
|
[mcp_servers.sqlite-graph-memory]
|
|
127
131
|
command = "uvx"
|
|
128
|
-
args = ["--with", "sqlite-graph-memory[
|
|
132
|
+
args = ["--python", "3.12", "--with", "sqlite-graph-memory[lite]", "sqlite-graph-memory"]
|
|
129
133
|
env = { BRAIN_INDEX_DIR = "/absolute/path/to/.sgm-index" }
|
|
130
134
|
```
|
|
131
135
|
|
|
132
136
|
Size, `du -sh` of a fresh Python 3.12 venv on an x86_64 Mac (1 Nov 2026): the base install is
|
|
133
137
|
26 MB and has no torch (numpy only, enough for the graph half and the SQLite ledger);
|
|
134
|
-
with `[embeddings]` (torch) it is 879 MB, 540 MB of that torch 2.2.2 CPU. With `[lite]
|
|
138
|
+
with `[embeddings]` (torch) it is 879 MB, 540 MB of that torch 2.2.2 CPU. With `[lite]`,
|
|
135
139
|
the same two models on ONNX Runtime and no torch, it is 155 MB (Windows, Python 3.12,
|
|
136
140
|
3 Nov 2026), installs in 12 s, and one MCP recall on the 202-note bench vault took 7.0 s
|
|
137
141
|
against 33.8 s through torch on the same machine, with the same top hits and scores.
|
|
138
142
|
`[lite]` is picked automatically when installed; `SGM_BACKEND=torch` forces torch (for a GPU).
|
|
139
143
|
An index built by either backend is searched correctly by the other.
|
|
140
|
-
Already installed with pip? Replace `uvx --with ... sqlite-graph-memory` by `sgm-mcp`
|
|
144
|
+
Already installed with pip? Replace `uvx --python 3.12 --with ... sqlite-graph-memory` by `sgm-mcp`
|
|
141
145
|
([`examples/mcp-config.json`](examples/mcp-config.json)). Agents that read files first:
|
|
142
146
|
[`llms.txt`](llms.txt).
|
|
143
147
|
|
|
144
148
|
## Three commands
|
|
145
149
|
|
|
146
150
|
```bash
|
|
147
|
-
pip install 'sqlite-graph-memory[
|
|
151
|
+
pip install 'sqlite-graph-memory[lite]'
|
|
148
152
|
sgm-index ./notes
|
|
149
153
|
sgm-ask --ab "In which programming language is the tool behind Project Ouzel written?"
|
|
150
154
|
```
|
|
151
155
|
|
|
152
|
-
|
|
156
|
+
On an Intel Mac, use Python 3.12 with `pip install`. On a newer Python it can quietly install 0.3.5, which has no `[lite]`.
|
|
157
|
+
|
|
158
|
+
`./notes` is any folder of markdown notes. Re-running `sgm-index` only re-embeds notes
|
|
159
|
+
that are new or changed since the last run (tracked by a manifest next to the index);
|
|
160
|
+
pass `--full` to force a complete rebuild.
|
|
161
|
+
|
|
162
|
+
To get exactly the output below, use the
|
|
153
163
|
202-note synthetic vault from this repo (it is not inside the pip package):
|
|
154
164
|
|
|
155
165
|
```bash
|
|
@@ -191,8 +201,9 @@ exists so you can measure which one wins on your own notes.
|
|
|
191
201
|
|
|
192
202
|
Graph RAG on SQLite for AI agents — a working pilot, not a framework. It is the extracted
|
|
193
203
|
memory layer of a personal "second brain" agent setup: vector search finds the entry
|
|
194
|
-
points, the `[[wikilinks]]` you already wrote by hand are the graph, and
|
|
195
|
-
|
|
204
|
+
points, the `[[wikilinks]]` you already wrote by hand are the graph, and dense similarity
|
|
205
|
+
orders what the hop dragged in (a cross-encoder rerank is opt-in with `--rerank`; see below
|
|
206
|
+
for why it is no longer the default).
|
|
196
207
|
SQLite is the only database ([`schema.sql`](src/sqlite_graph_memory/schema.sql)).
|
|
197
208
|
|
|
198
209
|
Status: **pilot**, and the word is load-bearing: it runs daily in one real setup (an index of ~28k curated notes, ~93k chunks, rebuilt nightly from a ~270k-file
|
|
@@ -215,12 +226,14 @@ For a single-user agent over a markdown knowledge base, all three are overkill:
|
|
|
215
226
|
- **SQLite is enough** — the only things worth persisting are derived state (a per-turn
|
|
216
227
|
ledger) and telemetry, and both are defined in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
|
|
217
228
|
One file, stdlib driver, zero ops.
|
|
218
|
-
-
|
|
219
|
-
|
|
229
|
+
- **Measure before adding a stage.** The pilot shipped a cross-encoder reranker from day one;
|
|
230
|
+
measured later, it lowered recall on long queries (our 184-question gold set: body nDCG@12
|
|
231
|
+
0.640 reranked vs 0.815 dense; DolphinBench Riley slice, 1000 sessions: R@5 0.48 vs 0.61).
|
|
232
|
+
Since 0.3.7 it is off by default and stays available as `--rerank` / `SGM_RERANK=1`.
|
|
220
233
|
|
|
221
234
|
So the pilot's bet: *vector retrieval for entry points, hand-curated wikilinks for
|
|
222
|
-
association,
|
|
223
|
-
|
|
235
|
+
association, SQLite for everything that must persist.* All steps live in one file,
|
|
236
|
+
`brain_ask.py`, in that order.
|
|
224
237
|
|
|
225
238
|
## Architecture
|
|
226
239
|
|
|
@@ -234,7 +247,8 @@ markdown notes (with [[wikilinks]])
|
|
|
234
247
|
├── brain_ask.py recall pipeline:
|
|
235
248
|
│ 1. dense retrieve top-60 chunks, dedup by file
|
|
236
249
|
│ 2. --graph +1-hop wikilink neighbours of top-15 hits (max 40)
|
|
237
|
-
│ 3.
|
|
250
|
+
│ 3. order dense similarity → top-12
|
|
251
|
+
│ (--rerank: cross-encoder instead, opt-in)
|
|
238
252
|
│ 4. --ab run vector-only AND vector+graph, diff,
|
|
239
253
|
│ log the delta to SQLite (ab_recall)
|
|
240
254
|
│
|
|
@@ -253,7 +267,7 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
253
267
|
### Design choices that survived contact with reality
|
|
254
268
|
|
|
255
269
|
- **Graph expansion is candidate generation, not ranking** (`brain_ask.py`). Neighbours go
|
|
256
|
-
into the same
|
|
270
|
+
into the same ranking pool as vector hits, so an irrelevant linked note gets buried.
|
|
257
271
|
That is what makes 1-hop expansion safe to leave on.
|
|
258
272
|
- **Entity gate** (`looks_like_entity` in `brain_ask.py`). A/B telemetry showed graph
|
|
259
273
|
expansion helps *theme* queries ("approaches to agent memory") but hurts *name/tool*
|
|
@@ -272,7 +286,7 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
272
286
|
|
|
273
287
|
- No entity lane. The production setup has an extra retrieval lane over people/project
|
|
274
288
|
cards; it is too entangled with personal data to publish.
|
|
275
|
-
-
|
|
289
|
+
- Packaging exists since v0.3.0 (`pip install sqlite-graph-memory`). There IS an eval suite now — see
|
|
276
290
|
[Measure before you swap](#measure-before-you-swap--eval) — but it scores retrieval on
|
|
277
291
|
wikilink-derived gold, which is weak supervision and says so out loud. Test coverage is uneven:
|
|
278
292
|
`index_notes.py`, `brain_ask.py` and `mcp_server.py` have unit tests, and
|
|
@@ -285,9 +299,9 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
285
299
|
|
|
286
300
|
```bash
|
|
287
301
|
# Indexing and reranking need an embedding stack; the base install leaves it out.
|
|
288
|
-
# [lite]
|
|
302
|
+
# [lite] runs the models on ONNX Runtime without torch (~155 MB); [embeddings]
|
|
289
303
|
# brings torch (~2 GB) if you want a GPU. Ask for one explicitly:
|
|
290
|
-
pip install 'sqlite-graph-memory[
|
|
304
|
+
pip install 'sqlite-graph-memory[lite]'
|
|
291
305
|
|
|
292
306
|
# 1. index a folder of markdown notes
|
|
293
307
|
sgm-index /path/to/notes
|
|
@@ -311,7 +325,7 @@ To enable the per-turn ledger in Claude Code, register the Stop hook (the exact
|
|
|
311
325
|
sgm-turnstate-show --stats
|
|
312
326
|
```
|
|
313
327
|
|
|
314
|
-
Working from a clone instead of an install? `pip install -e '.[
|
|
328
|
+
Working from a clone instead of an install? `pip install -e '.[lite]'` gives you the
|
|
315
329
|
same four commands, and the modules stay importable as
|
|
316
330
|
`from sqlite_graph_memory import brain_ask`.
|
|
317
331
|
|
|
@@ -412,6 +426,45 @@ is what runs. An eval that re-implements the pipeline measures the re-implementa
|
|
|
412
426
|
`--sqlite` appends one row per class and mode to a `gold_eval` table, which is how a run six
|
|
413
427
|
weeks from now can be diffed against today's.
|
|
414
428
|
|
|
429
|
+
### Sweeping the graph-expansion knobs — `eval/run_ablation.py`
|
|
430
|
+
|
|
431
|
+
`run_eval.py` scores one configuration at a time (`vector` vs `graph`). `run_ablation.py`
|
|
432
|
+
sweeps a grid of pipeline parameters — whether the 1-hop graph expansion runs at all
|
|
433
|
+
(`hops`), how many top hits seed it (`ghops`), how many neighbours it admits (`gmax`), the
|
|
434
|
+
dense-retrieve pool size (`topk`), and whether entity/name-shaped queries skip the hop
|
|
435
|
+
(`entity_gate`) — against the **same gold file**, in one run, reusing `brain_ask.py` and
|
|
436
|
+
`run_eval.py`'s own metrics so the sweep can't drift from what `sgm-ask` actually does:
|
|
437
|
+
|
|
438
|
+
```bash
|
|
439
|
+
python eval/run_ablation.py --list-grid # cells only, no model/index load
|
|
440
|
+
python eval/run_ablation.py --gold eval/gold-<today>.jsonl # the built-in 10-cell default grid
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
Each dense embedding is computed once per question and reused across every cell (a cell's
|
|
444
|
+
candidate pool is a slice of the widest pool asked for, not a re-retrieve); only the
|
|
445
|
+
cross-encoder rerank runs per `(question, cell)`, since the candidate set changes per cell.
|
|
446
|
+
The report — printed as a Markdown table and written as both `<prefix>.md` and `<prefix>.csv`
|
|
447
|
+
(`--out <prefix>`, or `--csv`/`--md` directly) — breaks down `n`, `Recall@12`, `MRR`, `nDCG@12`
|
|
448
|
+
and `delta_nDCG@12` (vs the grid's `0-hop` baseline) per `(cell, class)` and `overall`, and
|
|
449
|
+
warns explicitly whenever a class has fewer than 20 questions. The built-in `default`
|
|
450
|
+
10-cell grid varies **one axis at a time** against `1-hop` (`ghops=15, gmax=40, topk=60,
|
|
451
|
+
entity_gate=on`) rather than a full Cartesian product; `--grid` takes `default`, a
|
|
452
|
+
`';'`-separated `key=val` cell list (e.g. `--grid "hops=0;hops=1,ghops=30,gmax=80"` to test
|
|
453
|
+
multi-axis interactions), or a JSON array of cell dicts.
|
|
454
|
+
|
|
455
|
+
Sample run (`intfloat/multilingual-e5-base` + `cross-encoder/mmarco-mMiniLMv2-L12-H384-v1` on CPU) over a 5-note synthetic mini-vault (`12` questions: `5` title, `5` body, `1` bridge, `1` temporal) with `--grid "hops=0,topk=3;hops=1,ghops=2,gmax=5,topk=3,entity_gate=on;hops=1,ghops=2,gmax=5,topk=3,entity_gate=off"`:
|
|
456
|
+
|
|
457
|
+
| cell | class | n | Recall@12 | MRR | nDCG@12 | delta_nDCG@12 |
|
|
458
|
+
|---|---|---:|---:|---:|---:|---:|
|
|
459
|
+
| `cell-0` (`hops=0, topk=3`) | bridge | 1 | 0.500 | 0.500 | 0.387 | +0.000 |
|
|
460
|
+
| `cell-0` (`hops=0, topk=3`) | overall | 12 | 0.958 | 0.903 | 0.907 | +0.000 |
|
|
461
|
+
| `cell-1` (`hops=1, ghops=2, gmax=5, topk=3, gate=on`) | bridge | 1 | 1.000 | 0.500 | 0.693 | +0.307 |
|
|
462
|
+
| `cell-1` (`hops=1, ghops=2, gmax=5, topk=3, gate=on`) | overall | 12 | 1.000 | 0.903 | 0.933 | +0.026 |
|
|
463
|
+
| `cell-2` (`hops=1, ghops=2, gmax=5, topk=3, gate=off`) | bridge | 1 | 1.000 | 0.500 | 0.693 | +0.307 |
|
|
464
|
+
| `cell-2` (`hops=1, ghops=2, gmax=5, topk=3, gate=off`) | overall | 12 | 1.000 | 0.903 | 0.933 | +0.026 |
|
|
465
|
+
|
|
466
|
+
When `topk` is smaller than the vault (`topk=3 < 5` notes), 1-hop `[[wikilink]]` expansion (`cell-1`, `cell-2`) lifts `bridge` Recall@12 from `0.500` to `1.000` (`+0.307` nDCG@12, `+0.026` overall) without regressing `title`, `body`, or `temporal`. On the default 10-cell grid (`topk=20..80 > 5` notes), every cell scores identically (`overall` Recall@12 `1.000`, nDCG@12 `0.929`, `delta_nDCG@12 = +0.000`) because dense retrieval already admits the entire mini-vault before the graph hop runs.
|
|
467
|
+
|
|
415
468
|
### What it cost us to find out
|
|
416
469
|
|
|
417
470
|
Numbers from the home vault (~24k chunks, RU+EN, 2026-09-16), one frozen gold set of 184
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
sqlite_graph_memory/__init__.py,sha256=k3Jab-cnKnZpQ2RoYkXY57NDDrtKZJZ9AXegsm09LhA,1151
|
|
2
|
+
sqlite_graph_memory/brain_ask.py,sha256=ri60NrgRSVcAj89sLVmpGZBmfgJmAWq-p4VwOvyzHV8,26008
|
|
3
|
+
sqlite_graph_memory/doctor.py,sha256=fOHoCV7XdDfYNIb3-tpa6sJtwzKBSH-EhsTpA0uQ9Qo,6005
|
|
4
|
+
sqlite_graph_memory/index_notes.py,sha256=yhlpdAhi9mGBSdiE2xJI3soMT4s12A15XZX37ZIIU88,10958
|
|
5
|
+
sqlite_graph_memory/mcp_server.py,sha256=Oza1UFA0V8OEhDbFrHDYdexbxwnq99N1xbTTjhmAhss,10251
|
|
6
|
+
sqlite_graph_memory/onnx_backend.py,sha256=1P4sy5LrI_j4dgB-taFoakrDbn2JQIQnnmOuH7bA0ZM,5377
|
|
7
|
+
sqlite_graph_memory/ppr.py,sha256=L7VSAiliXr8j3PH2hQqKbdgm08BPm6pZkLcckoMxAro,10001
|
|
8
|
+
sqlite_graph_memory/schema.sql,sha256=8aySXKw3Azaxyzqbd76mKTfOaDP7FlpkLXtgwA8ZVK4,2543
|
|
9
|
+
sqlite_graph_memory/turnstate_hook.py,sha256=fypGmUcHQkzlRN74tvIG07lr9uAXpp2GjetqthkuMc8,8641
|
|
10
|
+
sqlite_graph_memory/turnstate_show.py,sha256=Bij4POJNSbJunHwGgm4i2NzkJQms8QBpR0mM9VVeKy4,3251
|
|
11
|
+
sqlite_graph_memory/vault_stats.py,sha256=zlJm1b7HTiYIpZe8_7OUM-ywszeQjsQrj8zvkqnuI5w,9496
|
|
12
|
+
sqlite_graph_memory-0.3.7.dist-info/METADATA,sha256=x3ENDEHqZwJjrBG9mPzlyNHf5mKI7uerOL_EIjl87wQ,41619
|
|
13
|
+
sqlite_graph_memory-0.3.7.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
+
sqlite_graph_memory-0.3.7.dist-info/entry_points.txt,sha256=lpoCm-jNjhBEtcQ16iIUd0ivr92Gr4c_fSRls2Zvbb0,432
|
|
15
|
+
sqlite_graph_memory-0.3.7.dist-info/licenses/LICENSE,sha256=p88nZdrfMUiES3_MpUEwhGmqz2hQFpyMh0k0cqdpfU8,1082
|
|
16
|
+
sqlite_graph_memory-0.3.7.dist-info/RECORD,,
|
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
sqlite_graph_memory/__init__.py,sha256=tp1bvR_lAMB3gg3_28p4sOADUAqsFBg15rCsyvoZ2WI,1151
|
|
2
|
-
sqlite_graph_memory/brain_ask.py,sha256=1CsBMtYeVSXdEXimS2xasAUvcuhXDxdLYE7w8uu0of0,21710
|
|
3
|
-
sqlite_graph_memory/doctor.py,sha256=fOHoCV7XdDfYNIb3-tpa6sJtwzKBSH-EhsTpA0uQ9Qo,6005
|
|
4
|
-
sqlite_graph_memory/index_notes.py,sha256=6SdRXKVyOp9QPmBnyb2Sj98pIcqmnhZgqF9MWA4EJcY,5794
|
|
5
|
-
sqlite_graph_memory/mcp_server.py,sha256=GItrJrtU34lGzamSD1ryEfL-Aq46W_J-4eDBZ3Pr_Wo,10218
|
|
6
|
-
sqlite_graph_memory/onnx_backend.py,sha256=1P4sy5LrI_j4dgB-taFoakrDbn2JQIQnnmOuH7bA0ZM,5377
|
|
7
|
-
sqlite_graph_memory/ppr.py,sha256=L7VSAiliXr8j3PH2hQqKbdgm08BPm6pZkLcckoMxAro,10001
|
|
8
|
-
sqlite_graph_memory/schema.sql,sha256=8aySXKw3Azaxyzqbd76mKTfOaDP7FlpkLXtgwA8ZVK4,2543
|
|
9
|
-
sqlite_graph_memory/turnstate_hook.py,sha256=fypGmUcHQkzlRN74tvIG07lr9uAXpp2GjetqthkuMc8,8641
|
|
10
|
-
sqlite_graph_memory/turnstate_show.py,sha256=Bij4POJNSbJunHwGgm4i2NzkJQms8QBpR0mM9VVeKy4,3251
|
|
11
|
-
sqlite_graph_memory/vault_stats.py,sha256=qYU-uzH_W4ME4Qf71UQrExb91cgyTEnjBJDqzwyh0e0,8946
|
|
12
|
-
sqlite_graph_memory-0.3.6.dist-info/METADATA,sha256=1Ev-QC7Ld4y0cd6UTqg3fdBGGGT3OpQChFDwbL3tPOM,37431
|
|
13
|
-
sqlite_graph_memory-0.3.6.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
-
sqlite_graph_memory-0.3.6.dist-info/entry_points.txt,sha256=lpoCm-jNjhBEtcQ16iIUd0ivr92Gr4c_fSRls2Zvbb0,432
|
|
15
|
-
sqlite_graph_memory-0.3.6.dist-info/licenses/LICENSE,sha256=p88nZdrfMUiES3_MpUEwhGmqz2hQFpyMh0k0cqdpfU8,1082
|
|
16
|
-
sqlite_graph_memory-0.3.6.dist-info/RECORD,,
|
|
File without changes
|
{sqlite_graph_memory-0.3.6.dist-info → sqlite_graph_memory-0.3.7.dist-info}/entry_points.txt
RENAMED
|
File without changes
|
{sqlite_graph_memory-0.3.6.dist-info → sqlite_graph_memory-0.3.7.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|