sqlite-graph-memory 0.3.8__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.8"
24
+ __version__ = "0.3.9"
25
25
 
26
26
  __all__ = ["__version__"]
@@ -143,15 +143,25 @@ FENCED_CODE_RX = re.compile(r'(?:```[\s\S]*?```|~~~[\s\S]*?~~~)')
143
143
  INLINE_CODE_RX = re.compile(r'`+[^`\n]*`+')
144
144
  WIKILINK_RX = re.compile(r'\[\[([^\]\|#]+)')
145
145
 
146
- def _links_in(path):
147
- """Outgoing wikilink TARGETS in a note (alias/heading stripped, code ignored)."""
148
- try: t = Path(path).read_text(encoding='utf-8', errors='ignore')
149
- except Exception: return []
146
+ def links_in_text(t):
147
+ """Outgoing wikilink TARGETS in note text (alias/heading stripped, code ignored)."""
150
148
  t = FENCED_CODE_RX.sub('', t)
151
149
  t = INLINE_CODE_RX.sub('', t)
152
150
  return [m.strip() for m in WIKILINK_RX.findall(t)]
153
151
 
154
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
+
155
165
  FRONTMATTER_RX = re.compile(r'^---\r?\n(.*?)\r?\n---', re.DOTALL)
156
166
  SUPERSEDED_BY_RX = re.compile(r'^superseded_by\s*:\s*"?(.+?)"?\s*$', re.MULTILINE)
157
167
 
@@ -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.8
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
@@ -64,6 +64,8 @@ Claude Code, Cursor, Codex or any other MCP client can recall from it.
64
64
 
65
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
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
+
67
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)
68
70
 
69
71
  **Your agent forgets everything between sessions, and plain vector search gives it back
@@ -93,6 +95,14 @@ Then point your client at the server. Use the absolute path of that index folder
93
95
 
94
96
  **Claude Code**
95
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
+
96
106
  ```bash
97
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
98
108
  ```
@@ -227,7 +237,8 @@ For a single-user agent over a markdown knowledge base, all three are overkill:
227
237
  No extraction pass, and edge quality beats anything a model would mine.
228
238
  - **SQLite is enough** — the only things worth persisting are derived state (a per-turn
229
239
  ledger) and telemetry, and both are defined in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
230
- 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.
231
242
  - **Measure before adding a stage.** The pilot shipped a cross-encoder reranker from day one;
232
243
  measured later, it lowered recall on long queries (our 184-question gold set: body nDCG@12
233
244
  0.640 reranked vs 0.815 dense; DolphinBench Riley slice, 1000 sessions: R@5 0.48 vs 0.61).
@@ -259,6 +270,8 @@ markdown notes (with [[wikilinks]])
259
270
  (ask, summary, files, tools, commands, decisions)
260
271
  to SQLite (turns). 0 LLM tokens, pure stdlib.
261
272
  turnstate_show.py = read-only viewer.
273
+ Off the recall path: nothing in recall
274
+ reads this table.
262
275
  ```
263
276
 
264
277
  [`schema.sql`](src/sqlite_graph_memory/schema.sql) documents both tables. The graph is **not** materialized in SQL:
@@ -276,9 +289,9 @@ an edge table only when hop depth or corpus size demands it.
276
289
  lookups ("NotebookLM"): a name's card links to everything, so the hop pulls in noise.
277
290
  The heuristic in `brain_ask.py` is deliberately conservative, and switches the graph off
278
291
  only for name-shaped queries.
279
- - **Crash-safety as a policy.** The graph hop (`brain_ask.py`) and the Stop-hook
280
- (`turnstate_hook.py`) are both wrapped, so any failure degrades to the previous behavior:
281
- 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.
282
295
  A memory layer must never make the agent worse than having no memory layer.
283
296
  - **Measure, don't believe.** `--ab` runs both pipelines on every real query and logs how
284
297
  many notes the graph promoted into the top-N, to `ab_recall` in [`schema.sql`](src/sqlite_graph_memory/schema.sql).
@@ -321,7 +334,8 @@ Run any of them on a base install and they tell you which extra is missing rathe
321
334
  raising `ModuleNotFoundError` — that path is covered by `tests/test_optional_extra.py`.
322
335
 
323
336
  To enable the per-turn ledger in Claude Code, register the Stop hook (the exact block is
324
- `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.
325
339
 
326
340
  ```bash
327
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=QCN9lXNZb7O0BUmBobR0XGrQUJyConcxQGEXAVO8C9E,1151
2
- sqlite_graph_memory/brain_ask.py,sha256=TeQTZI74muSve84ESv4lBsSUyCLhr58unHpqIFXRoJ4,29535
3
- sqlite_graph_memory/doctor.py,sha256=fOHoCV7XdDfYNIb3-tpa6sJtwzKBSH-EhsTpA0uQ9Qo,6005
4
- sqlite_graph_memory/index_notes.py,sha256=yhlpdAhi9mGBSdiE2xJI3soMT4s12A15XZX37ZIIU88,10958
5
- sqlite_graph_memory/mcp_server.py,sha256=Oza1UFA0V8OEhDbFrHDYdexbxwnq99N1xbTTjhmAhss,10251
6
- sqlite_graph_memory/onnx_backend.py,sha256=1P4sy5LrI_j4dgB-taFoakrDbn2JQIQnnmOuH7bA0ZM,5377
7
- sqlite_graph_memory/ppr.py,sha256=L7VSAiliXr8j3PH2hQqKbdgm08BPm6pZkLcckoMxAro,10001
8
- sqlite_graph_memory/schema.sql,sha256=8aySXKw3Azaxyzqbd76mKTfOaDP7FlpkLXtgwA8ZVK4,2543
9
- sqlite_graph_memory/turnstate_hook.py,sha256=fypGmUcHQkzlRN74tvIG07lr9uAXpp2GjetqthkuMc8,8641
10
- sqlite_graph_memory/turnstate_show.py,sha256=Bij4POJNSbJunHwGgm4i2NzkJQms8QBpR0mM9VVeKy4,3251
11
- sqlite_graph_memory/vault_stats.py,sha256=zlJm1b7HTiYIpZe8_7OUM-ywszeQjsQrj8zvkqnuI5w,9496
12
- sqlite_graph_memory-0.3.8.dist-info/METADATA,sha256=RhyEbXrPBRPSyUqqbrUsd4YVEcOcsitKoT0gXaffLUY,42019
13
- sqlite_graph_memory-0.3.8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
- sqlite_graph_memory-0.3.8.dist-info/entry_points.txt,sha256=lpoCm-jNjhBEtcQ16iIUd0ivr92Gr4c_fSRls2Zvbb0,432
15
- sqlite_graph_memory-0.3.8.dist-info/licenses/LICENSE,sha256=p88nZdrfMUiES3_MpUEwhGmqz2hQFpyMh0k0cqdpfU8,1082
16
- sqlite_graph_memory-0.3.8.dist-info/RECORD,,