sqlite-graph-memory 0.3.7__py3-none-any.whl → 0.3.9__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.
@@ -21,6 +21,6 @@ the indexer and the reranker will tell you what is missing instead of failing
21
21
  on an ``ImportError`` at startup.
22
22
  """
23
23
 
24
- __version__ = "0.3.7"
24
+ __version__ = "0.3.9"
25
25
 
26
26
  __all__ = ["__version__"]
@@ -9,11 +9,13 @@ USAGE:
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)
13
14
  python brain_ask.py --rerank "question" # opt in to the cross-encoder rerank (off by default)
14
15
 
15
16
  Config (env, all optional):
16
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)
17
19
  TURNSTATE_DB SQLite db for A/B telemetry (default: ./turnstate.db)
18
20
  BRAIN_ANSWER_OUT file to mirror the answer into (default: ./_brain_answer.txt)
19
21
  BRAIN_AB_JSON if set, --ab also writes a structured JSON diff to this path
@@ -141,15 +143,50 @@ FENCED_CODE_RX = re.compile(r'(?:```[\s\S]*?```|~~~[\s\S]*?~~~)')
141
143
  INLINE_CODE_RX = re.compile(r'`+[^`\n]*`+')
142
144
  WIKILINK_RX = re.compile(r'\[\[([^\]\|#]+)')
143
145
 
144
- def _links_in(path):
145
- """Outgoing wikilink TARGETS in a note (alias/heading stripped, code ignored)."""
146
- try: t = Path(path).read_text(encoding='utf-8', errors='ignore')
147
- except Exception: return []
146
+ def links_in_text(t):
147
+ """Outgoing wikilink TARGETS in note text (alias/heading stripped, code ignored)."""
148
148
  t = FENCED_CODE_RX.sub('', t)
149
149
  t = INLINE_CODE_RX.sub('', t)
150
150
  return [m.strip() for m in WIKILINK_RX.findall(t)]
151
151
 
152
152
 
153
+ def read_for_links(path):
154
+ """Note text exactly as the graph hop reads it, or None if unreadable."""
155
+ try: return Path(path).read_text(encoding='utf-8', errors='ignore')
156
+ except Exception: return None
157
+
158
+
159
+ def _links_in(path):
160
+ """Outgoing wikilink TARGETS in a note (alias/heading stripped, code fences ignored)."""
161
+ t = read_for_links(path)
162
+ return links_in_text(t) if t is not None else []
163
+
164
+
165
+ FRONTMATTER_RX = re.compile(r'^---\r?\n(.*?)\r?\n---', re.DOTALL)
166
+ SUPERSEDED_BY_RX = re.compile(r'^superseded_by\s*:\s*"?(.+?)"?\s*$', re.MULTILINE)
167
+
168
+
169
+ def _superseded_links_in(path):
170
+ """The `superseded_by` TARGET(s) from a note's YAML frontmatter (issue #93).
171
+
172
+ Followed regardless of the entity gate: a query that trips looks_like_entity()
173
+ still needs to reach the replacement of an outdated note, even though general
174
+ wikilink expansion is gated off for that query."""
175
+ try: t = Path(path).read_text(encoding='utf-8', errors='ignore')
176
+ except Exception: return []
177
+ fm = FRONTMATTER_RX.match(t)
178
+ if not fm:
179
+ return []
180
+ m = SUPERSEDED_BY_RX.search(fm.group(1))
181
+ if not m:
182
+ return []
183
+ val = m.group(1).strip().strip('"').strip("'").strip()
184
+ if not val:
185
+ return []
186
+ links = [l.strip() for l in WIKILINK_RX.findall(val) if l.strip()]
187
+ return links if links else [val]
188
+
189
+
153
190
 
154
191
  # --------------------------------------------------------------------------- pipeline
155
192
  # The retrieval pipeline lives in these functions so that anything measuring it
@@ -306,10 +343,15 @@ def _resolve_target_chunks(tgt, by_base, meta, root=None):
306
343
  return exact if exact else suffix_matches
307
344
 
308
345
 
309
- def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX, root=None):
346
+ def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX, root=None,
347
+ only_superseded=False):
310
348
  """Follow 1-hop OUTGOING wikilinks from the top vector hits and return the neighbour
311
349
  chunks to ADD to the candidate set; the reranker decides whether they are relevant.
312
350
 
351
+ only_superseded=True follows only a note's superseded_by frontmatter target instead
352
+ of every wikilink (issue #93): the entity gate uses this to still reach a replacement
353
+ note while leaving general wikilink expansion gated off.
354
+
313
355
  Bounded by ghops/gmax. CRASH-SAFETY: any failure returns [] and the caller degrades to
314
356
  vector-only -- worst case you get the old result, never an empty or broken recall."""
315
357
  added = []
@@ -322,7 +364,8 @@ def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX, ro
322
364
  root = vault_root(meta)
323
365
  in_order = set(base_order)
324
366
  for i in base_order[:ghops]:
325
- for tgt in _links_in(meta[i]['path']):
367
+ targets = _superseded_links_in(meta[i]['path']) if only_superseded else _links_in(meta[i]['path'])
368
+ for tgt in targets:
326
369
  idxs = _resolve_target_chunks(tgt, by_base, meta, root=root)
327
370
  if not idxs: continue
328
371
  best = max(idxs, key=lambda j: sims[j]) # best chunk of neighbour for THIS query
@@ -449,12 +492,56 @@ def maybe_star_prompt(stream=None, env=None, interactive=None):
449
492
  return False
450
493
 
451
494
 
495
+ def _parse_pool(args, env=None):
496
+ """Extract optional `--pool N` / `--topk-retrieve N` (or BRAIN_TOPK_RETRIEVE) -> (int|None, remaining_args)."""
497
+ env = os.environ if env is None else env
498
+ pool = None
499
+ env_val = (env.get('BRAIN_TOPK_RETRIEVE') or '').strip()
500
+ if env_val:
501
+ try:
502
+ pool = int(env_val)
503
+ except ValueError as exc:
504
+ sys.stderr.write('invalid BRAIN_TOPK_RETRIEVE=%r (expected positive integer)\n' % env_val)
505
+ raise SystemExit(2) from exc
506
+ if pool < 1:
507
+ sys.stderr.write('invalid BRAIN_TOPK_RETRIEVE=%r (must be >= 1)\n' % env_val)
508
+ raise SystemExit(2)
509
+ rest = []
510
+ i = 0
511
+ while i < len(args):
512
+ a = args[i]
513
+ if a in ('--pool', '--topk-retrieve'):
514
+ if i + 1 >= len(args):
515
+ sys.stderr.write('%s requires a positive integer argument\n' % a)
516
+ raise SystemExit(2)
517
+ raw = args[i + 1]
518
+ i += 2
519
+ elif a.startswith('--pool=') or a.startswith('--topk-retrieve='):
520
+ flag, _, raw = a.partition('=')
521
+ a = flag
522
+ i += 1
523
+ else:
524
+ rest.append(a)
525
+ i += 1
526
+ continue
527
+ try:
528
+ pool = int(raw)
529
+ except ValueError as exc:
530
+ sys.stderr.write('invalid %s value %r (expected positive integer)\n' % (a, raw))
531
+ raise SystemExit(2) from exc
532
+ if pool < 1:
533
+ sys.stderr.write('invalid %s value %r (must be >= 1)\n' % (a, raw))
534
+ raise SystemExit(2)
535
+ return pool, rest
536
+
537
+
452
538
  def main():
453
539
  args = sys.argv[1:]
454
540
  if '--version' in args:
455
541
  from sqlite_graph_memory import __version__
456
542
  print('sgm-ask %s' % __version__)
457
543
  return
544
+ pool, args = _parse_pool(args)
458
545
  ask = '--ask' in args
459
546
  graph = '--graph' in args; ab = '--ab' in args
460
547
  flags = {'--ask', '--graph', '--ab', '--ppr', '--rerank'}
@@ -471,7 +558,7 @@ def main():
471
558
  sims = query_sims(enc, emb, query)
472
559
 
473
560
  # dense retrieve -> dedup by path (best chunk per file) -> top-K unique files
474
- order = retrieve_candidates(sims, meta)
561
+ order = retrieve_candidates(sims, meta) if pool is None else retrieve_candidates(sims, meta, topk=pool)
475
562
 
476
563
  # Graph expansion: follow 1-hop OUTGOING wikilinks from the top vector hits, pull in
477
564
  # those neighbour notes (resolved to already-indexed chunks), then let the reranker
@@ -560,10 +647,16 @@ def main():
560
647
  return
561
648
 
562
649
  # GATE: wiki-graph helps THEME queries, hurts ENTITY/name queries -> skip graph for entities.
650
+ # Exception (issue #93): a superseded_by target still resolves even when gated, so an
651
+ # outdated note's replacement isn't dropped just because the query looks entity-like.
563
652
  gated = graph and looks_like_entity(query)
564
653
  if gated:
565
- sys.stderr.write("wiki-graph gated OFF (entity-like query) -> Direct only\n")
566
- order = graph_order if (graph and not gated) else base_order
654
+ sys.stderr.write("wiki-graph gated OFF (entity-like query) -> Direct only, except superseded_by\n")
655
+ sup_added = expand_1hop(sims, meta, base_order, only_superseded=True)
656
+ order = base_order + sup_added
657
+ graph_set = set(sup_added)
658
+ else:
659
+ order = graph_order if graph else base_order
567
660
  reranked = rerank(order)
568
661
  scope = 'all' + (' /graph+%d' % len(graph_set) if graph else '') + (' /ppr' if ppr_stems else '')
569
662
  lines = [f'QUERY: {query}', f'(scope={scope}; e5 {len(order)} files -> {"rerank" if ce is not None else "dense"}; {len(meta)} chunks)', '']
@@ -12,11 +12,9 @@ import sqlite3
12
12
  import sys
13
13
  from pathlib import Path
14
14
 
15
- from sqlite_graph_memory import brain_ask
16
-
17
15
  OK, WARN, FAIL = 'ok', 'warn', 'fail'
18
16
  MARK = {OK: '[ok] ', WARN: '[warn]', FAIL: '[FAIL]'}
19
- FEEDBACK = brain_ask.FEEDBACK_URL
17
+ FEEDBACK = 'https://github.com/tonydzi/sqlite-graph-memory/discussions/categories/ideas'
20
18
 
21
19
 
22
20
  def check_python(version=None):
@@ -40,7 +38,12 @@ def _intel_mac(system=None, machine=None):
40
38
 
41
39
  def check_embeddings(system=None, machine=None):
42
40
  """The heavy half. Without it the graph and the SQLite parts work, indexing and recall do not."""
43
- if brain_ask.backend() == 'onnx':
41
+ try:
42
+ from sqlite_graph_memory import brain_ask
43
+ is_onnx = (brain_ask.backend() == 'onnx')
44
+ except Exception:
45
+ is_onnx = (os.getenv('SGM_BACKEND', '').strip().lower() == 'onnx')
46
+ if is_onnx:
44
47
  try:
45
48
  import onnxruntime
46
49
  import tokenizers # noqa: F401
@@ -59,9 +62,13 @@ def check_embeddings(system=None, machine=None):
59
62
  import torch
60
63
  import sentence_transformers
61
64
  except ModuleNotFoundError as exc:
62
- return (WARN, 'The embeddings extra is not installed (%s missing).' % exc.name,
63
- 'Only needed to index and recall. Install it with: pip install "sqlite-graph-memory[lite]"'
64
- ' (or [embeddings] for torch and a GPU)')
65
+ if exc.name in ('torch', 'sentence_transformers'):
66
+ return (WARN, 'The embeddings extra is not installed (%s missing).' % exc.name,
67
+ 'Only needed to index and recall. Install it with: pip install "sqlite-graph-memory[lite]"'
68
+ ' (or [embeddings] for torch and a GPU)')
69
+ why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
70
+ return FAIL, 'torch or sentence-transformers fails to import (%s).' % why, \
71
+ 'Reinstall in a fresh virtualenv: pip install --force-reinstall "sqlite-graph-memory[embeddings]"'
65
72
  except Exception as exc: # torch dies at import on a numpy it was not built for
66
73
  why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
67
74
  if _intel_mac(system, machine) and np_major >= 2:
@@ -77,16 +84,31 @@ def check_embeddings(system=None, machine=None):
77
84
 
78
85
 
79
86
  def _hf_cache_dirs():
80
- roots = [os.getenv('HF_HUB_CACHE'), os.getenv('SENTENCE_TRANSFORMERS_HOME')]
81
- hf_home = os.getenv('HF_HOME') or str(Path.home() / '.cache' / 'huggingface')
82
- roots.append(str(Path(hf_home) / 'hub'))
83
- return [Path(r) for r in roots if r]
87
+ roots = []
88
+ if os.getenv('HF_HUB_CACHE'):
89
+ roots.append(Path(os.environ['HF_HUB_CACHE']))
90
+ elif os.getenv('HF_HOME'):
91
+ roots.append(Path(os.environ['HF_HOME']) / 'hub')
92
+ else:
93
+ xdg = os.getenv('XDG_CACHE_HOME')
94
+ base = Path(xdg) if xdg else Path.home() / '.cache'
95
+ roots.append(base / 'huggingface' / 'hub')
96
+
97
+ if os.getenv('SENTENCE_TRANSFORMERS_HOME'):
98
+ roots.append(Path(os.environ['SENTENCE_TRANSFORMERS_HOME']))
99
+
100
+ return [r for r in roots if r]
84
101
 
85
102
 
86
103
  def check_models():
87
104
  """Look for the two model folders in the local cache. Never downloads anything."""
105
+ try:
106
+ from sqlite_graph_memory import brain_ask
107
+ models = (brain_ask.E5_MODEL, brain_ask.RERANK_MODEL)
108
+ except Exception:
109
+ models = ('intfloat/multilingual-e5-base', 'cross-encoder/mmarco-mMiniLMv2-L12-H384-v1')
88
110
  missing = []
89
- for name in (brain_ask.E5_MODEL, brain_ask.RERANK_MODEL):
111
+ for name in models:
90
112
  folder = 'models--' + name.replace('/', '--')
91
113
  if not any((d / folder).exists() for d in _hf_cache_dirs()):
92
114
  missing.append(name)
@@ -97,7 +119,14 @@ def check_models():
97
119
 
98
120
 
99
121
  def check_index(index_dir=None):
100
- d = Path(index_dir) if index_dir else brain_ask.INDEX_DIR
122
+ if index_dir:
123
+ d = Path(index_dir)
124
+ else:
125
+ try:
126
+ from sqlite_graph_memory import brain_ask
127
+ d = brain_ask.INDEX_DIR
128
+ except Exception:
129
+ d = Path(os.getenv('BRAIN_INDEX_DIR', 'index'))
101
130
  emb, meta = d / '_brain_e5.npy', d / '_brain_e5_meta.pkl'
102
131
  if not emb.exists() and not meta.exists():
103
132
  return (WARN, 'No index in %s.' % d.resolve(),
@@ -105,6 +134,25 @@ def check_index(index_dir=None):
105
134
  if emb.exists() != meta.exists():
106
135
  left = meta.name if emb.exists() else emb.name
107
136
  return FAIL, 'The index is half there: %s is missing.' % left, 'Rebuild it: sgm-index /path/to/your/notes'
137
+ try:
138
+ import pickle
139
+ import numpy as np
140
+ raw_meta = meta.read_bytes()
141
+ if not raw_meta:
142
+ return FAIL, 'The index is empty: %s is 0 bytes.' % meta.name, 'Rebuild it: sgm-index /path/to/your/notes'
143
+ m = pickle.loads(raw_meta)
144
+ if not isinstance(m, list):
145
+ return FAIL, 'The index is corrupt: %s is not a list.' % meta.name, 'Rebuild it: sgm-index /path/to/your/notes'
146
+ if emb.stat().st_size == 0:
147
+ return FAIL, 'The index is empty: %s is 0 bytes.' % emb.name, 'Rebuild it: sgm-index /path/to/your/notes'
148
+ e = np.load(emb)
149
+ if len(e.shape) != 2 or e.shape[0] != len(m):
150
+ rows = e.shape[0] if len(e.shape) > 0 else 0
151
+ return FAIL, 'The index is corrupt: %s rows (%d) != %s chunks (%d).' % (
152
+ emb.name, rows, meta.name, len(m)), 'Rebuild it: sgm-index /path/to/your/notes'
153
+ except Exception as exc:
154
+ why = str(exc).splitlines()[0] if str(exc) else type(exc).__name__
155
+ return FAIL, 'The index is unreadable or truncated (%s).' % why, 'Rebuild it: sgm-index /path/to/your/notes'
108
156
  return OK, 'Index found in %s (%.1f MB).' % (d.resolve(), emb.stat().st_size / 1e6), ''
109
157
 
110
158
 
@@ -32,7 +32,9 @@ CHUNK_CHARS = 1200
32
32
  CHUNK_OVERLAP = 200
33
33
  SNIPPET_CHARS = 600
34
34
 
35
- FM_RX = re.compile(r'^---\r?\n(.*?)\r?\n---\r?\n', re.S)
35
+ # The closing fence may be the last line of the file: a note that is all frontmatter
36
+ # and has no final newline is still a note with frontmatter.
37
+ FM_RX = re.compile(r'^---\r?\n(.*?)\r?\n---[ \t]*(?:\r?\n|\Z)', re.S)
36
38
 
37
39
  try:
38
40
  from sqlite_graph_memory import brain_ask as _ba
@@ -62,6 +62,38 @@ def _links_in(path):
62
62
  return f(path)
63
63
 
64
64
 
65
+ def _normalize_target(tgt):
66
+ # Same normalization as the graph hop's _resolve_target_chunks, so both lanes
67
+ # read [[note]], [[note.md]] and [[folder/note]] the same way.
68
+ try:
69
+ from sqlite_graph_memory.brain_ask import _normalize_target as f
70
+ except ImportError: # run as a loose script next to brain_ask.py
71
+ from brain_ask import _normalize_target as f
72
+ return f(tgt)
73
+
74
+
75
+ def _resolve_target(tgt, idx, paths):
76
+ """Node for a wikilink target; None when no note matches.
77
+
78
+ Bare targets are the stem. A folder-qualified target must also match a path suffix:
79
+ [[projects/alpha]] points at projects/alpha.md, not at every note named alpha.
80
+ """
81
+ norm = _normalize_target(tgt)
82
+ if not norm:
83
+ return None
84
+ if '/' not in norm:
85
+ return idx.get(norm)
86
+ u = idx.get(norm.rsplit('/', 1)[-1])
87
+ if u is None:
88
+ return None
89
+ suffix = '/' + norm
90
+ for p in paths[u]:
91
+ rel = Path(p).with_suffix('').as_posix().lstrip('/').lower()
92
+ if rel == norm or ('/' + rel).endswith(suffix):
93
+ return u
94
+ return None
95
+
96
+
65
97
  class Graph:
66
98
  """File-level wikilink graph in CSR form: node = lowercase file stem."""
67
99
 
@@ -141,7 +173,7 @@ def build(meta):
141
173
  seen = set()
142
174
  for p in files:
143
175
  for tgt in _links_in(p):
144
- v = idx.get(tgt.strip().lower())
176
+ v = _resolve_target(tgt, idx, paths)
145
177
  if v is None or v == u or v in seen:
146
178
  continue
147
179
  seen.add(v)
@@ -9,7 +9,7 @@ and target resolution as ``brain_ask`` (``_links_in``, basename match, case-inse
9
9
  A second parser would report on a graph recall never sees.
10
10
 
11
11
  orphan rate pages with no inbound link ok <5% warn 5-15% fail >15%
12
- avg degree resolved outgoing links per page ok 3-8 warn 2-3 / 8-10 fail <2 or >10
12
+ avg degree resolved link names per page ok 3-8 warn 2-3 / 8-10 fail <2 or >10
13
13
  main component share of pages in the largest ok >=80% warn below
14
14
  weakly connected component
15
15
  stale concepts concept pages whose `updated` warn >50%
@@ -22,9 +22,13 @@ exist and links from a page to itself are not edges. A concept page is one with
22
22
  ``type: concept`` in its frontmatter or one that lives in a folder named ``concepts``
23
23
  inside the vault. Stale share is over all concept pages; undated ones (no date, or a
24
24
  date that is not a real day) are named in the detail and never count as stale.
25
- Verdicts are taken on the same rounded value the report prints.
25
+ Verdicts are taken on the same rounded value the report prints. Degree counts the link
26
+ names a page resolves, not the pages they fan out to: ``[[README]]`` with 300 README.md
27
+ files in the vault is one link, not 300. Each note is read once.
26
28
 
27
- Exit code: 0 all ok, 1 any warn, 2 any fail -- so it can sit in cron as a watchdog.
29
+ Exit code: 0 all ok, 1 any warn, 2 any fail -- so it can sit in cron as a watchdog. Notes
30
+ that cannot be read are counted, named and make the run at least a warn; a crash or a bad
31
+ flag exits 2, never 1, so a broken watchdog is never mistaken for a soft warning.
28
32
  Zero model calls, zero network, stdlib + the two sibling modules.
29
33
  """
30
34
  import argparse
@@ -36,8 +40,8 @@ from collections import defaultdict
36
40
  from pathlib import Path
37
41
 
38
42
  from sqlite_graph_memory import __version__
39
- from sqlite_graph_memory.brain_ask import _links_in, _normalize_target
40
- from sqlite_graph_memory.index_notes import FM_RX, iter_notes, read_note
43
+ from sqlite_graph_memory.brain_ask import _normalize_target, links_in_text, read_for_links
44
+ from sqlite_graph_memory.index_notes import FM_RX, iter_notes
41
45
 
42
46
  DEFAULTS = {
43
47
  'orphan_warn': 5.0, 'orphan_fail': 15.0,
@@ -48,7 +52,8 @@ DEFAULTS = {
48
52
  }
49
53
  RANK = {'ok': 0, 'warn': 1, 'fail': 2, 'n/a': 0}
50
54
 
51
- TYPE_RX = re.compile(r"""(?m)^type:\s*["']?([^"'\n]+?)["']?\s*$""")
55
+ # `type:` value on its own line, then any ` - item` lines under it (YAML block list).
56
+ TYPE_RX = re.compile(r"""(?m)^type:[ \t]*([^\n]*)((?:\n[ \t]*-[ \t][^\n]*)*)""")
52
57
  UPDATED_RX = re.compile(r"""(?m)^updated:\s*["']?(\d{4}-\d{2}-\d{2})""")
53
58
  DATE_RX = re.compile(r"""(?m)^date:\s*["']?(\d{4}-\d{2}-\d{2})""")
54
59
 
@@ -57,9 +62,10 @@ class EmptyVault(Exception):
57
62
  """No note under the folder: an unmounted or wrong path, reported as fail."""
58
63
 
59
64
 
60
- def build_graph(notes_dir):
61
- """(pages, edges): pages = {relative path without .md: Path},
62
- edges = {(src, dst)} between real pages."""
65
+ def scan(notes_dir):
66
+ """Read every note once. Returns pages {key: Path}, edges {(src, dst)}, the number
67
+ of resolved link names, concepts [(key, date or None)] and unreadable [key].
68
+ Only what the metrics need is kept: no note text, no per-page frontmatter."""
63
69
  root = Path(notes_dir)
64
70
  pages, by_path, by_stem = {}, defaultdict(list), defaultdict(list)
65
71
  for p in iter_notes(root):
@@ -67,25 +73,43 @@ def build_graph(notes_dir):
67
73
  pages[key] = p
68
74
  by_path[key.lower()].append(key)
69
75
  by_stem[p.stem.lower()].append(key)
70
- edges = set()
76
+ edges, n_links, concepts, unreadable = set(), 0, [], []
71
77
  for src, path in pages.items():
72
- for tgt in _links_in(path):
73
- norm = _normalize_target(tgt)
74
- if not norm:
78
+ text = read_for_links(path)
79
+ if text is None:
80
+ unreadable.append(src)
81
+ continue
82
+ m = FM_RX.match(text.lstrip('\ufeff'))
83
+ c = _concept(src, m.group(1) if m else '')
84
+ if c:
85
+ concepts.append(c)
86
+ names = set()
87
+ for tgt in links_in_text(text):
88
+ name = _normalize_target(tgt)
89
+ if not name:
75
90
  continue
76
- if '/' in norm:
77
- dsts = by_path.get(norm, ())
91
+ if '/' in name:
92
+ dsts = by_path.get(name, ())
78
93
  if not dsts:
79
- suffix = '/' + norm
94
+ suffix = '/' + name
80
95
  dsts = [
81
- k for k in by_stem.get(norm.rsplit('/', 1)[-1], ())
96
+ k for k in by_stem.get(name.rsplit('/', 1)[-1], ())
82
97
  if ('/' + k.lower()).endswith(suffix)
83
98
  ]
84
99
  else:
85
- dsts = by_stem.get(norm, ())
100
+ dsts = by_stem.get(name, ())
86
101
  for dst in dsts:
87
102
  if dst != src:
88
103
  edges.add((src, dst))
104
+ names.add(name)
105
+ n_links += len(names)
106
+ return pages, edges, n_links, concepts, unreadable
107
+
108
+
109
+ def build_graph(notes_dir):
110
+ """(pages, edges): pages = {relative path without .md: Path},
111
+ edges = {(src, dst)} between real pages."""
112
+ pages, edges = scan(notes_dir)[:2]
89
113
  return pages, edges
90
114
 
91
115
 
@@ -116,20 +140,46 @@ def _parse_day(s):
116
140
  return None
117
141
 
118
142
 
143
+ def fm_types(fm):
144
+ """Values of `type:` as a set: scalar, quoted, `[a, b]`, block list, `# comment`."""
145
+ m = TYPE_RX.search(fm)
146
+ if not m:
147
+ return set()
148
+ raw = [m.group(1)] + [l.split('-', 1)[1] for l in m.group(2).splitlines() if l.strip()]
149
+ out = set()
150
+ for chunk in raw:
151
+ quoted = re.match(r"""\s*(["'])(.*?)\1\s*(#.*)?$""", chunk)
152
+ if quoted: # one quoted scalar: `#` and `,` inside are text
153
+ item = quoted.group(2).strip().lower()
154
+ if item:
155
+ out.add(item)
156
+ continue
157
+ chunk = re.sub(r'(^|\s)#.*$', '', chunk).strip().strip('[]')
158
+ for item in chunk.split(','):
159
+ item = item.strip().strip('"\'').strip().lower()
160
+ if item:
161
+ out.add(item)
162
+ return out
163
+
164
+
165
+ def _concept(key, fm):
166
+ """(key, date or None) if the page is a concept page, else None."""
167
+ if 'concept' not in fm_types(fm) and \
168
+ not any(part.lower() == 'concepts' for part in Path(key).parent.parts):
169
+ return None
170
+ d = UPDATED_RX.search(fm) or DATE_RX.search(fm)
171
+ return key, _parse_day(d.group(1)) if d else None
172
+
173
+
119
174
  def concept_dates(pages):
120
- """[(key, date or None)] for every concept page."""
175
+ """[(key, date or None)] for every concept page in {key: Path}."""
121
176
  out = []
122
177
  for key, path in pages.items():
123
- text = read_note(path) or ''
124
- m = FM_RX.match(text)
125
- fm = m.group(1) if m else ''
126
- t = TYPE_RX.search(fm)
127
- is_concept = (t and t.group(1).strip().lower() == 'concept') or \
128
- any(part.lower() == 'concepts' for part in Path(key).parent.parts)
129
- if not is_concept:
130
- continue
131
- d = UPDATED_RX.search(fm) or DATE_RX.search(fm)
132
- out.append((key, _parse_day(d.group(1)) if d else None))
178
+ text = read_for_links(path) or ''
179
+ m = FM_RX.match(text.lstrip('\ufeff'))
180
+ c = _concept(key, m.group(1) if m else '')
181
+ if c:
182
+ out.append(c)
133
183
  return out
134
184
 
135
185
 
@@ -148,7 +198,7 @@ def verdict_degree(v, th):
148
198
  def compute(notes_dir, today=None, th=None):
149
199
  th = {**DEFAULTS, **(th or {})}
150
200
  today = today or datetime.date.today()
151
- pages, edges = build_graph(notes_dir)
201
+ pages, edges, n_links, concepts, unreadable = scan(notes_dir)
152
202
  n = len(pages)
153
203
  if n == 0:
154
204
  raise EmptyVault(f"sgm-stats: no notes under {notes_dir}")
@@ -158,13 +208,15 @@ def compute(notes_dir, today=None, th=None):
158
208
  indeg[dst] += 1
159
209
  orphans = sorted(p for p in pages if indeg[p] == 0)
160
210
  orphan_pct = round(100.0 * len(orphans) / n, 1)
161
- degree = round(len(edges) / n, 2)
211
+ degree = round(n_links / n, 2)
162
212
  main, n_comp = largest_component(pages, edges)
163
213
  main_pct = round(100.0 * main / n, 1)
164
214
 
165
- concepts = concept_dates(pages)
166
215
  dated = [(s, d) for s, d in concepts if d is not None]
167
- cutoff = today - datetime.timedelta(days=int(th['stale_days']))
216
+ try:
217
+ cutoff = today - datetime.timedelta(days=int(th['stale_days']))
218
+ except OverflowError:
219
+ cutoff = datetime.date.min
168
220
  stale = sorted(s for s, d in dated if d < cutoff)
169
221
  if concepts:
170
222
  stale_pct = round(100.0 * len(stale) / len(concepts), 1)
@@ -179,7 +231,7 @@ def compute(notes_dir, today=None, th=None):
179
231
  'examples': orphans[:5]},
180
232
  {'name': 'avg_degree', 'value': degree, 'unit': 'links/page',
181
233
  'verdict': verdict_degree(degree, th),
182
- 'detail': f"{len(edges)} resolved links over {n} pages"},
234
+ 'detail': f"{n_links} resolved links over {n} pages"},
183
235
  {'name': 'main_component', 'value': main_pct, 'unit': '%',
184
236
  'verdict': 'ok' if main_pct >= th['component_ok'] else 'warn',
185
237
  'detail': f"{main} of {n} pages; {n_comp} component{'' if n_comp == 1 else 's'}"},
@@ -192,6 +244,12 @@ def compute(notes_dir, today=None, th=None):
192
244
  if concepts else "no concept pages"),
193
245
  'examples': stale[:5]},
194
246
  ]
247
+ if unreadable:
248
+ metrics.append({'name': 'unreadable', 'value': len(unreadable), 'unit': 'files',
249
+ 'verdict': 'warn',
250
+ 'detail': f"{len(unreadable)} of {n} notes could not be read; "
251
+ "the numbers above exclude their links and frontmatter",
252
+ 'examples': sorted(unreadable)[:5]})
195
253
  worst = max(RANK[m['verdict']] for m in metrics)
196
254
  return {'notes_dir': str(notes_dir), 'pages': n, 'metrics': metrics,
197
255
  'verdict': ['ok', 'warn', 'fail'][worst], 'exit_code': worst}
@@ -202,11 +260,38 @@ def render(report):
202
260
  for m in report['metrics']:
203
261
  val = 'n/a' if m['value'] is None else f"{m['value']}{'%' if m['unit'] == '%' else ''}"
204
262
  lines.append(f"{m['verdict'].upper():<5} {m['name']:<15} {val:>7} {m['detail']}")
263
+ if m['name'] == 'unreadable' and m.get('examples'):
264
+ lines.append(' ' * 32 + 'e.g. ' + ', '.join(m['examples']))
205
265
  lines += ['', f"verdict: {report['verdict']}"]
206
266
  return '\n'.join(lines)
207
267
 
208
268
 
269
+ def _finite(s):
270
+ v = float(s)
271
+ if v != v or v in (float('inf'), float('-inf')):
272
+ raise argparse.ArgumentTypeError(f"not a finite number: {s}")
273
+ return v
274
+
275
+
276
+ def _days(s):
277
+ v = int(s)
278
+ if not 0 <= v <= 36500:
279
+ raise argparse.ArgumentTypeError(f"days must be 0..36500: {s}")
280
+ return v
281
+
282
+
209
283
  def main(argv=None):
284
+ try:
285
+ return _main(argv)
286
+ except SystemExit:
287
+ raise
288
+ except Exception: # crash = fail (2), never warn (1)
289
+ import traceback
290
+ traceback.print_exc()
291
+ return 2
292
+
293
+
294
+ def _main(argv=None):
210
295
  ap = argparse.ArgumentParser(prog='sgm-stats', description=__doc__.split('\n\n')[0])
211
296
  ap.add_argument('notes_dir')
212
297
  ap.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
@@ -214,7 +299,8 @@ def main(argv=None):
214
299
  ap.add_argument('--today', type=datetime.date.fromisoformat,
215
300
  help='date to measure staleness against (YYYY-MM-DD; default: today)')
216
301
  for key, val in DEFAULTS.items():
217
- ap.add_argument('--threshold-' + key.replace('_', '-'), dest=key, type=float,
302
+ ap.add_argument('--threshold-' + key.replace('_', '-'), dest=key,
303
+ type=_days if key == 'stale_days' else _finite,
218
304
  default=val, help=f'default {val}')
219
305
  a = ap.parse_args(argv)
220
306
  if not Path(a.notes_dir).is_dir():
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlite-graph-memory
3
- Version: 0.3.7
3
+ Version: 0.3.9
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,10 @@ 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
+
67
+ This package is layers 4 and 5 of a larger memory design (always-loaded instructions, auto memory, curated vault, verbatim originals, retrieval, turn ledger). The whole picture and a step-by-step install for you or your agent: [MEMORY.md in the starter kit](https://github.com/tonydzi/second-brain-starter-kit/blob/master/MEMORY.md) ([по-русски](https://github.com/tonydzi/second-brain-starter-kit/blob/master/MEMORY.ru.md)).
68
+
65
69
  ![sgm-index builds the index of the 202-note bench vault, then sgm-ask --ab shows tool-lanternfish entering the top 5 only through a graph hop; the one-minute CPU indexing wait is cut](docs/demo.gif)
66
70
 
67
71
  **Your agent forgets everything between sessions, and plain vector search gives it back
@@ -91,6 +95,14 @@ Then point your client at the server. Use the absolute path of that index folder
91
95
 
92
96
  **Claude Code**
93
97
 
98
+ As a plugin (asks for the index folder on install, Claude Code 2.1.275 or later):
99
+
100
+ ```
101
+ /plugin install sqlite-graph-memory --marketplace tonydzi/sqlite-graph-memory
102
+ ```
103
+
104
+ Or register the server by hand:
105
+
94
106
  ```bash
95
107
  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
96
108
  ```
@@ -225,7 +237,8 @@ For a single-user agent over a markdown knowledge base, all three are overkill:
225
237
  No extraction pass, and edge quality beats anything a model would mine.
226
238
  - **SQLite is enough** — the only things worth persisting are derived state (a per-turn
227
239
  ledger) and telemetry, and both are defined in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
228
- One file, stdlib driver, zero ops.
240
+ One file, stdlib driver, zero ops. The ledger is telemetry, not memory: recall never reads it,
241
+ so past turns do not change what `brain_ask.py` or the MCP server return.
229
242
  - **Measure before adding a stage.** The pilot shipped a cross-encoder reranker from day one;
230
243
  measured later, it lowered recall on long queries (our 184-question gold set: body nDCG@12
231
244
  0.640 reranked vs 0.815 dense; DolphinBench Riley slice, 1000 sessions: R@5 0.48 vs 0.61).
@@ -257,6 +270,8 @@ markdown notes (with [[wikilinks]])
257
270
  (ask, summary, files, tools, commands, decisions)
258
271
  to SQLite (turns). 0 LLM tokens, pure stdlib.
259
272
  turnstate_show.py = read-only viewer.
273
+ Off the recall path: nothing in recall
274
+ reads this table.
260
275
  ```
261
276
 
262
277
  [`schema.sql`](src/sqlite_graph_memory/schema.sql) documents both tables. The graph is **not** materialized in SQL:
@@ -274,9 +289,9 @@ an edge table only when hop depth or corpus size demands it.
274
289
  lookups ("NotebookLM"): a name's card links to everything, so the hop pulls in noise.
275
290
  The heuristic in `brain_ask.py` is deliberately conservative, and switches the graph off
276
291
  only for name-shaped queries.
277
- - **Crash-safety as a policy.** The graph hop (`brain_ask.py`) and the Stop-hook
278
- (`turnstate_hook.py`) are both wrapped, so any failure degrades to the previous behavior:
279
- vector-only recall, no ledger row.
292
+ - **Crash-safety as a policy.** The graph hop (`brain_ask.py`) is wrapped, so a failure
293
+ degrades recall to vector-only. The Stop-hook (`turnstate_hook.py`) is wrapped too, but it
294
+ sits off the recall path: a failure costs one ledger row and nothing else.
280
295
  A memory layer must never make the agent worse than having no memory layer.
281
296
  - **Measure, don't believe.** `--ab` runs both pipelines on every real query and logs how
282
297
  many notes the graph promoted into the top-N, to `ab_recall` in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
@@ -319,7 +334,8 @@ Run any of them on a base install and they tell you which extra is missing rathe
319
334
  raising `ModuleNotFoundError` — that path is covered by `tests/test_optional_extra.py`.
320
335
 
321
336
  To enable the per-turn ledger in Claude Code, register the Stop hook (the exact block is
322
- `examples/claude-code-stop-hook.json`, which calls `sgm-turnstate-hook`), then:
337
+ `examples/claude-code-stop-hook.json`, which calls `sgm-turnstate-hook`), then read it back with
338
+ `sgm-turnstate-show`. The ledger records what each turn did; recall never reads it.
323
339
 
324
340
  ```bash
325
341
  sgm-turnstate-show --stats
@@ -0,0 +1,16 @@
1
+ sqlite_graph_memory/__init__.py,sha256=079Dgg6bWzlCo7bZNbcPGN6Wgw5RTu6cENOlu91LCQk,1151
2
+ sqlite_graph_memory/brain_ask.py,sha256=KpL-hzi3LPREReJYQO8FwXcFJZRIz909Qk9MANWNzqg,29848
3
+ sqlite_graph_memory/doctor.py,sha256=-BfVVSGtlqM1lcNjofK9hwYp1dElv6kFXCwWYONG7EY,8332
4
+ sqlite_graph_memory/index_notes.py,sha256=pGJBZPDz_8YwIIAiVpBBWGyZkU026LvUIIk4qXDWEO8,11117
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=7GMMpUuT_j6BEMv2dZfy_WZIVdw3tiOhqpieQPYhcMA,11122
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=h3Y5jBxxYcqJ3skOwgl3vGCwdcOURiTpwc31S49-eAI,12826
12
+ sqlite_graph_memory-0.3.9.dist-info/METADATA,sha256=3B5CT1Y8oNKi0lceD9go73wE7BQeSrL-W6SJXY0RyQI,43063
13
+ sqlite_graph_memory-0.3.9.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
+ sqlite_graph_memory-0.3.9.dist-info/entry_points.txt,sha256=lpoCm-jNjhBEtcQ16iIUd0ivr92Gr4c_fSRls2Zvbb0,432
15
+ sqlite_graph_memory-0.3.9.dist-info/licenses/LICENSE,sha256=p88nZdrfMUiES3_MpUEwhGmqz2hQFpyMh0k0cqdpfU8,1082
16
+ sqlite_graph_memory-0.3.9.dist-info/RECORD,,
@@ -1,16 +0,0 @@
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,,