sqlite-graph-memory 0.3.5__tar.gz → 0.3.6__tar.gz

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.
Files changed (50) hide show
  1. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/CHANGELOG.md +12 -0
  2. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/PKG-INFO +15 -7
  3. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/README.md +10 -6
  4. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/pyproject.toml +10 -1
  5. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/__init__.py +1 -1
  6. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/brain_ask.py +66 -3
  7. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/doctor.py +12 -1
  8. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/index_notes.py +23 -14
  9. sqlite_graph_memory-0.3.6/src/sqlite_graph_memory/onnx_backend.py +127 -0
  10. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/turnstate_show.py +14 -6
  11. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/vault_stats.py +10 -2
  12. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_brain_ask.py +4 -0
  13. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_doctor.py +25 -1
  14. sqlite_graph_memory-0.3.6/tests/test_onnx_backend.py +149 -0
  15. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_optional_extra.py +2 -0
  16. sqlite_graph_memory-0.3.6/tests/test_turnstate_show.py +52 -0
  17. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_vault_stats.py +23 -1
  18. sqlite_graph_memory-0.3.6/tests/test_version_consistent.py +75 -0
  19. sqlite_graph_memory-0.3.6/tests/test_version_flag.py +36 -0
  20. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/.gitignore +0 -0
  21. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/CITATION.cff +0 -0
  22. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/LICENSE +0 -0
  23. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/bench/README.md +0 -0
  24. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/bench/requirements.txt +0 -0
  25. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/docs/RELEASING.md +0 -0
  26. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/docs/bitemporal.md +0 -0
  27. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/docs/demo.gif +0 -0
  28. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/docs/demo.sh +0 -0
  29. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/eval/build_gold.py +0 -0
  30. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/eval/run_eval.py +0 -0
  31. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/examples/README.md +0 -0
  32. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/examples/claude-code-stop-hook.json +0 -0
  33. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/examples/mcp-config.json +0 -0
  34. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/requirements.txt +0 -0
  35. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/mcp_server.py +0 -0
  36. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/ppr.py +0 -0
  37. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/schema.sql +0 -0
  38. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/src/sqlite_graph_memory/turnstate_hook.py +0 -0
  39. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_bench.py +0 -0
  40. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_changelog_released.py +0 -0
  41. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_eval.py +0 -0
  42. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_feedback_link.py +0 -0
  43. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_index_notes.py +0 -0
  44. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_index_notes_dotfiles.py +0 -0
  45. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_llms_txt.py +0 -0
  46. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_mcp_script_mode.py +0 -0
  47. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_mcp_server.py +0 -0
  48. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_ppr.py +0 -0
  49. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_star_prompt.py +0 -0
  50. {sqlite_graph_memory-0.3.5 → sqlite_graph_memory-0.3.6}/tests/test_turnstate_hook.py +0 -0
@@ -6,6 +6,18 @@ recorded after the fact rather than backdated to look contemporaneous.
6
6
 
7
7
  ## Unreleased
8
8
 
9
+ ## v0.3.6 - 2026-11-03
10
+
11
+ **Light backend: recall without torch.** New extra `[lite]` runs the same two models (multilingual-e5-base and the mMiniLMv2 reranker) on ONNX Runtime from their official ONNX exports: 155 MB installed instead of ~2 GB, and on the hub one MCP recall took 7.0 s instead of 33.8 s through torch, with the same hits and scores (embeddings agree to 3e-7). It is picked automatically when installed; `SGM_BACKEND=torch|onnx` forces either, and an index built by one backend works with the other. `pick_device()` no longer imports torch on this path: on a Windows CPU laptop that import alone took 44 s and pushed the first MCP call past the client's tool timeout (2026-11-01). Models stay in the persistent Hugging Face cache (`SGM_MODEL_CACHE` overrides), and `sgm-index` fetches the reranker too, so the first recall is not also a download. `sgm-doctor` reports the light backend. Install commands in README keep `[embeddings]` until `[lite]` is on PyPI.
12
+
13
+ **`sgm-turnstate-show`: a corrupt ledger gets one line, not a traceback.** When `TURNSTATE_DB` is not a SQLite file the command now prints `not a database: <path>` on stderr and exits 1, leaving the file untouched; a missing ledger keeps its friendly line. Thanks @ShahadatTest (#77), who picked up #74.
14
+
15
+ **`sgm-stats`: a wikilink inside inline code is no longer a graph edge.** `_links_in` already ignored fenced blocks; it now ignores inline code spans too, so an example like `` `[[x]]` `` stops inflating the link counts. Thanks @bfs2021 (#78), who picked up #72.
16
+
17
+ **`sgm-stats --json` on an empty folder prints JSON.** A cron script that parses the output now gets an object with `verdict: fail`, `exit_code: 2` and an `error` field instead of plain text; the exit code stays 2 and plain mode is unchanged. Thanks @sharmao07 (#79), who picked up #73.
18
+
19
+ **`--version` on `sgm-stats` and `sgm-ask`.** Both print the package version and exit 0; `sgm-ask` answers before it touches a model or an index. Thanks @BiswasNehaa (#81), who picked up #75.
20
+
9
21
  ## v0.3.5 - 2026-11-01
10
22
 
11
23
  **Release fix.** v0.3.4 was tagged but never reached PyPI: the release commit changed only this file, and the publish job stopped on its version check (pyproject, `__init__`, server.json still said 0.3.3). v0.3.5 is the first PyPI build with everything listed under v0.3.4 plus the entries below, with the version set in all four places.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlite-graph-memory
3
- Version: 0.3.5
3
+ Version: 0.3.6
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,7 +73,7 @@ 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 (proposed revision)](https://github.com/tonydzi/second-brain-starter-kit/blob/codex/dima-brain-H55019/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.
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
 
@@ -127,8 +131,12 @@ env = { BRAIN_INDEX_DIR = "/absolute/path/to/.sgm-index" }
127
131
 
128
132
  Size, `du -sh` of a fresh Python 3.12 venv on an x86_64 Mac (1 Nov 2026): the base install is
129
133
  26 MB and has no torch (numpy only, enough for the graph half and the SQLite ledger);
130
- with `[embeddings]`, which indexing and recall need, it is 879 MB, 540 MB of that torch 2.2.2
131
- CPU. On Linux the default torch wheel brings CUDA libraries and is bigger; not measured here.
134
+ with `[embeddings]` (torch) it is 879 MB, 540 MB of that torch 2.2.2 CPU. With `[lite]` (from v0.3.6),
135
+ the same two models on ONNX Runtime and no torch, it is 155 MB (Windows, Python 3.12,
136
+ 3 Nov 2026), installs in 12 s, and one MCP recall on the 202-note bench vault took 7.0 s
137
+ against 33.8 s through torch on the same machine, with the same top hits and scores.
138
+ `[lite]` is picked automatically when installed; `SGM_BACKEND=torch` forces torch (for a GPU).
139
+ An index built by either backend is searched correctly by the other.
132
140
  Already installed with pip? Replace `uvx --with ... sqlite-graph-memory` by `sgm-mcp`
133
141
  ([`examples/mcp-config.json`](examples/mcp-config.json)). Agents that read files first:
134
142
  [`llms.txt`](llms.txt).
@@ -276,9 +284,9 @@ an edge table only when hop depth or corpus size demands it.
276
284
  ## Quickstart
277
285
 
278
286
  ```bash
279
- # Indexing and reranking need the embedding stack; the base install leaves it out
280
- # so that `pip install sqlite-graph-memory` stays small instead of pulling ~2 GB
281
- # of torch. Ask for it explicitly:
287
+ # Indexing and reranking need an embedding stack; the base install leaves it out.
288
+ # [lite] (from v0.3.6) runs the models on ONNX Runtime without torch (~155 MB); [embeddings]
289
+ # brings torch (~2 GB) if you want a GPU. Ask for one explicitly:
282
290
  pip install 'sqlite-graph-memory[embeddings]'
283
291
 
284
292
  # 1. index a folder of markdown notes
@@ -18,7 +18,7 @@ One SQLite file, no graph database, no ETL pass, no server.**
18
18
 
19
19
  ## Install in your client
20
20
 
21
- Already using your own agent rules and projects? The [Russian existing-setup guide (proposed revision)](https://github.com/tonydzi/second-brain-starter-kit/blob/codex/dima-brain-H55019/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.
21
+ 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.
22
22
 
23
23
  Build the index once (any folder of markdown; [`uv`](https://docs.astral.sh/uv/) gives you `uvx`):
24
24
 
@@ -76,8 +76,12 @@ env = { BRAIN_INDEX_DIR = "/absolute/path/to/.sgm-index" }
76
76
 
77
77
  Size, `du -sh` of a fresh Python 3.12 venv on an x86_64 Mac (1 Nov 2026): the base install is
78
78
  26 MB and has no torch (numpy only, enough for the graph half and the SQLite ledger);
79
- with `[embeddings]`, which indexing and recall need, it is 879 MB, 540 MB of that torch 2.2.2
80
- CPU. On Linux the default torch wheel brings CUDA libraries and is bigger; not measured here.
79
+ with `[embeddings]` (torch) it is 879 MB, 540 MB of that torch 2.2.2 CPU. With `[lite]` (from v0.3.6),
80
+ the same two models on ONNX Runtime and no torch, it is 155 MB (Windows, Python 3.12,
81
+ 3 Nov 2026), installs in 12 s, and one MCP recall on the 202-note bench vault took 7.0 s
82
+ against 33.8 s through torch on the same machine, with the same top hits and scores.
83
+ `[lite]` is picked automatically when installed; `SGM_BACKEND=torch` forces torch (for a GPU).
84
+ An index built by either backend is searched correctly by the other.
81
85
  Already installed with pip? Replace `uvx --with ... sqlite-graph-memory` by `sgm-mcp`
82
86
  ([`examples/mcp-config.json`](examples/mcp-config.json)). Agents that read files first:
83
87
  [`llms.txt`](llms.txt).
@@ -225,9 +229,9 @@ an edge table only when hop depth or corpus size demands it.
225
229
  ## Quickstart
226
230
 
227
231
  ```bash
228
- # Indexing and reranking need the embedding stack; the base install leaves it out
229
- # so that `pip install sqlite-graph-memory` stays small instead of pulling ~2 GB
230
- # of torch. Ask for it explicitly:
232
+ # Indexing and reranking need an embedding stack; the base install leaves it out.
233
+ # [lite] (from v0.3.6) runs the models on ONNX Runtime without torch (~155 MB); [embeddings]
234
+ # brings torch (~2 GB) if you want a GPU. Ask for one explicitly:
231
235
  pip install 'sqlite-graph-memory[embeddings]'
232
236
 
233
237
  # 1. index a folder of markdown notes
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "sqlite-graph-memory"
7
- version = "0.3.5"
7
+ version = "0.3.6"
8
8
  description = "Associative memory for LLM agents: Graph RAG over a folder of markdown notes, in one SQLite file, with no server to run."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -40,6 +40,15 @@ classifiers = [
40
40
  dependencies = ["numpy>=1.24"]
41
41
 
42
42
  [project.optional-dependencies]
43
+ # The same two models on ONNX Runtime, no torch: ~60 MB instead of ~2 GB, and a recall
44
+ # that starts in seconds on a CPU laptop. Measured 2026-11-01 through the MCP server on
45
+ # Windows: `import torch` alone took 44 s and the client hit its 60 s tool timeout.
46
+ # brain_ask picks this stack automatically when it is installed (SGM_BACKEND overrides).
47
+ lite = [
48
+ "onnxruntime>=1.17",
49
+ "tokenizers>=0.15",
50
+ "huggingface_hub>=0.20",
51
+ ]
43
52
  # The indexer and the reranker need these; the graph half, the SQLite schema and
44
53
  # the turnstate memory do not. Kept out of the base install so that
45
54
  # `pip install sqlite-graph-memory` stays a two-second, ~20 MB operation instead
@@ -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.5"
24
+ __version__ = "0.3.6"
25
25
 
26
26
  __all__ = ["__version__"]
@@ -49,13 +49,37 @@ ENTITY_TOOLS = {'obsidian', 'syncthing', 'sqlite', 'telegram', 'whatsapp', 'n8n'
49
49
 
50
50
 
51
51
  _EMBEDDINGS_HINT = (
52
- "This step needs the optional embedding stack (sentence-transformers, torch).\n"
53
- "Install it with: pip install 'sqlite-graph-memory[embeddings]'\n"
52
+ "This step needs an embedding stack.\n"
53
+ "Light, no torch (~60 MB): pip install 'sqlite-graph-memory[lite]'\n"
54
+ "Torch, for a GPU: pip install 'sqlite-graph-memory[embeddings]'\n"
54
55
  "The base install stays small on purpose: the graph half, the SQLite schema\n"
55
56
  "and the turnstate memory work without it."
56
57
  )
57
58
 
58
59
 
60
+ def backend(env=None):
61
+ """'onnx' or 'torch': which stack runs the two models.
62
+
63
+ SGM_BACKEND=onnx|torch forces one. Unset (auto): ONNX whenever the lite stack is
64
+ installed, because it starts in seconds where torch took 44 s just to import on a
65
+ CPU laptop (2026-11-01); otherwise sentence-transformers, as before. Both run the
66
+ same checkpoints, so an index built by one is searched correctly by the other.
67
+ """
68
+ env = os.environ if env is None else env
69
+ want = (env.get('SGM_BACKEND') or 'auto').strip().lower()
70
+ if want in ('onnx', 'torch'):
71
+ return want
72
+ return 'onnx' if _onnx().available() else 'torch'
73
+
74
+
75
+ def _onnx():
76
+ try:
77
+ from sqlite_graph_memory import onnx_backend
78
+ except ImportError: # run as a loose script next to onnx_backend.py
79
+ import onnx_backend
80
+ return onnx_backend
81
+
82
+
59
83
  def _require_sentence_transformers():
60
84
  """Import sentence_transformers, or exit with instructions.
61
85
 
@@ -71,6 +95,10 @@ def _require_sentence_transformers():
71
95
  return sentence_transformers
72
96
 
73
97
  def pick_device():
98
+ # The ONNX path runs on CPU; importing torch here only to ask about CUDA was the
99
+ # 44-second stall the lite backend exists to remove.
100
+ if backend() == 'onnx':
101
+ return 'cpu'
74
102
  try:
75
103
  import torch
76
104
  return 'cuda' if torch.cuda.is_available() else 'cpu'
@@ -106,13 +134,15 @@ def looks_like_entity(q):
106
134
 
107
135
 
108
136
  FENCED_CODE_RX = re.compile(r'(?:```[\s\S]*?```|~~~[\s\S]*?~~~)')
137
+ INLINE_CODE_RX = re.compile(r'`+[^`\n]*`+')
109
138
  WIKILINK_RX = re.compile(r'\[\[([^\]\|#]+)')
110
139
 
111
140
  def _links_in(path):
112
- """Outgoing wikilink TARGETS in a note (alias/heading stripped, code fences ignored)."""
141
+ """Outgoing wikilink TARGETS in a note (alias/heading stripped, code ignored)."""
113
142
  try: t = Path(path).read_text(encoding='utf-8', errors='ignore')
114
143
  except Exception: return []
115
144
  t = FENCED_CODE_RX.sub('', t)
145
+ t = INLINE_CODE_RX.sub('', t)
116
146
  return [m.strip() for m in WIKILINK_RX.findall(t)]
117
147
 
118
148
 
@@ -129,13 +159,42 @@ def load_index(emb_path=None, meta_path=None):
129
159
  return emb, meta
130
160
 
131
161
 
162
+ def _try_onnx(kind):
163
+ """The ONNX model, or None to fall back to torch.
164
+
165
+ Only an auto-picked ONNX falls back: someone who already has the torch models cached
166
+ and gets onnxruntime from another package may be offline, with no ONNX files yet.
167
+ Their recall must keep working on torch. SGM_BACKEND=onnx raises instead.
168
+ """
169
+ if backend() != 'onnx':
170
+ return None
171
+ try:
172
+ return getattr(_onnx(), kind)()
173
+ except Exception as exc:
174
+ if (os.getenv('SGM_BACKEND') or '').strip().lower() == 'onnx':
175
+ raise
176
+ try:
177
+ import sentence_transformers # noqa: F401
178
+ except ImportError:
179
+ raise exc
180
+ sys.stderr.write('ONNX %s unavailable (%s: %s); using torch\n'
181
+ % (kind, type(exc).__name__, str(exc).splitlines()[0] if str(exc) else ''))
182
+ return None
183
+
184
+
132
185
  def load_encoder(dev=None):
186
+ m = _try_onnx('Encoder')
187
+ if m is not None:
188
+ return m
133
189
  _require_sentence_transformers()
134
190
  from sentence_transformers import SentenceTransformer
135
191
  return SentenceTransformer(E5_MODEL, device=dev or pick_device())
136
192
 
137
193
 
138
194
  def load_reranker(dev=None):
195
+ m = _try_onnx('CrossEncoder')
196
+ if m is not None:
197
+ return m
139
198
  _require_sentence_transformers()
140
199
  from sentence_transformers import CrossEncoder
141
200
  return CrossEncoder(RERANK_MODEL, device=dev or pick_device())
@@ -294,6 +353,10 @@ def maybe_star_prompt(stream=None, env=None, interactive=None):
294
353
 
295
354
  def main():
296
355
  args = sys.argv[1:]
356
+ if '--version' in args:
357
+ from sqlite_graph_memory import __version__
358
+ print('sgm-ask %s' % __version__)
359
+ return
297
360
  ask = '--ask' in args
298
361
  graph = '--graph' in args; ab = '--ab' in args
299
362
  flags = {'--ask', '--graph', '--ab', '--ppr'}
@@ -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[embeddings]"')
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:
@@ -29,12 +29,12 @@ FM_RX = re.compile(r'^---\r?\n(.*?)\r?\n---\r?\n', re.S)
29
29
 
30
30
 
31
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
- )
32
+ try:
33
+ from sqlite_graph_memory import brain_ask as _ba
34
+ except ImportError: # run as a loose script next to brain_ask.py
35
+ import brain_ask as _ba
36
+
37
+ _EMBEDDINGS_HINT = _ba._EMBEDDINGS_HINT
38
38
 
39
39
 
40
40
  def _require_sentence_transformers():
@@ -130,14 +130,23 @@ def main():
130
130
  if not texts:
131
131
  print('no indexable .md notes found under', notes_dir); return
132
132
 
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)
133
+ if _ba.backend() == 'onnx':
134
+ enc = _ba.load_encoder()
135
+ # Fetch the reranker too: otherwise the first recall from an MCP client is also
136
+ # a ~470 MB download and runs into the client's tool timeout.
137
+ try:
138
+ _ba._onnx().prefetch()
139
+ except Exception as exc: # offline: the first recall fetches it instead
140
+ print('reranker not prefetched (%s); the first recall will fetch it' % type(exc).__name__)
141
+ else:
142
+ _require_sentence_transformers()
143
+ from sentence_transformers import SentenceTransformer
144
+ try:
145
+ import torch
146
+ dev = 'cuda' if torch.cuda.is_available() else 'cpu'
147
+ except Exception:
148
+ dev = 'cpu'
149
+ enc = SentenceTransformer(E5_MODEL, device=dev)
141
150
  emb = enc.encode(texts, normalize_embeddings=True, convert_to_numpy=True,
142
151
  batch_size=64, show_progress_bar=True).astype('float32')
143
152
 
@@ -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, ")"); return
42
- c = sqlite3.connect(DB)
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,6 +35,7 @@ import sys
35
35
  from collections import defaultdict
36
36
  from pathlib import Path
37
37
 
38
+ from sqlite_graph_memory import __version__
38
39
  from sqlite_graph_memory.brain_ask import _links_in
39
40
  from sqlite_graph_memory.index_notes import FM_RX, iter_notes, read_note
40
41
 
@@ -194,6 +195,7 @@ def render(report):
194
195
  def main(argv=None):
195
196
  ap = argparse.ArgumentParser(prog='sgm-stats', description=__doc__.split('\n\n')[0])
196
197
  ap.add_argument('notes_dir')
198
+ ap.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
197
199
  ap.add_argument('--json', action='store_true', help='machine-readable output')
198
200
  ap.add_argument('--today', type=datetime.date.fromisoformat,
199
201
  help='date to measure staleness against (YYYY-MM-DD; default: today)')
@@ -207,8 +209,14 @@ def main(argv=None):
207
209
  try:
208
210
  report = compute(a.notes_dir, today=a.today, th=th)
209
211
  except EmptyVault as e:
210
- print(e, file=sys.stderr)
211
- return 2
212
+ if a.json:
213
+ report = {
214
+ 'notes_dir': str(a.notes_dir), 'pages': 0, 'metrics': [],
215
+ 'verdict': 'fail', 'exit_code': 2, 'error': str(e),
216
+ }
217
+ else:
218
+ print(e, file=sys.stderr)
219
+ return 2
212
220
  print(json.dumps(report, indent=2, ensure_ascii=False) if a.json else render(report))
213
221
  return report['exit_code']
214
222
 
@@ -100,6 +100,10 @@ def test_looks_like_entity(query, expected):
100
100
  "Another outside [[another_valid#anchor|alias]].",
101
101
  ["valid_note", "another_valid"],
102
102
  ),
103
+ # A wikilink inside inline code should NOT count
104
+ ("Write `[[example]]` to link.", []),
105
+ # Inline code hides its link, the surrounding sentence still counts
106
+ ("Outside [[real]]. Inside `[[example]]` only.", ["real"]),
103
107
  ],
104
108
  )
105
109
  def test_links_in_content_cases(tmp_path, content, expected):
@@ -40,12 +40,36 @@ def test_models_missing_when_cache_is_empty(tmp_path, monkeypatch):
40
40
 
41
41
 
42
42
  def test_missing_torch_is_a_warning_not_a_failure(monkeypatch):
43
+ monkeypatch.setenv("SGM_BACKEND", "torch")
43
44
  monkeypatch.setitem(sys.modules, "torch", None) # import torch -> ModuleNotFoundError
44
45
  status, what, fix = doctor.check_embeddings()
45
- assert status == doctor.WARN and "embeddings" in fix
46
+ assert status == doctor.WARN and "embeddings" in fix and "lite" in fix
47
+
48
+
49
+ def test_light_backend_is_ok_without_torch(monkeypatch):
50
+ import pytest
51
+ pytest.importorskip("onnxruntime")
52
+ monkeypatch.setenv("SGM_BACKEND", "onnx")
53
+ monkeypatch.setitem(sys.modules, "torch", None)
54
+ status, what, _ = doctor.check_embeddings()
55
+ assert status == doctor.OK and "onnxruntime" in what
56
+
57
+
58
+ import pytest # noqa: E402
59
+
60
+
61
+ @pytest.mark.parametrize("missing", ["onnxruntime", "tokenizers", "huggingface_hub"])
62
+ def test_incomplete_light_backend_fails(monkeypatch, missing):
63
+ """Codex review 2026-11-03: onnxruntime alone used to print ok while recall died."""
64
+ monkeypatch.setenv("SGM_BACKEND", "onnx")
65
+ monkeypatch.setitem(sys.modules, missing, None)
66
+ status, what, fix = doctor.check_embeddings()
67
+ # Names the first missing package, which on a runner without [lite] is onnxruntime.
68
+ assert status == doctor.FAIL and "[lite]" in fix and "incomplete" in what
46
69
 
47
70
 
48
71
  def test_broken_torch_on_intel_mac_points_at_numpy(monkeypatch):
72
+ monkeypatch.setenv("SGM_BACKEND", "torch")
49
73
  class Boom:
50
74
  def __getattr__(self, name):
51
75
  raise RuntimeError("Numpy is not available")
@@ -0,0 +1,149 @@
1
+ # -*- coding: utf-8 -*-
2
+ """The light (ONNX) backend: picked when installed, never imports torch, same numbers.
3
+
4
+ Why: through the MCP server on a Windows CPU laptop (2026-11-01) `import torch` alone took
5
+ 44 s inside pick_device(), the encoder had not loaded at 90 s, and the client gave up at its
6
+ 60 s tool timeout. The light path must not touch torch at all, not even to ask about CUDA.
7
+
8
+ RED-FIRST: drop the `backend() == 'onnx'` early return from brain_ask.pick_device and
9
+ test_pick_device_does_not_import_torch fails; drop the onnx branch from load_encoder and
10
+ test_loaders_use_onnx_without_sentence_transformers fails with SystemExit.
11
+
12
+ The last test downloads the two models (~1.6 GB once) and is skipped unless
13
+ SGM_LIVE_MODELS=1. Reference logits were measured with sentence-transformers 6.1 on CPU.
14
+ """
15
+ import builtins
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ import pytest
20
+
21
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
22
+
23
+ from sqlite_graph_memory import brain_ask, onnx_backend # noqa: E402
24
+
25
+
26
+ @pytest.fixture
27
+ def torch_forbidden(monkeypatch):
28
+ """Record every attempt to import torch or sentence_transformers.
29
+
30
+ The attempts are recorded, not only refused: pick_device() wraps its torch import in
31
+ `except Exception`, so a raising fake alone would be swallowed and the test stay green.
32
+ """
33
+ real_import = builtins.__import__
34
+ attempts = []
35
+
36
+ def fake_import(name, *args, **kwargs):
37
+ if name.split(".")[0] in ("torch", "sentence_transformers"):
38
+ attempts.append(name)
39
+ raise ModuleNotFoundError("blocked by test", name=name)
40
+ return real_import(name, *args, **kwargs)
41
+
42
+ for mod in ("torch", "sentence_transformers"):
43
+ monkeypatch.delitem(sys.modules, mod, raising=False)
44
+ monkeypatch.setattr(builtins, "__import__", fake_import)
45
+ yield attempts
46
+ assert attempts == [], "light backend tried to import %s" % attempts
47
+
48
+
49
+ def test_backend_env_forces_either_stack(monkeypatch):
50
+ monkeypatch.setattr(onnx_backend, "available", lambda: True)
51
+ assert brain_ask.backend({"SGM_BACKEND": "torch"}) == "torch"
52
+ monkeypatch.setattr(onnx_backend, "available", lambda: False)
53
+ assert brain_ask.backend({"SGM_BACKEND": "onnx"}) == "onnx"
54
+
55
+
56
+ @pytest.mark.parametrize("installed,expected", [(True, "onnx"), (False, "torch")])
57
+ def test_backend_auto_prefers_onnx_when_installed(monkeypatch, installed, expected):
58
+ monkeypatch.setattr(onnx_backend, "available", lambda: installed)
59
+ assert brain_ask.backend({}) == expected
60
+ assert brain_ask.backend({"SGM_BACKEND": "auto"}) == expected
61
+
62
+
63
+ def test_pick_device_does_not_import_torch(monkeypatch, torch_forbidden):
64
+ monkeypatch.setenv("SGM_BACKEND", "onnx")
65
+ assert brain_ask.pick_device() == "cpu"
66
+
67
+
68
+ def test_loaders_use_onnx_without_sentence_transformers(monkeypatch, torch_forbidden):
69
+ monkeypatch.setenv("SGM_BACKEND", "onnx")
70
+ monkeypatch.setattr(onnx_backend, "Encoder", lambda: "enc")
71
+ monkeypatch.setattr(onnx_backend, "CrossEncoder", lambda: "ce")
72
+ assert brain_ask.load_encoder() == "enc"
73
+ assert brain_ask.load_reranker() == "ce"
74
+
75
+
76
+ class _FakeST:
77
+ """Stands in for sentence_transformers on a machine with cached torch models."""
78
+ def SentenceTransformer(self, *a, **k):
79
+ return "torch-enc"
80
+
81
+ def CrossEncoder(self, *a, **k):
82
+ return "torch-ce"
83
+
84
+
85
+ def _offline(*a, **k):
86
+ raise OSError("offline: onnx/model.onnx is not in the cache")
87
+
88
+
89
+ @pytest.mark.parametrize("loader,want", [("load_encoder", "torch-enc"),
90
+ ("load_reranker", "torch-ce")])
91
+ def test_auto_onnx_failure_falls_back_to_torch(monkeypatch, loader, want):
92
+ """Codex review 2026-11-03: onnxruntime from another package + offline + torch models
93
+ cached must keep recall working instead of failing on a missing ONNX file."""
94
+ monkeypatch.delenv("SGM_BACKEND", raising=False)
95
+ monkeypatch.setattr(onnx_backend, "available", lambda: True)
96
+ monkeypatch.setattr(onnx_backend, "Encoder", _offline)
97
+ monkeypatch.setattr(onnx_backend, "CrossEncoder", _offline)
98
+ monkeypatch.setitem(sys.modules, "sentence_transformers", _FakeST())
99
+ assert getattr(brain_ask, loader)("cpu") == want
100
+
101
+
102
+ def test_forced_onnx_failure_raises(monkeypatch):
103
+ monkeypatch.setenv("SGM_BACKEND", "onnx")
104
+ monkeypatch.setattr(onnx_backend, "Encoder", _offline)
105
+ monkeypatch.setitem(sys.modules, "sentence_transformers", _FakeST())
106
+ with pytest.raises(OSError):
107
+ brain_ask.load_encoder("cpu")
108
+
109
+
110
+ def test_model_cache_is_not_temp(monkeypatch, tmp_path):
111
+ """SGM_MODEL_CACHE is passed through; unset means huggingface_hub's persistent cache."""
112
+ seen = []
113
+ hub = pytest.importorskip("huggingface_hub")
114
+ monkeypatch.setattr(hub, "hf_hub_download",
115
+ lambda repo, f, cache_dir=None: seen.append(cache_dir) or f)
116
+ monkeypatch.setenv("SGM_MODEL_CACHE", str(tmp_path))
117
+ onnx_backend._fetch("r", ["a"])
118
+ monkeypatch.delenv("SGM_MODEL_CACHE")
119
+ onnx_backend._fetch("r", ["a"])
120
+ assert seen == [str(tmp_path), None]
121
+
122
+
123
+ REF_PAIRS = [
124
+ ("query: как я думаю о памяти агентов", "Память агента: граф заметок и SQLite."),
125
+ ("query: как я думаю о памяти агентов", "Рецепт борща с фасолью."),
126
+ ("slow import", "torch takes 44 s to import on a laptop without GPU " * 80),
127
+ ]
128
+ REF_LOGITS = [-0.85672015, -9.523896, 0.01399507]
129
+
130
+
131
+ @pytest.mark.skipif(not onnx_backend.available(), reason="lite extra not installed")
132
+ @pytest.mark.skipif("SGM_LIVE_MODELS" not in __import__("os").environ,
133
+ reason="downloads ~1.6 GB; set SGM_LIVE_MODELS=1")
134
+ def test_live_numbers_match_sentence_transformers():
135
+ import numpy as np
136
+ scores = onnx_backend.CrossEncoder().predict(REF_PAIRS)
137
+ assert np.allclose(scores, REF_LOGITS, atol=1e-3), scores
138
+ texts = ["query: как я думаю о памяти агентов",
139
+ "passage: The reranker forgives coarse chunk boundaries. " * 60]
140
+ emb = onnx_backend.Encoder().encode(texts)
141
+ assert emb.shape == (2, 768)
142
+ assert np.allclose(np.linalg.norm(emb, axis=1), 1.0, atol=1e-5)
143
+ try:
144
+ from sentence_transformers import SentenceTransformer
145
+ except ImportError:
146
+ return
147
+ ref = SentenceTransformer(brain_ask.E5_MODEL, device="cpu").encode(
148
+ texts, normalize_embeddings=True, convert_to_numpy=True)
149
+ assert float((emb * ref).sum(1).min()) > 0.9999
@@ -38,6 +38,8 @@ def no_sentence_transformers(monkeypatch):
38
38
 
39
39
  monkeypatch.delitem(sys.modules, "sentence_transformers", raising=False)
40
40
  monkeypatch.setattr(builtins, "__import__", fake_import)
41
+ # The torch path is the one under test; with the lite extra installed, auto would pick ONNX.
42
+ monkeypatch.setenv("SGM_BACKEND", "torch")
41
43
 
42
44
 
43
45
  def test_indexer_exits_with_install_instructions(tmp_path, monkeypatch, capsys,
@@ -0,0 +1,52 @@
1
+ # -*- coding: utf-8 -*-
2
+ """sgm-turnstate-show: corrupt ledgers get a one-line error, not a traceback (#74)."""
3
+ import os
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ import pytest
9
+
10
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
11
+ from sqlite_graph_memory import turnstate_show # noqa: E402
12
+
13
+
14
+ def test_corrupt_ledger_exits_one_without_traceback(tmp_path, monkeypatch, capsys):
15
+ bad = tmp_path / "c.db"
16
+ bad.write_text("junk", encoding="utf-8")
17
+ monkeypatch.setenv("TURNSTATE_DB", str(bad))
18
+ turnstate_show.DB = str(bad)
19
+ assert turnstate_show.main(["--stats"]) == 1
20
+ err = capsys.readouterr().err
21
+ assert "not a database" in err
22
+ assert str(bad) in err
23
+ assert "Traceback" not in err
24
+ assert bad.read_text(encoding="utf-8") == "junk"
25
+
26
+
27
+ def test_corrupt_ledger_module_cli_exits_nonzero(tmp_path):
28
+ bad = tmp_path / "c.db"
29
+ bad.write_bytes(b"junk")
30
+ env = os.environ.copy()
31
+ env["TURNSTATE_DB"] = str(bad)
32
+ env["PYTHONPATH"] = str(Path(__file__).resolve().parents[1] / "src")
33
+ proc = subprocess.run(
34
+ [sys.executable, "-m", "sqlite_graph_memory.turnstate_show", "--stats"],
35
+ env=env,
36
+ capture_output=True,
37
+ text=True,
38
+ )
39
+ assert proc.returncode == 1
40
+ assert "not a database" in proc.stderr
41
+ assert "Traceback" not in proc.stderr
42
+ assert "Traceback" not in proc.stdout
43
+
44
+
45
+ def test_missing_ledger_stays_friendly(tmp_path, monkeypatch, capsys):
46
+ missing = tmp_path / "missing.db"
47
+ monkeypatch.setenv("TURNSTATE_DB", str(missing))
48
+ turnstate_show.DB = str(missing)
49
+ assert turnstate_show.main(["--stats"]) == 0
50
+ out = capsys.readouterr().out
51
+ assert "no ledger yet" in out
52
+ assert str(missing) in out
@@ -78,6 +78,14 @@ def test_dangling_and_self_links_are_not_edges(tmp_path):
78
78
  assert _metric(r, "avg_degree")["detail"].startswith("2 resolved links")
79
79
 
80
80
 
81
+ def test_link_in_inline_code_is_not_an_edge(tmp_path):
82
+ (tmp_path / "a.md").write_text("Write `[[x]]` to link.\n", encoding="utf-8")
83
+ (tmp_path / "x.md").write_text("# x\n", encoding="utf-8")
84
+ pages, edges = vault_stats.build_graph(tmp_path)
85
+ assert pages.keys() == {"a", "x"}
86
+ assert edges == set()
87
+
88
+
81
89
  # ------------------------------------------------------------------ average degree
82
90
 
83
91
  @pytest.mark.parametrize("extra,expected", [
@@ -220,7 +228,21 @@ def test_impossible_date_is_undated_not_a_crash(tmp_path):
220
228
 
221
229
  def test_empty_vault_exits_with_fail_code(tmp_path, capsys):
222
230
  assert vault_stats.main([str(tmp_path)]) == 2
223
- assert "no notes" in capsys.readouterr().err
231
+ captured = capsys.readouterr()
232
+ assert "no notes" in captured.err
233
+ assert captured.out == ""
234
+
235
+
236
+ def test_empty_vault_json_output(tmp_path, capsys):
237
+ code = vault_stats.main([str(tmp_path), "--json"])
238
+ assert code == 2
239
+ captured = capsys.readouterr()
240
+ report = json.loads(captured.out)
241
+ assert report["verdict"] == "fail"
242
+ assert report["exit_code"] == 2
243
+ assert report["pages"] == 0
244
+ assert report["notes_dir"] == str(tmp_path)
245
+ assert "no notes" in report["error"]
224
246
 
225
247
 
226
248
  def test_single_quoted_frontmatter(tmp_path):
@@ -0,0 +1,75 @@
1
+ """Every place that names the version agrees, on every PR.
2
+
3
+ v0.3.4 was tagged on 2026-10-31 and never reached PyPI: the release commit changed only
4
+ CHANGELOG.md, so pyproject, __init__ and server.json still said 0.3.3 and the publish job
5
+ stopped on its own version check, after the tag. That check runs too late to prevent
6
+ anything, so the same comparison runs here, where a red X stops the merge.
7
+
8
+ A CHANGELOG section may be written ahead of the bump if its header says "unreleased".
9
+ """
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+
14
+ ROOT = Path(__file__).resolve().parents[1]
15
+ # The version must end the token: "## v0.4.0-rc1" or "## v0.3.3.post1" is not v0.4.0 / v0.3.3.
16
+ SECTION = re.compile(r"^## v(\d+\.\d+\.\d+)(?=[ \t]|$)(.*)$", re.M)
17
+
18
+
19
+ def top_released(changelog):
20
+ """Version of the first section not marked unreleased, or None."""
21
+ for m in SECTION.finditer(changelog):
22
+ if "unreleased" not in m.group(2).lower():
23
+ return m.group(1)
24
+ return None
25
+
26
+
27
+ def disagreements(pyproject, init_py, server, changelog):
28
+ """Places that differ from the version in pyproject.toml."""
29
+ want = re.search(r'^version\s*=\s*"([^"]+)"', pyproject, re.M).group(1)
30
+ pkg = server["packages"][0]
31
+ seen = {
32
+ "__init__.__version__": re.search(r'^__version__\s*=\s*"([^"]+)"', init_py, re.M).group(1),
33
+ "server.json version": server["version"],
34
+ "server.json packages[0].version": pkg["version"],
35
+ "server.json runtimeArguments pin": pkg["runtimeArguments"][0]["value"].rsplit("==", 1)[-1],
36
+ "CHANGELOG top released section": top_released(changelog),
37
+ }
38
+ return [f"{k} = {v}, pyproject = {want}" for k, v in seen.items() if v != want]
39
+
40
+
41
+ def test_all_versions_agree():
42
+ bad = disagreements(
43
+ (ROOT / "pyproject.toml").read_text(encoding="utf-8"),
44
+ (ROOT / "src/sqlite_graph_memory/__init__.py").read_text(encoding="utf-8"),
45
+ json.loads((ROOT / "server.json").read_text(encoding="utf-8")),
46
+ (ROOT / "CHANGELOG.md").read_text(encoding="utf-8"),
47
+ )
48
+ assert not bad, "version mismatch, a release from here would stop before PyPI:\n " + "\n ".join(bad)
49
+
50
+
51
+ PY = 'version = "0.3.3"\n'
52
+ INIT = '__version__ = "0.3.3"\n'
53
+ SRV = {"version": "0.3.3", "packages": [{"version": "0.3.3",
54
+ "runtimeArguments": [{"value": "sqlite-graph-memory[embeddings]==0.3.3"}]}]}
55
+
56
+
57
+ def test_the_v034_release_commit_is_caught():
58
+ log = "# Changelog\n\n## v0.3.4 - 2026-10-31\n\nx\n\n## v0.3.3 - 2026-10-26\n\ny\n"
59
+ assert disagreements(PY, INIT, SRV, log) == ["CHANGELOG top released section = 0.3.4, pyproject = 0.3.3"]
60
+
61
+
62
+ def test_section_marked_unreleased_may_lead():
63
+ log = "## v0.3.4 - unreleased\n\nx\n\n## v0.3.3 - 2026-10-26\n\ny\n"
64
+ assert disagreements(PY, INIT, SRV, log) == []
65
+
66
+
67
+ def test_prerelease_header_is_not_the_stable_version():
68
+ log = "## v0.3.3.post1 - 2026-10-27\n\nx\n\n## v0.3.4-rc1\n\ny\n\n## v0.3.3 - 2026-10-26\n\nz\n"
69
+ assert top_released(log) == "0.3.3"
70
+
71
+
72
+ def test_forgotten_pin_in_server_json_is_caught():
73
+ srv = json.loads(json.dumps(SRV))
74
+ srv["packages"][0]["runtimeArguments"][0]["value"] = "sqlite-graph-memory[embeddings]==0.3.2"
75
+ assert len(disagreements(PY, INIT, srv, "## v0.3.3\n")) == 1
@@ -0,0 +1,36 @@
1
+ # -*- coding: utf-8 -*-
2
+ """`--version` on sgm-stats and sgm-ask prints the package version and exits 0 (issue #75).
3
+
4
+ Runs offline: no model, no index, no network. Both commands are run as modules so the
5
+ test does not need the package installed.
6
+ """
7
+ import os
8
+ import subprocess
9
+ import sys
10
+ from pathlib import Path
11
+
12
+ import pytest
13
+
14
+ SRC = Path(__file__).resolve().parents[1] / "src"
15
+ sys.path.insert(0, str(SRC))
16
+ from sqlite_graph_memory import __version__ # noqa: E402
17
+
18
+
19
+ @pytest.mark.parametrize(
20
+ ("module", "prog"),
21
+ [
22
+ ("sqlite_graph_memory.vault_stats", "sgm-stats"),
23
+ ("sqlite_graph_memory.brain_ask", "sgm-ask"),
24
+ ],
25
+ )
26
+ def test_version_flag_prints_the_version_and_exits_zero(module, prog, tmp_path):
27
+ env = os.environ.copy()
28
+ env["BRAIN_INDEX_DIR"] = str(tmp_path / "no-index")
29
+ env["PYTHONPATH"] = os.pathsep.join(filter(None, [str(SRC), env.get("PYTHONPATH")]))
30
+ res = subprocess.run(
31
+ [sys.executable, "-m", module, "--version"],
32
+ capture_output=True, text=True, cwd=str(tmp_path), env=env, timeout=60,
33
+ )
34
+ assert res.returncode == 0, res.stderr
35
+ assert res.stdout.strip().endswith(__version__), res.stdout
36
+ assert prog in res.stdout