sqlite-graph-memory 0.3.5__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 +181 -19
- sqlite_graph_memory/doctor.py +12 -1
- sqlite_graph_memory/index_notes.py +174 -45
- sqlite_graph_memory/mcp_server.py +1 -1
- sqlite_graph_memory/onnx_backend.py +127 -0
- sqlite_graph_memory/turnstate_show.py +14 -6
- sqlite_graph_memory/vault_stats.py +27 -5
- {sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.7.dist-info}/METADATA +87 -26
- sqlite_graph_memory-0.3.7.dist-info/RECORD +16 -0
- sqlite_graph_memory-0.3.5.dist-info/RECORD +0 -15
- {sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.7.dist-info}/WHEEL +0 -0
- {sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.7.dist-info}/entry_points.txt +0 -0
- {sqlite_graph_memory-0.3.5.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)
|
|
@@ -49,13 +53,37 @@ ENTITY_TOOLS = {'obsidian', 'syncthing', 'sqlite', 'telegram', 'whatsapp', 'n8n'
|
|
|
49
53
|
|
|
50
54
|
|
|
51
55
|
_EMBEDDINGS_HINT = (
|
|
52
|
-
"This step needs
|
|
53
|
-
"
|
|
56
|
+
"This step needs an embedding stack.\n"
|
|
57
|
+
"Light, no torch (~60 MB): pip install 'sqlite-graph-memory[lite]'\n"
|
|
58
|
+
"Torch, for a GPU: pip install 'sqlite-graph-memory[embeddings]'\n"
|
|
54
59
|
"The base install stays small on purpose: the graph half, the SQLite schema\n"
|
|
55
60
|
"and the turnstate memory work without it."
|
|
56
61
|
)
|
|
57
62
|
|
|
58
63
|
|
|
64
|
+
def backend(env=None):
|
|
65
|
+
"""'onnx' or 'torch': which stack runs the two models.
|
|
66
|
+
|
|
67
|
+
SGM_BACKEND=onnx|torch forces one. Unset (auto): ONNX whenever the lite stack is
|
|
68
|
+
installed, because it starts in seconds where torch took 44 s just to import on a
|
|
69
|
+
CPU laptop (2026-11-01); otherwise sentence-transformers, as before. Both run the
|
|
70
|
+
same checkpoints, so an index built by one is searched correctly by the other.
|
|
71
|
+
"""
|
|
72
|
+
env = os.environ if env is None else env
|
|
73
|
+
want = (env.get('SGM_BACKEND') or 'auto').strip().lower()
|
|
74
|
+
if want in ('onnx', 'torch'):
|
|
75
|
+
return want
|
|
76
|
+
return 'onnx' if _onnx().available() else 'torch'
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _onnx():
|
|
80
|
+
try:
|
|
81
|
+
from sqlite_graph_memory import onnx_backend
|
|
82
|
+
except ImportError: # run as a loose script next to onnx_backend.py
|
|
83
|
+
import onnx_backend
|
|
84
|
+
return onnx_backend
|
|
85
|
+
|
|
86
|
+
|
|
59
87
|
def _require_sentence_transformers():
|
|
60
88
|
"""Import sentence_transformers, or exit with instructions.
|
|
61
89
|
|
|
@@ -71,6 +99,10 @@ def _require_sentence_transformers():
|
|
|
71
99
|
return sentence_transformers
|
|
72
100
|
|
|
73
101
|
def pick_device():
|
|
102
|
+
# The ONNX path runs on CPU; importing torch here only to ask about CUDA was the
|
|
103
|
+
# 44-second stall the lite backend exists to remove.
|
|
104
|
+
if backend() == 'onnx':
|
|
105
|
+
return 'cpu'
|
|
74
106
|
try:
|
|
75
107
|
import torch
|
|
76
108
|
return 'cuda' if torch.cuda.is_available() else 'cpu'
|
|
@@ -106,13 +138,15 @@ def looks_like_entity(q):
|
|
|
106
138
|
|
|
107
139
|
|
|
108
140
|
FENCED_CODE_RX = re.compile(r'(?:```[\s\S]*?```|~~~[\s\S]*?~~~)')
|
|
141
|
+
INLINE_CODE_RX = re.compile(r'`+[^`\n]*`+')
|
|
109
142
|
WIKILINK_RX = re.compile(r'\[\[([^\]\|#]+)')
|
|
110
143
|
|
|
111
144
|
def _links_in(path):
|
|
112
|
-
"""Outgoing wikilink TARGETS in a note (alias/heading stripped, code
|
|
145
|
+
"""Outgoing wikilink TARGETS in a note (alias/heading stripped, code ignored)."""
|
|
113
146
|
try: t = Path(path).read_text(encoding='utf-8', errors='ignore')
|
|
114
147
|
except Exception: return []
|
|
115
148
|
t = FENCED_CODE_RX.sub('', t)
|
|
149
|
+
t = INLINE_CODE_RX.sub('', t)
|
|
116
150
|
return [m.strip() for m in WIKILINK_RX.findall(t)]
|
|
117
151
|
|
|
118
152
|
|
|
@@ -129,13 +163,55 @@ def load_index(emb_path=None, meta_path=None):
|
|
|
129
163
|
return emb, meta
|
|
130
164
|
|
|
131
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
|
+
|
|
177
|
+
def _try_onnx(kind):
|
|
178
|
+
"""The ONNX model, or None to fall back to torch.
|
|
179
|
+
|
|
180
|
+
Only an auto-picked ONNX falls back: someone who already has the torch models cached
|
|
181
|
+
and gets onnxruntime from another package may be offline, with no ONNX files yet.
|
|
182
|
+
Their recall must keep working on torch. SGM_BACKEND=onnx raises instead.
|
|
183
|
+
"""
|
|
184
|
+
if backend() != 'onnx':
|
|
185
|
+
return None
|
|
186
|
+
try:
|
|
187
|
+
return getattr(_onnx(), kind)()
|
|
188
|
+
except Exception as exc:
|
|
189
|
+
if (os.getenv('SGM_BACKEND') or '').strip().lower() == 'onnx':
|
|
190
|
+
raise
|
|
191
|
+
try:
|
|
192
|
+
import sentence_transformers # noqa: F401
|
|
193
|
+
except ImportError:
|
|
194
|
+
raise exc
|
|
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))
|
|
199
|
+
return None
|
|
200
|
+
|
|
201
|
+
|
|
132
202
|
def load_encoder(dev=None):
|
|
203
|
+
m = _try_onnx('Encoder')
|
|
204
|
+
if m is not None:
|
|
205
|
+
return m
|
|
133
206
|
_require_sentence_transformers()
|
|
134
207
|
from sentence_transformers import SentenceTransformer
|
|
135
208
|
return SentenceTransformer(E5_MODEL, device=dev or pick_device())
|
|
136
209
|
|
|
137
210
|
|
|
138
211
|
def load_reranker(dev=None):
|
|
212
|
+
m = _try_onnx('CrossEncoder')
|
|
213
|
+
if m is not None:
|
|
214
|
+
return m
|
|
139
215
|
_require_sentence_transformers()
|
|
140
216
|
from sentence_transformers import CrossEncoder
|
|
141
217
|
return CrossEncoder(RERANK_MODEL, device=dev or pick_device())
|
|
@@ -159,15 +235,78 @@ def retrieve_candidates(sims, meta, topk=TOPK_RETRIEVE):
|
|
|
159
235
|
return order
|
|
160
236
|
|
|
161
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
|
+
|
|
162
269
|
def index_by_basename(meta):
|
|
163
270
|
"""basename(no .md) -> meta indices, used to resolve [[wikilink]] targets to chunks."""
|
|
164
|
-
by_base =
|
|
271
|
+
by_base = _BasenameIndex(root=vault_root(meta))
|
|
165
272
|
for j, mm in enumerate(meta):
|
|
166
273
|
by_base.setdefault(Path(mm['path']).stem.lower(), []).append(j)
|
|
167
274
|
return by_base
|
|
168
275
|
|
|
169
276
|
|
|
170
|
-
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):
|
|
171
310
|
"""Follow 1-hop OUTGOING wikilinks from the top vector hits and return the neighbour
|
|
172
311
|
chunks to ADD to the candidate set; the reranker decides whether they are relevant.
|
|
173
312
|
|
|
@@ -177,10 +316,14 @@ def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX):
|
|
|
177
316
|
if not base_order: return added
|
|
178
317
|
try:
|
|
179
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)
|
|
180
323
|
in_order = set(base_order)
|
|
181
324
|
for i in base_order[:ghops]:
|
|
182
325
|
for tgt in _links_in(meta[i]['path']):
|
|
183
|
-
idxs =
|
|
326
|
+
idxs = _resolve_target_chunks(tgt, by_base, meta, root=root)
|
|
184
327
|
if not idxs: continue
|
|
185
328
|
best = max(idxs, key=lambda j: sims[j]) # best chunk of neighbour for THIS query
|
|
186
329
|
if best in in_order: continue
|
|
@@ -193,11 +336,25 @@ def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX):
|
|
|
193
336
|
return added
|
|
194
337
|
|
|
195
338
|
|
|
196
|
-
def
|
|
197
|
-
"""
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
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 []
|
|
201
358
|
return sorted(zip(cand, sc), key=lambda x: -x[1])[:topn]
|
|
202
359
|
|
|
203
360
|
|
|
@@ -294,9 +451,13 @@ def maybe_star_prompt(stream=None, env=None, interactive=None):
|
|
|
294
451
|
|
|
295
452
|
def main():
|
|
296
453
|
args = sys.argv[1:]
|
|
454
|
+
if '--version' in args:
|
|
455
|
+
from sqlite_graph_memory import __version__
|
|
456
|
+
print('sgm-ask %s' % __version__)
|
|
457
|
+
return
|
|
297
458
|
ask = '--ask' in args
|
|
298
459
|
graph = '--graph' in args; ab = '--ab' in args
|
|
299
|
-
flags = {'--ask', '--graph', '--ab', '--ppr'}
|
|
460
|
+
flags = {'--ask', '--graph', '--ab', '--ppr', '--rerank'}
|
|
300
461
|
query = ' '.join(a for a in args if a not in flags)
|
|
301
462
|
if not query or not EMB.exists():
|
|
302
463
|
sys.stderr.write('need an embedding index (%s) and a query — run index_notes.py first\n' % EMB)
|
|
@@ -335,12 +496,12 @@ def main():
|
|
|
335
496
|
elif order and ('--ppr' in args or ppr_enabled()):
|
|
336
497
|
ppr_stems = ppr_lane(meta, sims, base_order)
|
|
337
498
|
|
|
338
|
-
#
|
|
339
|
-
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
|
|
340
501
|
def rerank(cand):
|
|
341
502
|
if not ppr_stems:
|
|
342
|
-
return rerank_candidates(ce, query, cand, meta)
|
|
343
|
-
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
|
|
344
505
|
return fuse_ppr(full, meta, ppr_stems, TOPN)
|
|
345
506
|
|
|
346
507
|
# --ab: run BOTH paths in ONE process, diff, log. Answers "does graph REALLY help?"
|
|
@@ -393,6 +554,7 @@ def main():
|
|
|
393
554
|
except Exception:
|
|
394
555
|
pass
|
|
395
556
|
_out = Path(os.getenv('BRAIN_ANSWER_OUT', '_brain_answer.txt'))
|
|
557
|
+
text = _with_notes(text)
|
|
396
558
|
_out.write_text(text, encoding='utf-8'); print(text)
|
|
397
559
|
maybe_star_prompt()
|
|
398
560
|
return
|
|
@@ -404,7 +566,7 @@ def main():
|
|
|
404
566
|
order = graph_order if (graph and not gated) else base_order
|
|
405
567
|
reranked = rerank(order)
|
|
406
568
|
scope = 'all' + (' /graph+%d' % len(graph_set) if graph else '') + (' /ppr' if ppr_stems else '')
|
|
407
|
-
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)', '']
|
|
408
570
|
if ask:
|
|
409
571
|
lines.append('=== CONTEXT BUNDLE (paste to your agent) ===\n')
|
|
410
572
|
for i, sc in reranked[:8]:
|
|
@@ -418,7 +580,7 @@ def main():
|
|
|
418
580
|
lines.append("%2d. [rr=%6.2f] [%s] %s%s" % (rank, float(sc), m.get('date', ''), m['title'], gmark))
|
|
419
581
|
lines.append(" %s" % m['snippet'][:140])
|
|
420
582
|
_out = Path(os.getenv('BRAIN_ANSWER_OUT', '_brain_answer.txt'))
|
|
421
|
-
_out.write_text('\n'.join(lines), encoding='utf-8')
|
|
583
|
+
_out.write_text(_with_notes('\n'.join(lines)), encoding='utf-8')
|
|
422
584
|
print(f'{len(reranked)} hits (scope={scope}) -> {_out}')
|
|
423
585
|
|
|
424
586
|
|
sqlite_graph_memory/doctor.py
CHANGED
|
@@ -40,6 +40,16 @@ def _intel_mac(system=None, machine=None):
|
|
|
40
40
|
|
|
41
41
|
def check_embeddings(system=None, machine=None):
|
|
42
42
|
"""The heavy half. Without it the graph and the SQLite parts work, indexing and recall do not."""
|
|
43
|
+
if brain_ask.backend() == 'onnx':
|
|
44
|
+
try:
|
|
45
|
+
import onnxruntime
|
|
46
|
+
import tokenizers # noqa: F401
|
|
47
|
+
import huggingface_hub # noqa: F401
|
|
48
|
+
except Exception as exc:
|
|
49
|
+
why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
|
|
50
|
+
return FAIL, 'The light backend is incomplete (%s).' % why, \
|
|
51
|
+
'Reinstall in a fresh virtualenv: pip install --force-reinstall "sqlite-graph-memory[lite]"'
|
|
52
|
+
return OK, 'Light backend: onnxruntime %s, no torch needed.' % onnxruntime.__version__, ''
|
|
43
53
|
try:
|
|
44
54
|
import numpy
|
|
45
55
|
np_major = int(numpy.__version__.split('.')[0])
|
|
@@ -50,7 +60,8 @@ def check_embeddings(system=None, machine=None):
|
|
|
50
60
|
import sentence_transformers
|
|
51
61
|
except ModuleNotFoundError as exc:
|
|
52
62
|
return (WARN, 'The embeddings extra is not installed (%s missing).' % exc.name,
|
|
53
|
-
'Only needed to index and recall. Install it with: pip install "sqlite-graph-memory[
|
|
63
|
+
'Only needed to index and recall. Install it with: pip install "sqlite-graph-memory[lite]"'
|
|
64
|
+
' (or [embeddings] for torch and a GPU)')
|
|
54
65
|
except Exception as exc: # torch dies at import on a numpy it was not built for
|
|
55
66
|
why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
|
|
56
67
|
if _intel_mac(system, machine) and np_major >= 2:
|
|
@@ -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,14 +34,12 @@ SNIPPET_CHARS = 600
|
|
|
27
34
|
|
|
28
35
|
FM_RX = re.compile(r'^---\r?\n(.*?)\r?\n---\r?\n', re.S)
|
|
29
36
|
|
|
37
|
+
try:
|
|
38
|
+
from sqlite_graph_memory import brain_ask as _ba
|
|
39
|
+
except ImportError: # run as a loose script next to brain_ask.py
|
|
40
|
+
import brain_ask as _ba
|
|
30
41
|
|
|
31
|
-
|
|
32
|
-
_EMBEDDINGS_HINT = (
|
|
33
|
-
"This step needs the optional embedding stack (sentence-transformers, torch).\n"
|
|
34
|
-
"Install it with: pip install 'sqlite-graph-memory[embeddings]'\n"
|
|
35
|
-
"The base install stays small on purpose: the graph half, the SQLite schema\n"
|
|
36
|
-
"and the turnstate memory work without it."
|
|
37
|
-
)
|
|
42
|
+
_EMBEDDINGS_HINT = _ba._EMBEDDINGS_HINT
|
|
38
43
|
|
|
39
44
|
|
|
40
45
|
def _require_sentence_transformers():
|
|
@@ -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,45 +112,168 @@ def read_note(path):
|
|
|
106
112
|
return None
|
|
107
113
|
|
|
108
114
|
|
|
109
|
-
def
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
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}
|
|
115
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
|
|
116
134
|
meta, texts = [], []
|
|
117
|
-
for
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
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:
|
|
131
|
-
print('no indexable .md notes found under', notes_dir); return
|
|
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
|
|
132
140
|
|
|
133
|
-
_require_sentence_transformers()
|
|
134
|
-
from sentence_transformers import SentenceTransformer
|
|
135
|
-
try:
|
|
136
|
-
import torch
|
|
137
|
-
dev = 'cuda' if torch.cuda.is_available() else 'cpu'
|
|
138
|
-
except Exception:
|
|
139
|
-
dev = 'cpu'
|
|
140
|
-
enc = SentenceTransformer(E5_MODEL, device=dev)
|
|
141
|
-
emb = enc.encode(texts, normalize_embeddings=True, convert_to_numpy=True,
|
|
142
|
-
batch_size=64, show_progress_bar=True).astype('float32')
|
|
143
141
|
|
|
144
|
-
|
|
145
|
-
(
|
|
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
|
+
|
|
146
251
|
files = len({m['path'] for m in meta})
|
|
147
|
-
|
|
252
|
+
return {'chunks': len(meta), 'files': files, 'new_texts': len(new_texts)}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def main():
|
|
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:
|
|
262
|
+
print(__doc__); return
|
|
263
|
+
notes_dir = Path(args.notes_dir)
|
|
264
|
+
out_dir = Path(os.getenv('BRAIN_INDEX_DIR', 'index'))
|
|
265
|
+
|
|
266
|
+
result = build_index(notes_dir, out_dir=out_dir, full=args.full)
|
|
267
|
+
if result['chunks'] == 0:
|
|
268
|
+
print('no indexable .md notes found under', notes_dir); return
|
|
269
|
+
if _ba.backend() == 'onnx':
|
|
270
|
+
# Fetch the reranker too: otherwise the first recall from an MCP client is also
|
|
271
|
+
# a ~470 MB download and runs into the client's tool timeout.
|
|
272
|
+
try:
|
|
273
|
+
_ba._onnx().prefetch()
|
|
274
|
+
except Exception as exc: # offline: the first recall fetches it instead
|
|
275
|
+
print('reranker not prefetched (%s); the first recall will fetch it' % type(exc).__name__)
|
|
276
|
+
print('indexed %d chunks from %d files -> %s' % (result['chunks'], result['files'], out_dir))
|
|
148
277
|
|
|
149
278
|
|
|
150
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",
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""onnx_backend.py: the same two models brain_ask uses, run on ONNX Runtime, no torch.
|
|
3
|
+
|
|
4
|
+
Why it exists: on a laptop without a GPU the torch stack is the slow part of a recall,
|
|
5
|
+
not the search. Measured 2026-11-01 on a Windows machine through the MCP server:
|
|
6
|
+
`import torch` alone took 44 s, the encoder had not loaded at 90 s, and the client gave
|
|
7
|
+
up at its 60 s tool timeout. ONNX Runtime plus `tokenizers` is a ~60 MB install that
|
|
8
|
+
imports in under a second.
|
|
9
|
+
|
|
10
|
+
Same weights, same index: both model repos publish an official ONNX export of the very
|
|
11
|
+
checkpoint the torch path loads (`onnx/model.onnx`), so an index built with
|
|
12
|
+
sentence-transformers keeps working here and the other way round. The equivalence is
|
|
13
|
+
pinned by tests/test_onnx_backend.py against sentence-transformers outputs.
|
|
14
|
+
|
|
15
|
+
Models are cached by huggingface_hub in its persistent cache (HF_HUB_CACHE, default
|
|
16
|
+
~/.cache/huggingface/hub), never in the system temp dir, so Windows cleanup does not
|
|
17
|
+
force a second 1.6 GB download. SGM_MODEL_CACHE overrides the folder.
|
|
18
|
+
|
|
19
|
+
Input: lists of strings (encode) or (query, passage) pairs (predict).
|
|
20
|
+
Output: float32 numpy arrays shaped like the sentence-transformers calls they replace.
|
|
21
|
+
Called by: brain_ask.load_encoder / load_reranker when the backend resolves to "onnx".
|
|
22
|
+
"""
|
|
23
|
+
import os
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
E5_REPO = 'intfloat/multilingual-e5-base'
|
|
28
|
+
E5_FILES = ('onnx/model.onnx', 'onnx/tokenizer.json')
|
|
29
|
+
RERANK_REPO = 'cross-encoder/mmarco-mMiniLMv2-L12-H384-v1'
|
|
30
|
+
RERANK_FILES = ('onnx/model.onnx', 'tokenizer.json')
|
|
31
|
+
MAX_LEN = 512 # sentence-transformers max_seq_length / max_length for both checkpoints
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def available():
|
|
35
|
+
"""True when the lite stack (onnxruntime, tokenizers, huggingface_hub) is importable."""
|
|
36
|
+
try:
|
|
37
|
+
import onnxruntime # noqa: F401
|
|
38
|
+
import tokenizers # noqa: F401
|
|
39
|
+
import huggingface_hub # noqa: F401
|
|
40
|
+
except ImportError:
|
|
41
|
+
return False
|
|
42
|
+
return True
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _fetch(repo, files):
|
|
46
|
+
"""Download (or reuse from cache) the named files of one model repo -> local paths."""
|
|
47
|
+
from huggingface_hub import hf_hub_download
|
|
48
|
+
cache = os.getenv('SGM_MODEL_CACHE') or None
|
|
49
|
+
return [hf_hub_download(repo, f, cache_dir=cache) for f in files]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def prefetch():
|
|
53
|
+
"""Fetch both models now, so the first recall is not also a 1.6 GB download."""
|
|
54
|
+
_fetch(E5_REPO, E5_FILES)
|
|
55
|
+
_fetch(RERANK_REPO, RERANK_FILES)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _session(model_path):
|
|
59
|
+
import onnxruntime as ort
|
|
60
|
+
opts = ort.SessionOptions()
|
|
61
|
+
opts.log_severity_level = 3 # keep stdout/stderr clean for the MCP pipe
|
|
62
|
+
return ort.InferenceSession(model_path, sess_options=opts,
|
|
63
|
+
providers=['CPUExecutionProvider'])
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _tokenizer(path):
|
|
67
|
+
from tokenizers import Tokenizer
|
|
68
|
+
tok = Tokenizer.from_file(path)
|
|
69
|
+
tok.enable_truncation(max_length=MAX_LEN)
|
|
70
|
+
tok.enable_padding()
|
|
71
|
+
return tok
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _feed(sess, encs):
|
|
75
|
+
ids = np.array([e.ids for e in encs], dtype=np.int64)
|
|
76
|
+
mask = np.array([e.attention_mask for e in encs], dtype=np.int64)
|
|
77
|
+
feed = {'input_ids': ids, 'attention_mask': mask}
|
|
78
|
+
names = {i.name for i in sess.get_inputs()}
|
|
79
|
+
if 'token_type_ids' in names:
|
|
80
|
+
feed['token_type_ids'] = np.array([e.type_ids for e in encs], dtype=np.int64)
|
|
81
|
+
return {k: v for k, v in feed.items() if k in names}, mask
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class Encoder:
|
|
85
|
+
"""Drop-in for SentenceTransformer(E5_MODEL).encode: mean pooling, optional L2 norm."""
|
|
86
|
+
|
|
87
|
+
def __init__(self):
|
|
88
|
+
model, tok = _fetch(E5_REPO, E5_FILES)
|
|
89
|
+
self.sess = _session(model)
|
|
90
|
+
self.tok = _tokenizer(tok)
|
|
91
|
+
|
|
92
|
+
def encode(self, texts, normalize_embeddings=True, convert_to_numpy=True,
|
|
93
|
+
batch_size=32, show_progress_bar=False):
|
|
94
|
+
out = []
|
|
95
|
+
for s in range(0, len(texts), batch_size):
|
|
96
|
+
feed, mask = _feed(self.sess, self.tok.encode_batch(list(texts[s:s + batch_size])))
|
|
97
|
+
hidden = self.sess.run(None, feed)[0] # (n, seq, dim)
|
|
98
|
+
m = mask[..., None].astype(np.float32)
|
|
99
|
+
vec = (hidden * m).sum(1) / np.clip(m.sum(1), 1e-9, None)
|
|
100
|
+
if normalize_embeddings:
|
|
101
|
+
vec = vec / np.clip(np.linalg.norm(vec, axis=1, keepdims=True), 1e-12, None)
|
|
102
|
+
out.append(vec.astype(np.float32))
|
|
103
|
+
if show_progress_bar:
|
|
104
|
+
print(' encoded %d/%d' % (min(s + batch_size, len(texts)), len(texts)), flush=True)
|
|
105
|
+
return np.concatenate(out) if out else np.zeros((0, 768), np.float32)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class CrossEncoder:
|
|
109
|
+
"""Drop-in for sentence_transformers.CrossEncoder(RERANK_MODEL).predict.
|
|
110
|
+
|
|
111
|
+
Returns the raw logit, as sentence-transformers does for this checkpoint (measured
|
|
112
|
+
2026-11-03 with sentence-transformers 6.1: -0.857 / -9.52 / 0.014 on the test pairs,
|
|
113
|
+
no sigmoid), so `rr=` in the CLI output reads the same whichever backend ran.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(self):
|
|
117
|
+
model, tok = _fetch(RERANK_REPO, RERANK_FILES)
|
|
118
|
+
self.sess = _session(model)
|
|
119
|
+
self.tok = _tokenizer(tok)
|
|
120
|
+
|
|
121
|
+
def predict(self, pairs, batch_size=32):
|
|
122
|
+
pairs = [(str(a), str(b)) for a, b in pairs]
|
|
123
|
+
out = []
|
|
124
|
+
for s in range(0, len(pairs), batch_size):
|
|
125
|
+
feed, _ = _feed(self.sess, self.tok.encode_batch(pairs[s:s + batch_size]))
|
|
126
|
+
out.append(self.sess.run(None, feed)[0].reshape(-1))
|
|
127
|
+
return np.concatenate(out).astype(np.float32) if out else np.zeros(0, np.float32)
|
|
@@ -30,16 +30,23 @@ def jl(s):
|
|
|
30
30
|
return []
|
|
31
31
|
|
|
32
32
|
|
|
33
|
-
def main():
|
|
33
|
+
def main(argv=None):
|
|
34
34
|
ap = argparse.ArgumentParser()
|
|
35
35
|
ap.add_argument("--session")
|
|
36
36
|
ap.add_argument("--n", type=int, default=15)
|
|
37
37
|
ap.add_argument("--stats", action="store_true")
|
|
38
|
-
a = ap.parse_args()
|
|
38
|
+
a = ap.parse_args(argv)
|
|
39
39
|
|
|
40
40
|
if not os.path.isfile(DB):
|
|
41
|
-
print("(no ledger yet:", DB, ")")
|
|
42
|
-
|
|
41
|
+
print("(no ledger yet:", DB, ")")
|
|
42
|
+
return 0
|
|
43
|
+
try:
|
|
44
|
+
c = sqlite3.connect(DB)
|
|
45
|
+
# Opening succeeds on junk bytes; the first query is what raises DatabaseError.
|
|
46
|
+
c.execute("select 1 from sqlite_master limit 1").fetchone()
|
|
47
|
+
except sqlite3.Error:
|
|
48
|
+
print("sgm-turnstate-show: not a database: %s" % DB, file=sys.stderr)
|
|
49
|
+
return 1
|
|
43
50
|
|
|
44
51
|
if a.stats:
|
|
45
52
|
tot = c.execute("select count(*) from turns").fetchone()[0]
|
|
@@ -51,7 +58,7 @@ def main():
|
|
|
51
58
|
"select session_id,count(*),max(ts) from turns group by session_id "
|
|
52
59
|
"order by max(ts) desc limit 12"):
|
|
53
60
|
print(" %-38s %4d turns last %s" % (sid[:38], n, last))
|
|
54
|
-
return
|
|
61
|
+
return 0
|
|
55
62
|
|
|
56
63
|
q = ("select ts,project,ask,summary,files,tools,commands,decisions,session_id "
|
|
57
64
|
"from turns ")
|
|
@@ -79,7 +86,8 @@ def main():
|
|
|
79
86
|
print(" - %s" % x)
|
|
80
87
|
if summary:
|
|
81
88
|
print("💬 summary: %s" % summary.replace("\n", " ")[:200])
|
|
89
|
+
return 0
|
|
82
90
|
|
|
83
91
|
|
|
84
92
|
if __name__ == "__main__":
|
|
85
|
-
main()
|
|
93
|
+
sys.exit(main() or 0)
|
|
@@ -35,7 +35,8 @@ import sys
|
|
|
35
35
|
from collections import defaultdict
|
|
36
36
|
from pathlib import Path
|
|
37
37
|
|
|
38
|
-
from sqlite_graph_memory
|
|
38
|
+
from sqlite_graph_memory import __version__
|
|
39
|
+
from sqlite_graph_memory.brain_ask import _links_in, _normalize_target
|
|
39
40
|
from sqlite_graph_memory.index_notes import FM_RX, iter_notes, read_note
|
|
40
41
|
|
|
41
42
|
DEFAULTS = {
|
|
@@ -60,15 +61,29 @@ def build_graph(notes_dir):
|
|
|
60
61
|
"""(pages, edges): pages = {relative path without .md: Path},
|
|
61
62
|
edges = {(src, dst)} between real pages."""
|
|
62
63
|
root = Path(notes_dir)
|
|
63
|
-
pages, by_stem = {}, defaultdict(list)
|
|
64
|
+
pages, by_path, by_stem = {}, defaultdict(list), defaultdict(list)
|
|
64
65
|
for p in iter_notes(root):
|
|
65
66
|
key = p.relative_to(root).with_suffix('').as_posix()
|
|
66
67
|
pages[key] = p
|
|
68
|
+
by_path[key.lower()].append(key)
|
|
67
69
|
by_stem[p.stem.lower()].append(key)
|
|
68
70
|
edges = set()
|
|
69
71
|
for src, path in pages.items():
|
|
70
72
|
for tgt in _links_in(path):
|
|
71
|
-
|
|
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:
|
|
72
87
|
if dst != src:
|
|
73
88
|
edges.add((src, dst))
|
|
74
89
|
return pages, edges
|
|
@@ -194,6 +209,7 @@ def render(report):
|
|
|
194
209
|
def main(argv=None):
|
|
195
210
|
ap = argparse.ArgumentParser(prog='sgm-stats', description=__doc__.split('\n\n')[0])
|
|
196
211
|
ap.add_argument('notes_dir')
|
|
212
|
+
ap.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
|
|
197
213
|
ap.add_argument('--json', action='store_true', help='machine-readable output')
|
|
198
214
|
ap.add_argument('--today', type=datetime.date.fromisoformat,
|
|
199
215
|
help='date to measure staleness against (YYYY-MM-DD; default: today)')
|
|
@@ -207,8 +223,14 @@ def main(argv=None):
|
|
|
207
223
|
try:
|
|
208
224
|
report = compute(a.notes_dir, today=a.today, th=th)
|
|
209
225
|
except EmptyVault as e:
|
|
210
|
-
|
|
211
|
-
|
|
226
|
+
if a.json:
|
|
227
|
+
report = {
|
|
228
|
+
'notes_dir': str(a.notes_dir), 'pages': 0, 'metrics': [],
|
|
229
|
+
'verdict': 'fail', 'exit_code': 2, 'error': str(e),
|
|
230
|
+
}
|
|
231
|
+
else:
|
|
232
|
+
print(e, file=sys.stderr)
|
|
233
|
+
return 2
|
|
212
234
|
print(json.dumps(report, indent=2, ensure_ascii=False) if a.json else render(report))
|
|
213
235
|
return report['exit_code']
|
|
214
236
|
|
|
@@ -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
|
|
@@ -47,6 +47,10 @@ Requires-Dist: numpy<2; (sys_platform == 'darwin' and platform_machine == 'x86_6
|
|
|
47
47
|
Requires-Dist: sentence-transformers<5; (sys_platform == 'darwin' and platform_machine == 'x86_64') and extra == 'embeddings'
|
|
48
48
|
Requires-Dist: sentence-transformers>=2.6; extra == 'embeddings'
|
|
49
49
|
Requires-Dist: transformers<4.50; (sys_platform == 'darwin' and platform_machine == 'x86_64') and extra == 'embeddings'
|
|
50
|
+
Provides-Extra: lite
|
|
51
|
+
Requires-Dist: huggingface-hub>=0.20; extra == 'lite'
|
|
52
|
+
Requires-Dist: onnxruntime>=1.17; extra == 'lite'
|
|
53
|
+
Requires-Dist: tokenizers>=0.15; extra == 'lite'
|
|
50
54
|
Description-Content-Type: text/markdown
|
|
51
55
|
|
|
52
56
|
# sqlite-graph-memory: persistent memory for Claude Code, Cursor and Codex over your own markdown notes
|
|
@@ -69,14 +73,18 @@ One SQLite file, no graph database, no ETL pass, no server.**
|
|
|
69
73
|
|
|
70
74
|
## Install in your client
|
|
71
75
|
|
|
72
|
-
Already using your own agent rules and projects? The [Russian existing-setup guide
|
|
76
|
+
Already using your own agent rules and projects? The [Russian existing-setup guide](https://github.com/tonydzi/second-brain-starter-kit/blob/master/docs/EXISTING-SETUP.ru.md) combines this memory backend with the optional starter-kit method, preserves existing settings, and checks recall in a fresh chat. Install one memory connection per client; the starter-kit memory plugin and manual registration are alternatives.
|
|
73
77
|
|
|
74
78
|
Build the index once (any folder of markdown; [`uv`](https://docs.astral.sh/uv/) gives you `uvx`):
|
|
75
79
|
|
|
76
80
|
```bash
|
|
77
|
-
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
|
|
78
82
|
```
|
|
79
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
|
+
|
|
80
88
|
Then point your client at the server. Use the absolute path of that index folder.
|
|
81
89
|
|
|
82
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.
|
|
@@ -84,7 +92,7 @@ Then point your client at the server. Use the absolute path of that index folder
|
|
|
84
92
|
**Claude Code**
|
|
85
93
|
|
|
86
94
|
```bash
|
|
87
|
-
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
|
|
88
96
|
```
|
|
89
97
|
|
|
90
98
|
**Cursor** (`~/.cursor/mcp.json`; Claude Desktop, Zed and Windsurf take the same `mcpServers` block)
|
|
@@ -94,7 +102,7 @@ claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --
|
|
|
94
102
|
"mcpServers": {
|
|
95
103
|
"sqlite-graph-memory": {
|
|
96
104
|
"command": "uvx",
|
|
97
|
-
"args": ["--with", "sqlite-graph-memory[
|
|
105
|
+
"args": ["--python", "3.12", "--with", "sqlite-graph-memory[lite]", "sqlite-graph-memory"],
|
|
98
106
|
"env": { "BRAIN_INDEX_DIR": "/absolute/path/to/.sgm-index" }
|
|
99
107
|
}
|
|
100
108
|
}
|
|
@@ -109,7 +117,7 @@ claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --
|
|
|
109
117
|
"sqlite-graph-memory": {
|
|
110
118
|
"type": "stdio",
|
|
111
119
|
"command": "uvx",
|
|
112
|
-
"args": ["--with", "sqlite-graph-memory[
|
|
120
|
+
"args": ["--python", "3.12", "--with", "sqlite-graph-memory[lite]", "sqlite-graph-memory"],
|
|
113
121
|
"env": { "BRAIN_INDEX_DIR": "/absolute/path/to/.sgm-index" }
|
|
114
122
|
}
|
|
115
123
|
}
|
|
@@ -121,27 +129,37 @@ claude mcp add sqlite-graph-memory -e BRAIN_INDEX_DIR=$HOME/.sgm-index -- uvx --
|
|
|
121
129
|
```toml
|
|
122
130
|
[mcp_servers.sqlite-graph-memory]
|
|
123
131
|
command = "uvx"
|
|
124
|
-
args = ["--with", "sqlite-graph-memory[
|
|
132
|
+
args = ["--python", "3.12", "--with", "sqlite-graph-memory[lite]", "sqlite-graph-memory"]
|
|
125
133
|
env = { BRAIN_INDEX_DIR = "/absolute/path/to/.sgm-index" }
|
|
126
134
|
```
|
|
127
135
|
|
|
128
136
|
Size, `du -sh` of a fresh Python 3.12 venv on an x86_64 Mac (1 Nov 2026): the base install is
|
|
129
137
|
26 MB and has no torch (numpy only, enough for the graph half and the SQLite ledger);
|
|
130
|
-
with `[embeddings]
|
|
131
|
-
|
|
132
|
-
|
|
138
|
+
with `[embeddings]` (torch) it is 879 MB, 540 MB of that torch 2.2.2 CPU. With `[lite]`,
|
|
139
|
+
the same two models on ONNX Runtime and no torch, it is 155 MB (Windows, Python 3.12,
|
|
140
|
+
3 Nov 2026), installs in 12 s, and one MCP recall on the 202-note bench vault took 7.0 s
|
|
141
|
+
against 33.8 s through torch on the same machine, with the same top hits and scores.
|
|
142
|
+
`[lite]` is picked automatically when installed; `SGM_BACKEND=torch` forces torch (for a GPU).
|
|
143
|
+
An index built by either backend is searched correctly by the other.
|
|
144
|
+
Already installed with pip? Replace `uvx --python 3.12 --with ... sqlite-graph-memory` by `sgm-mcp`
|
|
133
145
|
([`examples/mcp-config.json`](examples/mcp-config.json)). Agents that read files first:
|
|
134
146
|
[`llms.txt`](llms.txt).
|
|
135
147
|
|
|
136
148
|
## Three commands
|
|
137
149
|
|
|
138
150
|
```bash
|
|
139
|
-
pip install 'sqlite-graph-memory[
|
|
151
|
+
pip install 'sqlite-graph-memory[lite]'
|
|
140
152
|
sgm-index ./notes
|
|
141
153
|
sgm-ask --ab "In which programming language is the tool behind Project Ouzel written?"
|
|
142
154
|
```
|
|
143
155
|
|
|
144
|
-
|
|
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
|
|
145
163
|
202-note synthetic vault from this repo (it is not inside the pip package):
|
|
146
164
|
|
|
147
165
|
```bash
|
|
@@ -183,8 +201,9 @@ exists so you can measure which one wins on your own notes.
|
|
|
183
201
|
|
|
184
202
|
Graph RAG on SQLite for AI agents — a working pilot, not a framework. It is the extracted
|
|
185
203
|
memory layer of a personal "second brain" agent setup: vector search finds the entry
|
|
186
|
-
points, the `[[wikilinks]]` you already wrote by hand are the graph, and
|
|
187
|
-
|
|
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).
|
|
188
207
|
SQLite is the only database ([`schema.sql`](src/sqlite_graph_memory/schema.sql)).
|
|
189
208
|
|
|
190
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
|
|
@@ -207,12 +226,14 @@ For a single-user agent over a markdown knowledge base, all three are overkill:
|
|
|
207
226
|
- **SQLite is enough** — the only things worth persisting are derived state (a per-turn
|
|
208
227
|
ledger) and telemetry, and both are defined in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
|
|
209
228
|
One file, stdlib driver, zero ops.
|
|
210
|
-
-
|
|
211
|
-
|
|
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`.
|
|
212
233
|
|
|
213
234
|
So the pilot's bet: *vector retrieval for entry points, hand-curated wikilinks for
|
|
214
|
-
association,
|
|
215
|
-
|
|
235
|
+
association, SQLite for everything that must persist.* All steps live in one file,
|
|
236
|
+
`brain_ask.py`, in that order.
|
|
216
237
|
|
|
217
238
|
## Architecture
|
|
218
239
|
|
|
@@ -226,7 +247,8 @@ markdown notes (with [[wikilinks]])
|
|
|
226
247
|
├── brain_ask.py recall pipeline:
|
|
227
248
|
│ 1. dense retrieve top-60 chunks, dedup by file
|
|
228
249
|
│ 2. --graph +1-hop wikilink neighbours of top-15 hits (max 40)
|
|
229
|
-
│ 3.
|
|
250
|
+
│ 3. order dense similarity → top-12
|
|
251
|
+
│ (--rerank: cross-encoder instead, opt-in)
|
|
230
252
|
│ 4. --ab run vector-only AND vector+graph, diff,
|
|
231
253
|
│ log the delta to SQLite (ab_recall)
|
|
232
254
|
│
|
|
@@ -245,7 +267,7 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
245
267
|
### Design choices that survived contact with reality
|
|
246
268
|
|
|
247
269
|
- **Graph expansion is candidate generation, not ranking** (`brain_ask.py`). Neighbours go
|
|
248
|
-
into the same
|
|
270
|
+
into the same ranking pool as vector hits, so an irrelevant linked note gets buried.
|
|
249
271
|
That is what makes 1-hop expansion safe to leave on.
|
|
250
272
|
- **Entity gate** (`looks_like_entity` in `brain_ask.py`). A/B telemetry showed graph
|
|
251
273
|
expansion helps *theme* queries ("approaches to agent memory") but hurts *name/tool*
|
|
@@ -264,7 +286,7 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
264
286
|
|
|
265
287
|
- No entity lane. The production setup has an extra retrieval lane over people/project
|
|
266
288
|
cards; it is too entangled with personal data to publish.
|
|
267
|
-
-
|
|
289
|
+
- Packaging exists since v0.3.0 (`pip install sqlite-graph-memory`). There IS an eval suite now — see
|
|
268
290
|
[Measure before you swap](#measure-before-you-swap--eval) — but it scores retrieval on
|
|
269
291
|
wikilink-derived gold, which is weak supervision and says so out loud. Test coverage is uneven:
|
|
270
292
|
`index_notes.py`, `brain_ask.py` and `mcp_server.py` have unit tests, and
|
|
@@ -276,10 +298,10 @@ an edge table only when hop depth or corpus size demands it.
|
|
|
276
298
|
## Quickstart
|
|
277
299
|
|
|
278
300
|
```bash
|
|
279
|
-
# Indexing and reranking need
|
|
280
|
-
#
|
|
281
|
-
#
|
|
282
|
-
pip install 'sqlite-graph-memory[
|
|
301
|
+
# Indexing and reranking need an embedding stack; the base install leaves it out.
|
|
302
|
+
# [lite] runs the models on ONNX Runtime without torch (~155 MB); [embeddings]
|
|
303
|
+
# brings torch (~2 GB) if you want a GPU. Ask for one explicitly:
|
|
304
|
+
pip install 'sqlite-graph-memory[lite]'
|
|
283
305
|
|
|
284
306
|
# 1. index a folder of markdown notes
|
|
285
307
|
sgm-index /path/to/notes
|
|
@@ -303,7 +325,7 @@ To enable the per-turn ledger in Claude Code, register the Stop hook (the exact
|
|
|
303
325
|
sgm-turnstate-show --stats
|
|
304
326
|
```
|
|
305
327
|
|
|
306
|
-
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
|
|
307
329
|
same four commands, and the modules stay importable as
|
|
308
330
|
`from sqlite_graph_memory import brain_ask`.
|
|
309
331
|
|
|
@@ -404,6 +426,45 @@ is what runs. An eval that re-implements the pipeline measures the re-implementa
|
|
|
404
426
|
`--sqlite` appends one row per class and mode to a `gold_eval` table, which is how a run six
|
|
405
427
|
weeks from now can be diffed against today's.
|
|
406
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
|
+
|
|
407
468
|
### What it cost us to find out
|
|
408
469
|
|
|
409
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,15 +0,0 @@
|
|
|
1
|
-
sqlite_graph_memory/__init__.py,sha256=tqMLjmtW62GpxsI1IGGe5TYwaXqkVx0d1-bmFxOy2iE,1151
|
|
2
|
-
sqlite_graph_memory/brain_ask.py,sha256=rcXquak8fIYzKLPJL0GhrQGvbA0cVIcj805lNUjvcTY,19392
|
|
3
|
-
sqlite_graph_memory/doctor.py,sha256=zCdiOo9FIh_DKrDCUL3trI3q44xrtZTNVcFjL_XcD0o,5366
|
|
4
|
-
sqlite_graph_memory/index_notes.py,sha256=blm9lLlB5MSLB39tNYVtjVGULLQXTQGOth_LV4utyic,5378
|
|
5
|
-
sqlite_graph_memory/mcp_server.py,sha256=GItrJrtU34lGzamSD1ryEfL-Aq46W_J-4eDBZ3Pr_Wo,10218
|
|
6
|
-
sqlite_graph_memory/ppr.py,sha256=L7VSAiliXr8j3PH2hQqKbdgm08BPm6pZkLcckoMxAro,10001
|
|
7
|
-
sqlite_graph_memory/schema.sql,sha256=8aySXKw3Azaxyzqbd76mKTfOaDP7FlpkLXtgwA8ZVK4,2543
|
|
8
|
-
sqlite_graph_memory/turnstate_hook.py,sha256=fypGmUcHQkzlRN74tvIG07lr9uAXpp2GjetqthkuMc8,8641
|
|
9
|
-
sqlite_graph_memory/turnstate_show.py,sha256=IED7fmJQM5VgBNwxmEoNSZtujRmWja-qVPg5ckbWVnY,2909
|
|
10
|
-
sqlite_graph_memory/vault_stats.py,sha256=QYNGck556RDyLIVFH1C864su5tWehep1DHE21sSTi9g,8596
|
|
11
|
-
sqlite_graph_memory-0.3.5.dist-info/METADATA,sha256=ATapZ36CIk5AOwyHevNLQX3YqB7MTy7WX2j6JqNJV_I,36912
|
|
12
|
-
sqlite_graph_memory-0.3.5.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
-
sqlite_graph_memory-0.3.5.dist-info/entry_points.txt,sha256=lpoCm-jNjhBEtcQ16iIUd0ivr92Gr4c_fSRls2Zvbb0,432
|
|
14
|
-
sqlite_graph_memory-0.3.5.dist-info/licenses/LICENSE,sha256=p88nZdrfMUiES3_MpUEwhGmqz2hQFpyMh0k0cqdpfU8,1082
|
|
15
|
-
sqlite_graph_memory-0.3.5.dist-info/RECORD,,
|
|
File without changes
|
{sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.7.dist-info}/entry_points.txt
RENAMED
|
File without changes
|
{sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.7.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|