sqlite-graph-memory 0.3.6__py3-none-any.whl → 0.3.8__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 +204 -22
- 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.8.dist-info}/METADATA +77 -22
- sqlite_graph_memory-0.3.8.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.8.dist-info}/WHEEL +0 -0
- {sqlite_graph_memory-0.3.6.dist-info → sqlite_graph_memory-0.3.8.dist-info}/entry_points.txt +0 -0
- {sqlite_graph_memory-0.3.6.dist-info → sqlite_graph_memory-0.3.8.dist-info}/licenses/LICENSE +0 -0
sqlite_graph_memory/__init__.py
CHANGED
sqlite_graph_memory/brain_ask.py
CHANGED
|
@@ -2,22 +2,28 @@
|
|
|
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)
|
|
9
9
|
python brain_ask.py --graph "question" # vector + graph expansion (Associative)
|
|
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
|
+
python brain_ask.py --pool 15 --graph "q" # override dense candidate pool size (default: 60)
|
|
12
13
|
python brain_ask.py --ppr --graph "question" # + PageRank lane in the ORDERING (see ppr.py)
|
|
14
|
+
python brain_ask.py --rerank "question" # opt in to the cross-encoder rerank (off by default)
|
|
13
15
|
|
|
14
16
|
Config (env, all optional):
|
|
15
17
|
BRAIN_INDEX_DIR dir holding the embedding index (default: ./index)
|
|
18
|
+
BRAIN_TOPK_RETRIEVE dense candidate pool size before rerank (default: 60; CLI --pool overrides)
|
|
16
19
|
TURNSTATE_DB SQLite db for A/B telemetry (default: ./turnstate.db)
|
|
17
20
|
BRAIN_ANSWER_OUT file to mirror the answer into (default: ./_brain_answer.txt)
|
|
18
21
|
BRAIN_AB_JSON if set, --ab also writes a structured JSON diff to this path
|
|
19
22
|
SGM_PPR=1 same as --ppr: fuse personalized PageRank over [[wikilinks]] with the
|
|
20
23
|
reranker by RRF, reranker top 5 protected (off by default)
|
|
24
|
+
SGM_RERANK=1 same as --rerank. Off by default since 0.3.7: the mmarco cross-encoder
|
|
25
|
+
lowered recall on long queries (DolphinBench Riley slice, 1000 sessions:
|
|
26
|
+
R@5 0.61 dense vs 0.48 reranked); it still wins some short title queries.
|
|
21
27
|
SGM_NO_STAR_PROMPT=1 never print the one-time GitHub star line after --ab
|
|
22
28
|
SGM_CONFIG_DIR where that line's once-per-machine marker lives
|
|
23
29
|
(default: $XDG_CONFIG_HOME or ~/.config, /sqlite-graph-memory)
|
|
@@ -146,6 +152,31 @@ def _links_in(path):
|
|
|
146
152
|
return [m.strip() for m in WIKILINK_RX.findall(t)]
|
|
147
153
|
|
|
148
154
|
|
|
155
|
+
FRONTMATTER_RX = re.compile(r'^---\r?\n(.*?)\r?\n---', re.DOTALL)
|
|
156
|
+
SUPERSEDED_BY_RX = re.compile(r'^superseded_by\s*:\s*"?(.+?)"?\s*$', re.MULTILINE)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _superseded_links_in(path):
|
|
160
|
+
"""The `superseded_by` TARGET(s) from a note's YAML frontmatter (issue #93).
|
|
161
|
+
|
|
162
|
+
Followed regardless of the entity gate: a query that trips looks_like_entity()
|
|
163
|
+
still needs to reach the replacement of an outdated note, even though general
|
|
164
|
+
wikilink expansion is gated off for that query."""
|
|
165
|
+
try: t = Path(path).read_text(encoding='utf-8', errors='ignore')
|
|
166
|
+
except Exception: return []
|
|
167
|
+
fm = FRONTMATTER_RX.match(t)
|
|
168
|
+
if not fm:
|
|
169
|
+
return []
|
|
170
|
+
m = SUPERSEDED_BY_RX.search(fm.group(1))
|
|
171
|
+
if not m:
|
|
172
|
+
return []
|
|
173
|
+
val = m.group(1).strip().strip('"').strip("'").strip()
|
|
174
|
+
if not val:
|
|
175
|
+
return []
|
|
176
|
+
links = [l.strip() for l in WIKILINK_RX.findall(val) if l.strip()]
|
|
177
|
+
return links if links else [val]
|
|
178
|
+
|
|
179
|
+
|
|
149
180
|
|
|
150
181
|
# --------------------------------------------------------------------------- pipeline
|
|
151
182
|
# The retrieval pipeline lives in these functions so that anything measuring it
|
|
@@ -159,6 +190,17 @@ def load_index(emb_path=None, meta_path=None):
|
|
|
159
190
|
return emb, meta
|
|
160
191
|
|
|
161
192
|
|
|
193
|
+
FALLBACK_NOTES = [] # filled by _try_onnx, printed at the top of the answer by _with_notes
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _with_notes(text):
|
|
197
|
+
"""Put fallback notes at the top of the answer. Through MCP the agent sees only the
|
|
198
|
+
answer, never stderr, so a silent fallback would hide the slow torch path (#89)."""
|
|
199
|
+
if not FALLBACK_NOTES:
|
|
200
|
+
return text
|
|
201
|
+
return '\n'.join(FALLBACK_NOTES) + '\n\n' + text
|
|
202
|
+
|
|
203
|
+
|
|
162
204
|
def _try_onnx(kind):
|
|
163
205
|
"""The ONNX model, or None to fall back to torch.
|
|
164
206
|
|
|
@@ -177,8 +219,10 @@ def _try_onnx(kind):
|
|
|
177
219
|
import sentence_transformers # noqa: F401
|
|
178
220
|
except ImportError:
|
|
179
221
|
raise exc
|
|
180
|
-
|
|
181
|
-
|
|
222
|
+
why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
|
|
223
|
+
sys.stderr.write('ONNX %s unavailable (%s); using torch\n' % (kind, why))
|
|
224
|
+
FALLBACK_NOTES.append('NOTE: the light ONNX %s failed to load (%s), so this recall ran '
|
|
225
|
+
'on torch and was slower. Run sgm-doctor to see why.' % (kind, why))
|
|
182
226
|
return None
|
|
183
227
|
|
|
184
228
|
|
|
@@ -218,28 +262,101 @@ def retrieve_candidates(sims, meta, topk=TOPK_RETRIEVE):
|
|
|
218
262
|
return order
|
|
219
263
|
|
|
220
264
|
|
|
265
|
+
def _normalize_target(tgt):
|
|
266
|
+
"""Normalize a wikilink target: backslashes to /, strip leading/trailing slashes and .md, lowercase."""
|
|
267
|
+
s = (tgt or '').strip().replace('\\', '/').strip('/')
|
|
268
|
+
if s.lower().endswith('.md'):
|
|
269
|
+
s = s[:-3].strip()
|
|
270
|
+
return s.lower()
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class _BasenameIndex(dict):
|
|
274
|
+
"""Dict mapping lowercase filename stem -> chunk indices, with precomputed vault `root`."""
|
|
275
|
+
__slots__ = ('root',)
|
|
276
|
+
|
|
277
|
+
def __init__(self, *args, root='', **kwargs):
|
|
278
|
+
super().__init__(*args, **kwargs)
|
|
279
|
+
self.root = root
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def vault_root(meta):
|
|
283
|
+
"""Common directory prefix of every chunk path in `meta`, computed once per index."""
|
|
284
|
+
paths = [Path(m['path']).as_posix() for m in meta]
|
|
285
|
+
try:
|
|
286
|
+
root = os.path.commonpath(paths) if len(paths) > 1 else ''
|
|
287
|
+
except ValueError:
|
|
288
|
+
root = ''
|
|
289
|
+
if root and any(p == root for p in paths):
|
|
290
|
+
root = Path(root).parent.as_posix()
|
|
291
|
+
if root == '.':
|
|
292
|
+
root = ''
|
|
293
|
+
return root
|
|
294
|
+
|
|
295
|
+
|
|
221
296
|
def index_by_basename(meta):
|
|
222
297
|
"""basename(no .md) -> meta indices, used to resolve [[wikilink]] targets to chunks."""
|
|
223
|
-
by_base =
|
|
298
|
+
by_base = _BasenameIndex(root=vault_root(meta))
|
|
224
299
|
for j, mm in enumerate(meta):
|
|
225
300
|
by_base.setdefault(Path(mm['path']).stem.lower(), []).append(j)
|
|
226
301
|
return by_base
|
|
227
302
|
|
|
228
303
|
|
|
229
|
-
def
|
|
304
|
+
def _resolve_target_chunks(tgt, by_base, meta, root=None):
|
|
305
|
+
"""Resolve a wikilink target (`[[name]]`, `[[name.md]]`, or `[[folder/name]]`) to chunk indices.
|
|
306
|
+
|
|
307
|
+
For folder-qualified targets (`/` in normalized target), prefers exact vault-relative path
|
|
308
|
+
matches (`sub/c`) before falling back to deeper path-suffix matches (`other/sub/c`), matching
|
|
309
|
+
`vault_stats.build_graph`.
|
|
310
|
+
"""
|
|
311
|
+
norm = _normalize_target(tgt)
|
|
312
|
+
if not norm:
|
|
313
|
+
return []
|
|
314
|
+
if '/' not in norm:
|
|
315
|
+
return by_base.get(norm, [])
|
|
316
|
+
stem = norm.rsplit('/', 1)[-1]
|
|
317
|
+
cands = by_base.get(stem, [])
|
|
318
|
+
if not cands:
|
|
319
|
+
return []
|
|
320
|
+
if root is None:
|
|
321
|
+
root = getattr(by_base, 'root', None)
|
|
322
|
+
if root is None:
|
|
323
|
+
root = vault_root(meta)
|
|
324
|
+
exact, suffix_matches = [], []
|
|
325
|
+
suffix = '/' + norm
|
|
326
|
+
for j in cands:
|
|
327
|
+
p = Path(meta[j]['path']).with_suffix('').as_posix()
|
|
328
|
+
rel = p[len(root):].lstrip('/').lower() if (root and p.startswith(root)) else p.lstrip('/').lower()
|
|
329
|
+
if rel == norm or p.lstrip('/').lower() == norm:
|
|
330
|
+
exact.append(j)
|
|
331
|
+
elif ('/' + rel).endswith(suffix) or ('/' + p.lower()).endswith(suffix):
|
|
332
|
+
suffix_matches.append(j)
|
|
333
|
+
return exact if exact else suffix_matches
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX, root=None,
|
|
337
|
+
only_superseded=False):
|
|
230
338
|
"""Follow 1-hop OUTGOING wikilinks from the top vector hits and return the neighbour
|
|
231
339
|
chunks to ADD to the candidate set; the reranker decides whether they are relevant.
|
|
232
340
|
|
|
341
|
+
only_superseded=True follows only a note's superseded_by frontmatter target instead
|
|
342
|
+
of every wikilink (issue #93): the entity gate uses this to still reach a replacement
|
|
343
|
+
note while leaving general wikilink expansion gated off.
|
|
344
|
+
|
|
233
345
|
Bounded by ghops/gmax. CRASH-SAFETY: any failure returns [] and the caller degrades to
|
|
234
346
|
vector-only -- worst case you get the old result, never an empty or broken recall."""
|
|
235
347
|
added = []
|
|
236
348
|
if not base_order: return added
|
|
237
349
|
try:
|
|
238
350
|
by_base = by_base or index_by_basename(meta)
|
|
351
|
+
if root is None:
|
|
352
|
+
root = getattr(by_base, 'root', None)
|
|
353
|
+
if root is None:
|
|
354
|
+
root = vault_root(meta)
|
|
239
355
|
in_order = set(base_order)
|
|
240
356
|
for i in base_order[:ghops]:
|
|
241
|
-
|
|
242
|
-
|
|
357
|
+
targets = _superseded_links_in(meta[i]['path']) if only_superseded else _links_in(meta[i]['path'])
|
|
358
|
+
for tgt in targets:
|
|
359
|
+
idxs = _resolve_target_chunks(tgt, by_base, meta, root=root)
|
|
243
360
|
if not idxs: continue
|
|
244
361
|
best = max(idxs, key=lambda j: sims[j]) # best chunk of neighbour for THIS query
|
|
245
362
|
if best in in_order: continue
|
|
@@ -252,11 +369,25 @@ def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX):
|
|
|
252
369
|
return added
|
|
253
370
|
|
|
254
371
|
|
|
255
|
-
def
|
|
256
|
-
"""
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
372
|
+
def rerank_enabled(env=None, argv=None):
|
|
373
|
+
"""True when the cross-encoder rerank is asked for (--rerank or SGM_RERANK=1). Default off."""
|
|
374
|
+
env = os.environ if env is None else env
|
|
375
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
376
|
+
return '--rerank' in argv or str(env.get('SGM_RERANK', '')).strip() == '1'
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def rerank_candidates(ce, query, cand, meta, topn=TOPN, sims=None):
|
|
380
|
+
"""Order candidate chunks -> [(chunk index, score)], best first.
|
|
381
|
+
ce=None (the default) keeps the dense e5 similarity from `sims`; a cross-encoder `ce`
|
|
382
|
+
rescores (query, title + snippet) pairs instead.
|
|
383
|
+
topn=None returns the whole list (the PPR fusion needs the tail)."""
|
|
384
|
+
if ce is None:
|
|
385
|
+
if sims is None:
|
|
386
|
+
raise ValueError('rerank_candidates: pass sims= when no cross-encoder is loaded')
|
|
387
|
+
sc = [float(sims[i]) for i in cand]
|
|
388
|
+
else:
|
|
389
|
+
pairs = [(query, meta[i]['title'] + '. ' + meta[i]['snippet']) for i in cand]
|
|
390
|
+
sc = ce.predict(pairs) if len(pairs) else []
|
|
260
391
|
return sorted(zip(cand, sc), key=lambda x: -x[1])[:topn]
|
|
261
392
|
|
|
262
393
|
|
|
@@ -351,15 +482,59 @@ def maybe_star_prompt(stream=None, env=None, interactive=None):
|
|
|
351
482
|
return False
|
|
352
483
|
|
|
353
484
|
|
|
485
|
+
def _parse_pool(args, env=None):
|
|
486
|
+
"""Extract optional `--pool N` / `--topk-retrieve N` (or BRAIN_TOPK_RETRIEVE) -> (int|None, remaining_args)."""
|
|
487
|
+
env = os.environ if env is None else env
|
|
488
|
+
pool = None
|
|
489
|
+
env_val = (env.get('BRAIN_TOPK_RETRIEVE') or '').strip()
|
|
490
|
+
if env_val:
|
|
491
|
+
try:
|
|
492
|
+
pool = int(env_val)
|
|
493
|
+
except ValueError as exc:
|
|
494
|
+
sys.stderr.write('invalid BRAIN_TOPK_RETRIEVE=%r (expected positive integer)\n' % env_val)
|
|
495
|
+
raise SystemExit(2) from exc
|
|
496
|
+
if pool < 1:
|
|
497
|
+
sys.stderr.write('invalid BRAIN_TOPK_RETRIEVE=%r (must be >= 1)\n' % env_val)
|
|
498
|
+
raise SystemExit(2)
|
|
499
|
+
rest = []
|
|
500
|
+
i = 0
|
|
501
|
+
while i < len(args):
|
|
502
|
+
a = args[i]
|
|
503
|
+
if a in ('--pool', '--topk-retrieve'):
|
|
504
|
+
if i + 1 >= len(args):
|
|
505
|
+
sys.stderr.write('%s requires a positive integer argument\n' % a)
|
|
506
|
+
raise SystemExit(2)
|
|
507
|
+
raw = args[i + 1]
|
|
508
|
+
i += 2
|
|
509
|
+
elif a.startswith('--pool=') or a.startswith('--topk-retrieve='):
|
|
510
|
+
flag, _, raw = a.partition('=')
|
|
511
|
+
a = flag
|
|
512
|
+
i += 1
|
|
513
|
+
else:
|
|
514
|
+
rest.append(a)
|
|
515
|
+
i += 1
|
|
516
|
+
continue
|
|
517
|
+
try:
|
|
518
|
+
pool = int(raw)
|
|
519
|
+
except ValueError as exc:
|
|
520
|
+
sys.stderr.write('invalid %s value %r (expected positive integer)\n' % (a, raw))
|
|
521
|
+
raise SystemExit(2) from exc
|
|
522
|
+
if pool < 1:
|
|
523
|
+
sys.stderr.write('invalid %s value %r (must be >= 1)\n' % (a, raw))
|
|
524
|
+
raise SystemExit(2)
|
|
525
|
+
return pool, rest
|
|
526
|
+
|
|
527
|
+
|
|
354
528
|
def main():
|
|
355
529
|
args = sys.argv[1:]
|
|
356
530
|
if '--version' in args:
|
|
357
531
|
from sqlite_graph_memory import __version__
|
|
358
532
|
print('sgm-ask %s' % __version__)
|
|
359
533
|
return
|
|
534
|
+
pool, args = _parse_pool(args)
|
|
360
535
|
ask = '--ask' in args
|
|
361
536
|
graph = '--graph' in args; ab = '--ab' in args
|
|
362
|
-
flags = {'--ask', '--graph', '--ab', '--ppr'}
|
|
537
|
+
flags = {'--ask', '--graph', '--ab', '--ppr', '--rerank'}
|
|
363
538
|
query = ' '.join(a for a in args if a not in flags)
|
|
364
539
|
if not query or not EMB.exists():
|
|
365
540
|
sys.stderr.write('need an embedding index (%s) and a query — run index_notes.py first\n' % EMB)
|
|
@@ -373,7 +548,7 @@ def main():
|
|
|
373
548
|
sims = query_sims(enc, emb, query)
|
|
374
549
|
|
|
375
550
|
# dense retrieve -> dedup by path (best chunk per file) -> top-K unique files
|
|
376
|
-
order = retrieve_candidates(sims, meta)
|
|
551
|
+
order = retrieve_candidates(sims, meta) if pool is None else retrieve_candidates(sims, meta, topk=pool)
|
|
377
552
|
|
|
378
553
|
# Graph expansion: follow 1-hop OUTGOING wikilinks from the top vector hits, pull in
|
|
379
554
|
# those neighbour notes (resolved to already-indexed chunks), then let the reranker
|
|
@@ -398,12 +573,12 @@ def main():
|
|
|
398
573
|
elif order and ('--ppr' in args or ppr_enabled()):
|
|
399
574
|
ppr_stems = ppr_lane(meta, sims, base_order)
|
|
400
575
|
|
|
401
|
-
#
|
|
402
|
-
ce = load_reranker(dev)
|
|
576
|
+
# dense order by default; the cross-encoder runs only when asked (--rerank / SGM_RERANK=1)
|
|
577
|
+
ce = load_reranker(dev) if rerank_enabled(argv=args) else None
|
|
403
578
|
def rerank(cand):
|
|
404
579
|
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
|
|
580
|
+
return rerank_candidates(ce, query, cand, meta, sims=sims)
|
|
581
|
+
full = rerank_candidates(ce, query, cand, meta, topn=None, sims=sims) # fusion needs the tail
|
|
407
582
|
return fuse_ppr(full, meta, ppr_stems, TOPN)
|
|
408
583
|
|
|
409
584
|
# --ab: run BOTH paths in ONE process, diff, log. Answers "does graph REALLY help?"
|
|
@@ -456,18 +631,25 @@ def main():
|
|
|
456
631
|
except Exception:
|
|
457
632
|
pass
|
|
458
633
|
_out = Path(os.getenv('BRAIN_ANSWER_OUT', '_brain_answer.txt'))
|
|
634
|
+
text = _with_notes(text)
|
|
459
635
|
_out.write_text(text, encoding='utf-8'); print(text)
|
|
460
636
|
maybe_star_prompt()
|
|
461
637
|
return
|
|
462
638
|
|
|
463
639
|
# GATE: wiki-graph helps THEME queries, hurts ENTITY/name queries -> skip graph for entities.
|
|
640
|
+
# Exception (issue #93): a superseded_by target still resolves even when gated, so an
|
|
641
|
+
# outdated note's replacement isn't dropped just because the query looks entity-like.
|
|
464
642
|
gated = graph and looks_like_entity(query)
|
|
465
643
|
if gated:
|
|
466
|
-
sys.stderr.write("wiki-graph gated OFF (entity-like query) -> Direct only\n")
|
|
467
|
-
|
|
644
|
+
sys.stderr.write("wiki-graph gated OFF (entity-like query) -> Direct only, except superseded_by\n")
|
|
645
|
+
sup_added = expand_1hop(sims, meta, base_order, only_superseded=True)
|
|
646
|
+
order = base_order + sup_added
|
|
647
|
+
graph_set = set(sup_added)
|
|
648
|
+
else:
|
|
649
|
+
order = graph_order if graph else base_order
|
|
468
650
|
reranked = rerank(order)
|
|
469
651
|
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)', '']
|
|
652
|
+
lines = [f'QUERY: {query}', f'(scope={scope}; e5 {len(order)} files -> {"rerank" if ce is not None else "dense"}; {len(meta)} chunks)', '']
|
|
471
653
|
if ask:
|
|
472
654
|
lines.append('=== CONTEXT BUNDLE (paste to your agent) ===\n')
|
|
473
655
|
for i, sc in reranked[:8]:
|
|
@@ -481,7 +663,7 @@ def main():
|
|
|
481
663
|
lines.append("%2d. [rr=%6.2f] [%s] %s%s" % (rank, float(sc), m.get('date', ''), m['title'], gmark))
|
|
482
664
|
lines.append(" %s" % m['snippet'][:140])
|
|
483
665
|
_out = Path(os.getenv('BRAIN_ANSWER_OUT', '_brain_answer.txt'))
|
|
484
|
-
_out.write_text('\n'.join(lines), encoding='utf-8')
|
|
666
|
+
_out.write_text(_with_notes('\n'.join(lines)), encoding='utf-8')
|
|
485
667
|
print(f'{len(reranked)} hits (scope={scope}) -> {_out}')
|
|
486
668
|
|
|
487
669
|
|
|
@@ -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.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
|

|
|
66
68
|
|
|
67
69
|
**Your agent forgets everything between sessions, and plain vector search gives it back
|
|
@@ -78,9 +80,13 @@ Already using your own agent rules and projects? The [Russian existing-setup gui
|
|
|
78
80
|
Build the index once (any folder of markdown; [`uv`](https://docs.astral.sh/uv/) gives you `uvx`):
|
|
79
81
|
|
|
80
82
|
```bash
|
|
81
|
-
BRAIN_INDEX_DIR=$HOME/.sgm-index uvx --from 'sqlite-graph-memory[
|
|
83
|
+
BRAIN_INDEX_DIR=$HOME/.sgm-index uvx --python 3.12 --from 'sqlite-graph-memory[lite]' sgm-index ~/notes
|
|
82
84
|
```
|
|
83
85
|
|
|
86
|
+
`--python 3.12` is deliberate. onnxruntime has no wheels for Python 3.14 on an Intel Mac, or on
|
|
87
|
+
Apple Silicon below macOS 14. On such a machine an unpinned `uvx` falls back to release 0.3.5,
|
|
88
|
+
which has no `[lite]`, and `sgm-index` then stops and asks for `[embeddings]`.
|
|
89
|
+
|
|
84
90
|
Then point your client at the server. Use the absolute path of that index folder.
|
|
85
91
|
|
|
86
92
|
**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 +94,7 @@ Then point your client at the server. Use the absolute path of that index folder
|
|
|
88
94
|
**Claude Code**
|
|
89
95
|
|
|
90
96
|
```bash
|
|
91
|
-
claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --with 'sqlite-graph-memory[
|
|
97
|
+
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
98
|
```
|
|
93
99
|
|
|
94
100
|
**Cursor** (`~/.cursor/mcp.json`; Claude Desktop, Zed and Windsurf take the same `mcpServers` block)
|
|
@@ -98,7 +104,7 @@ claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --
|
|
|
98
104
|
"mcpServers": {
|
|
99
105
|
"sqlite-graph-memory": {
|
|
100
106
|
"command": "uvx",
|
|
101
|
-
"args": ["--with", "sqlite-graph-memory[
|
|
107
|
+
"args": ["--python", "3.12", "--with", "sqlite-graph-memory[lite]", "sqlite-graph-memory"],
|
|
102
108
|
"env": { "BRAIN_INDEX_DIR": "/absolute/path/to/.sgm-index" }
|
|
103
109
|
}
|
|
104
110
|
}
|
|
@@ -113,7 +119,7 @@ claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --
|
|
|
113
119
|
"sqlite-graph-memory": {
|
|
114
120
|
"type": "stdio",
|
|
115
121
|
"command": "uvx",
|
|
116
|
-
"args": ["--with", "sqlite-graph-memory[
|
|
122
|
+
"args": ["--python", "3.12", "--with", "sqlite-graph-memory[lite]", "sqlite-graph-memory"],
|
|
117
123
|
"env": { "BRAIN_INDEX_DIR": "/absolute/path/to/.sgm-index" }
|
|
118
124
|
}
|
|
119
125
|
}
|
|
@@ -125,31 +131,37 @@ claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --
|
|
|
125
131
|
```toml
|
|
126
132
|
[mcp_servers.sqlite-graph-memory]
|
|
127
133
|
command = "uvx"
|
|
128
|
-
args = ["--with", "sqlite-graph-memory[
|
|
134
|
+
args = ["--python", "3.12", "--with", "sqlite-graph-memory[lite]", "sqlite-graph-memory"]
|
|
129
135
|
env = { BRAIN_INDEX_DIR = "/absolute/path/to/.sgm-index" }
|
|
130
136
|
```
|
|
131
137
|
|
|
132
138
|
Size, `du -sh` of a fresh Python 3.12 venv on an x86_64 Mac (1 Nov 2026): the base install is
|
|
133
139
|
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]
|
|
140
|
+
with `[embeddings]` (torch) it is 879 MB, 540 MB of that torch 2.2.2 CPU. With `[lite]`,
|
|
135
141
|
the same two models on ONNX Runtime and no torch, it is 155 MB (Windows, Python 3.12,
|
|
136
142
|
3 Nov 2026), installs in 12 s, and one MCP recall on the 202-note bench vault took 7.0 s
|
|
137
143
|
against 33.8 s through torch on the same machine, with the same top hits and scores.
|
|
138
144
|
`[lite]` is picked automatically when installed; `SGM_BACKEND=torch` forces torch (for a GPU).
|
|
139
145
|
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`
|
|
146
|
+
Already installed with pip? Replace `uvx --python 3.12 --with ... sqlite-graph-memory` by `sgm-mcp`
|
|
141
147
|
([`examples/mcp-config.json`](examples/mcp-config.json)). Agents that read files first:
|
|
142
148
|
[`llms.txt`](llms.txt).
|
|
143
149
|
|
|
144
150
|
## Three commands
|
|
145
151
|
|
|
146
152
|
```bash
|
|
147
|
-
pip install 'sqlite-graph-memory[
|
|
153
|
+
pip install 'sqlite-graph-memory[lite]'
|
|
148
154
|
sgm-index ./notes
|
|
149
155
|
sgm-ask --ab "In which programming language is the tool behind Project Ouzel written?"
|
|
150
156
|
```
|
|
151
157
|
|
|
152
|
-
|
|
158
|
+
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]`.
|
|
159
|
+
|
|
160
|
+
`./notes` is any folder of markdown notes. Re-running `sgm-index` only re-embeds notes
|
|
161
|
+
that are new or changed since the last run (tracked by a manifest next to the index);
|
|
162
|
+
pass `--full` to force a complete rebuild.
|
|
163
|
+
|
|
164
|
+
To get exactly the output below, use the
|
|
153
165
|
202-note synthetic vault from this repo (it is not inside the pip package):
|
|
154
166
|
|
|
155
167
|
```bash
|
|
@@ -191,8 +203,9 @@ exists so you can measure which one wins on your own notes.
|
|
|
191
203
|
|
|
192
204
|
Graph RAG on SQLite for AI agents — a working pilot, not a framework. It is the extracted
|
|
193
205
|
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
|
-
|
|
206
|
+
points, the `[[wikilinks]]` you already wrote by hand are the graph, and dense similarity
|
|
207
|
+
orders what the hop dragged in (a cross-encoder rerank is opt-in with `--rerank`; see below
|
|
208
|
+
for why it is no longer the default).
|
|
196
209
|
SQLite is the only database ([`schema.sql`](src/sqlite_graph_memory/schema.sql)).
|
|
197
210
|
|
|
198
211
|
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 +228,14 @@ For a single-user agent over a markdown knowledge base, all three are overkill:
|
|
|
215
228
|
- **SQLite is enough** — the only things worth persisting are derived state (a per-turn
|
|
216
229
|
ledger) and telemetry, and both are defined in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
|
|
217
230
|
One file, stdlib driver, zero ops.
|
|
218
|
-
-
|
|
219
|
-
|
|
231
|
+
- **Measure before adding a stage.** The pilot shipped a cross-encoder reranker from day one;
|
|
232
|
+
measured later, it lowered recall on long queries (our 184-question gold set: body nDCG@12
|
|
233
|
+
0.640 reranked vs 0.815 dense; DolphinBench Riley slice, 1000 sessions: R@5 0.48 vs 0.61).
|
|
234
|
+
Since 0.3.7 it is off by default and stays available as `--rerank` / `SGM_RERANK=1`.
|
|
220
235
|
|
|
221
236
|
So the pilot's bet: *vector retrieval for entry points, hand-curated wikilinks for
|
|
222
|
-
association,
|
|
223
|
-
|
|
237
|
+
association, SQLite for everything that must persist.* All steps live in one file,
|
|
238
|
+
`brain_ask.py`, in that order.
|
|
224
239
|
|
|
225
240
|
## Architecture
|
|
226
241
|
|
|
@@ -234,7 +249,8 @@ markdown notes (with [[wikilinks]])
|
|
|
234
249
|
├── brain_ask.py recall pipeline:
|
|
235
250
|
│ 1. dense retrieve top-60 chunks, dedup by file
|
|
236
251
|
│ 2. --graph +1-hop wikilink neighbours of top-15 hits (max 40)
|
|
237
|
-
│ 3.
|
|
252
|
+
│ 3. order dense similarity → top-12
|
|
253
|
+
│ (--rerank: cross-encoder instead, opt-in)
|
|
238
254
|
│ 4. --ab run vector-only AND vector+graph, diff,
|
|
239
255
|
│ log the delta to SQLite (ab_recall)
|
|
240
256
|
│
|
|
@@ -253,7 +269,7 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
253
269
|
### Design choices that survived contact with reality
|
|
254
270
|
|
|
255
271
|
- **Graph expansion is candidate generation, not ranking** (`brain_ask.py`). Neighbours go
|
|
256
|
-
into the same
|
|
272
|
+
into the same ranking pool as vector hits, so an irrelevant linked note gets buried.
|
|
257
273
|
That is what makes 1-hop expansion safe to leave on.
|
|
258
274
|
- **Entity gate** (`looks_like_entity` in `brain_ask.py`). A/B telemetry showed graph
|
|
259
275
|
expansion helps *theme* queries ("approaches to agent memory") but hurts *name/tool*
|
|
@@ -272,7 +288,7 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
272
288
|
|
|
273
289
|
- No entity lane. The production setup has an extra retrieval lane over people/project
|
|
274
290
|
cards; it is too entangled with personal data to publish.
|
|
275
|
-
-
|
|
291
|
+
- Packaging exists since v0.3.0 (`pip install sqlite-graph-memory`). There IS an eval suite now — see
|
|
276
292
|
[Measure before you swap](#measure-before-you-swap--eval) — but it scores retrieval on
|
|
277
293
|
wikilink-derived gold, which is weak supervision and says so out loud. Test coverage is uneven:
|
|
278
294
|
`index_notes.py`, `brain_ask.py` and `mcp_server.py` have unit tests, and
|
|
@@ -285,9 +301,9 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
285
301
|
|
|
286
302
|
```bash
|
|
287
303
|
# Indexing and reranking need an embedding stack; the base install leaves it out.
|
|
288
|
-
# [lite]
|
|
304
|
+
# [lite] runs the models on ONNX Runtime without torch (~155 MB); [embeddings]
|
|
289
305
|
# brings torch (~2 GB) if you want a GPU. Ask for one explicitly:
|
|
290
|
-
pip install 'sqlite-graph-memory[
|
|
306
|
+
pip install 'sqlite-graph-memory[lite]'
|
|
291
307
|
|
|
292
308
|
# 1. index a folder of markdown notes
|
|
293
309
|
sgm-index /path/to/notes
|
|
@@ -311,7 +327,7 @@ To enable the per-turn ledger in Claude Code, register the Stop hook (the exact
|
|
|
311
327
|
sgm-turnstate-show --stats
|
|
312
328
|
```
|
|
313
329
|
|
|
314
|
-
Working from a clone instead of an install? `pip install -e '.[
|
|
330
|
+
Working from a clone instead of an install? `pip install -e '.[lite]'` gives you the
|
|
315
331
|
same four commands, and the modules stay importable as
|
|
316
332
|
`from sqlite_graph_memory import brain_ask`.
|
|
317
333
|
|
|
@@ -412,6 +428,45 @@ is what runs. An eval that re-implements the pipeline measures the re-implementa
|
|
|
412
428
|
`--sqlite` appends one row per class and mode to a `gold_eval` table, which is how a run six
|
|
413
429
|
weeks from now can be diffed against today's.
|
|
414
430
|
|
|
431
|
+
### Sweeping the graph-expansion knobs — `eval/run_ablation.py`
|
|
432
|
+
|
|
433
|
+
`run_eval.py` scores one configuration at a time (`vector` vs `graph`). `run_ablation.py`
|
|
434
|
+
sweeps a grid of pipeline parameters — whether the 1-hop graph expansion runs at all
|
|
435
|
+
(`hops`), how many top hits seed it (`ghops`), how many neighbours it admits (`gmax`), the
|
|
436
|
+
dense-retrieve pool size (`topk`), and whether entity/name-shaped queries skip the hop
|
|
437
|
+
(`entity_gate`) — against the **same gold file**, in one run, reusing `brain_ask.py` and
|
|
438
|
+
`run_eval.py`'s own metrics so the sweep can't drift from what `sgm-ask` actually does:
|
|
439
|
+
|
|
440
|
+
```bash
|
|
441
|
+
python eval/run_ablation.py --list-grid # cells only, no model/index load
|
|
442
|
+
python eval/run_ablation.py --gold eval/gold-<today>.jsonl # the built-in 10-cell default grid
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
Each dense embedding is computed once per question and reused across every cell (a cell's
|
|
446
|
+
candidate pool is a slice of the widest pool asked for, not a re-retrieve); only the
|
|
447
|
+
cross-encoder rerank runs per `(question, cell)`, since the candidate set changes per cell.
|
|
448
|
+
The report — printed as a Markdown table and written as both `<prefix>.md` and `<prefix>.csv`
|
|
449
|
+
(`--out <prefix>`, or `--csv`/`--md` directly) — breaks down `n`, `Recall@12`, `MRR`, `nDCG@12`
|
|
450
|
+
and `delta_nDCG@12` (vs the grid's `0-hop` baseline) per `(cell, class)` and `overall`, and
|
|
451
|
+
warns explicitly whenever a class has fewer than 20 questions. The built-in `default`
|
|
452
|
+
10-cell grid varies **one axis at a time** against `1-hop` (`ghops=15, gmax=40, topk=60,
|
|
453
|
+
entity_gate=on`) rather than a full Cartesian product; `--grid` takes `default`, a
|
|
454
|
+
`';'`-separated `key=val` cell list (e.g. `--grid "hops=0;hops=1,ghops=30,gmax=80"` to test
|
|
455
|
+
multi-axis interactions), or a JSON array of cell dicts.
|
|
456
|
+
|
|
457
|
+
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"`:
|
|
458
|
+
|
|
459
|
+
| cell | class | n | Recall@12 | MRR | nDCG@12 | delta_nDCG@12 |
|
|
460
|
+
|---|---|---:|---:|---:|---:|---:|
|
|
461
|
+
| `cell-0` (`hops=0, topk=3`) | bridge | 1 | 0.500 | 0.500 | 0.387 | +0.000 |
|
|
462
|
+
| `cell-0` (`hops=0, topk=3`) | overall | 12 | 0.958 | 0.903 | 0.907 | +0.000 |
|
|
463
|
+
| `cell-1` (`hops=1, ghops=2, gmax=5, topk=3, gate=on`) | bridge | 1 | 1.000 | 0.500 | 0.693 | +0.307 |
|
|
464
|
+
| `cell-1` (`hops=1, ghops=2, gmax=5, topk=3, gate=on`) | overall | 12 | 1.000 | 0.903 | 0.933 | +0.026 |
|
|
465
|
+
| `cell-2` (`hops=1, ghops=2, gmax=5, topk=3, gate=off`) | bridge | 1 | 1.000 | 0.500 | 0.693 | +0.307 |
|
|
466
|
+
| `cell-2` (`hops=1, ghops=2, gmax=5, topk=3, gate=off`) | overall | 12 | 1.000 | 0.903 | 0.933 | +0.026 |
|
|
467
|
+
|
|
468
|
+
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.
|
|
469
|
+
|
|
415
470
|
### What it cost us to find out
|
|
416
471
|
|
|
417
472
|
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=QCN9lXNZb7O0BUmBobR0XGrQUJyConcxQGEXAVO8C9E,1151
|
|
2
|
+
sqlite_graph_memory/brain_ask.py,sha256=TeQTZI74muSve84ESv4lBsSUyCLhr58unHpqIFXRoJ4,29535
|
|
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.8.dist-info/METADATA,sha256=RhyEbXrPBRPSyUqqbrUsd4YVEcOcsitKoT0gXaffLUY,42019
|
|
13
|
+
sqlite_graph_memory-0.3.8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
+
sqlite_graph_memory-0.3.8.dist-info/entry_points.txt,sha256=lpoCm-jNjhBEtcQ16iIUd0ivr92Gr4c_fSRls2Zvbb0,432
|
|
15
|
+
sqlite_graph_memory-0.3.8.dist-info/licenses/LICENSE,sha256=p88nZdrfMUiES3_MpUEwhGmqz2hQFpyMh0k0cqdpfU8,1082
|
|
16
|
+
sqlite_graph_memory-0.3.8.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.8.dist-info}/entry_points.txt
RENAMED
|
File without changes
|
{sqlite_graph_memory-0.3.6.dist-info → sqlite_graph_memory-0.3.8.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|