sqlite-graph-memory 0.3.5__py3-none-any.whl → 0.3.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlite_graph_memory/__init__.py +1 -1
- sqlite_graph_memory/brain_ask.py +66 -3
- sqlite_graph_memory/doctor.py +12 -1
- sqlite_graph_memory/index_notes.py +23 -14
- sqlite_graph_memory/onnx_backend.py +127 -0
- sqlite_graph_memory/turnstate_show.py +14 -6
- sqlite_graph_memory/vault_stats.py +10 -2
- {sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.6.dist-info}/METADATA +15 -7
- sqlite_graph_memory-0.3.6.dist-info/RECORD +16 -0
- sqlite_graph_memory-0.3.5.dist-info/RECORD +0 -15
- {sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.6.dist-info}/WHEEL +0 -0
- {sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.6.dist-info}/entry_points.txt +0 -0
- {sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.6.dist-info}/licenses/LICENSE +0 -0
sqlite_graph_memory/__init__.py
CHANGED
sqlite_graph_memory/brain_ask.py
CHANGED
|
@@ -49,13 +49,37 @@ ENTITY_TOOLS = {'obsidian', 'syncthing', 'sqlite', 'telegram', 'whatsapp', 'n8n'
|
|
|
49
49
|
|
|
50
50
|
|
|
51
51
|
_EMBEDDINGS_HINT = (
|
|
52
|
-
"This step needs
|
|
53
|
-
"
|
|
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
|
|
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'}
|
sqlite_graph_memory/doctor.py
CHANGED
|
@@ -40,6 +40,16 @@ def _intel_mac(system=None, machine=None):
|
|
|
40
40
|
|
|
41
41
|
def check_embeddings(system=None, machine=None):
|
|
42
42
|
"""The heavy half. Without it the graph and the SQLite parts work, indexing and recall do not."""
|
|
43
|
+
if brain_ask.backend() == 'onnx':
|
|
44
|
+
try:
|
|
45
|
+
import onnxruntime
|
|
46
|
+
import tokenizers # noqa: F401
|
|
47
|
+
import huggingface_hub # noqa: F401
|
|
48
|
+
except Exception as exc:
|
|
49
|
+
why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
|
|
50
|
+
return FAIL, 'The light backend is incomplete (%s).' % why, \
|
|
51
|
+
'Reinstall in a fresh virtualenv: pip install --force-reinstall "sqlite-graph-memory[lite]"'
|
|
52
|
+
return OK, 'Light backend: onnxruntime %s, no torch needed.' % onnxruntime.__version__, ''
|
|
43
53
|
try:
|
|
44
54
|
import numpy
|
|
45
55
|
np_major = int(numpy.__version__.split('.')[0])
|
|
@@ -50,7 +60,8 @@ def check_embeddings(system=None, machine=None):
|
|
|
50
60
|
import sentence_transformers
|
|
51
61
|
except ModuleNotFoundError as exc:
|
|
52
62
|
return (WARN, 'The embeddings extra is not installed (%s missing).' % exc.name,
|
|
53
|
-
'Only needed to index and recall. Install it with: pip install "sqlite-graph-memory[
|
|
63
|
+
'Only needed to index and recall. Install it with: pip install "sqlite-graph-memory[lite]"'
|
|
64
|
+
' (or [embeddings] for torch and a GPU)')
|
|
54
65
|
except Exception as exc: # torch dies at import on a numpy it was not built for
|
|
55
66
|
why = '%s: %s' % (type(exc).__name__, str(exc).splitlines()[0] if str(exc) else '')
|
|
56
67
|
if _intel_mac(system, machine) and np_major >= 2:
|
|
@@ -29,12 +29,12 @@ FM_RX = re.compile(r'^---\r?\n(.*?)\r?\n---\r?\n', re.S)
|
|
|
29
29
|
|
|
30
30
|
|
|
31
31
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
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, ")")
|
|
42
|
-
|
|
41
|
+
print("(no ledger yet:", DB, ")")
|
|
42
|
+
return 0
|
|
43
|
+
try:
|
|
44
|
+
c = sqlite3.connect(DB)
|
|
45
|
+
# Opening succeeds on junk bytes; the first query is what raises DatabaseError.
|
|
46
|
+
c.execute("select 1 from sqlite_master limit 1").fetchone()
|
|
47
|
+
except sqlite3.Error:
|
|
48
|
+
print("sgm-turnstate-show: not a database: %s" % DB, file=sys.stderr)
|
|
49
|
+
return 1
|
|
43
50
|
|
|
44
51
|
if a.stats:
|
|
45
52
|
tot = c.execute("select count(*) from turns").fetchone()[0]
|
|
@@ -51,7 +58,7 @@ def main():
|
|
|
51
58
|
"select session_id,count(*),max(ts) from turns group by session_id "
|
|
52
59
|
"order by max(ts) desc limit 12"):
|
|
53
60
|
print(" %-38s %4d turns last %s" % (sid[:38], n, last))
|
|
54
|
-
return
|
|
61
|
+
return 0
|
|
55
62
|
|
|
56
63
|
q = ("select ts,project,ask,summary,files,tools,commands,decisions,session_id "
|
|
57
64
|
"from turns ")
|
|
@@ -79,7 +86,8 @@ def main():
|
|
|
79
86
|
print(" - %s" % x)
|
|
80
87
|
if summary:
|
|
81
88
|
print("💬 summary: %s" % summary.replace("\n", " ")[:200])
|
|
89
|
+
return 0
|
|
82
90
|
|
|
83
91
|
|
|
84
92
|
if __name__ == "__main__":
|
|
85
|
-
main()
|
|
93
|
+
sys.exit(main() or 0)
|
|
@@ -35,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
|
-
|
|
211
|
-
|
|
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
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: sqlite-graph-memory
|
|
3
|
-
Version: 0.3.
|
|
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
|
|
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]
|
|
131
|
-
|
|
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
|
|
280
|
-
#
|
|
281
|
-
#
|
|
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
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
sqlite_graph_memory/__init__.py,sha256=tp1bvR_lAMB3gg3_28p4sOADUAqsFBg15rCsyvoZ2WI,1151
|
|
2
|
+
sqlite_graph_memory/brain_ask.py,sha256=1CsBMtYeVSXdEXimS2xasAUvcuhXDxdLYE7w8uu0of0,21710
|
|
3
|
+
sqlite_graph_memory/doctor.py,sha256=fOHoCV7XdDfYNIb3-tpa6sJtwzKBSH-EhsTpA0uQ9Qo,6005
|
|
4
|
+
sqlite_graph_memory/index_notes.py,sha256=6SdRXKVyOp9QPmBnyb2Sj98pIcqmnhZgqF9MWA4EJcY,5794
|
|
5
|
+
sqlite_graph_memory/mcp_server.py,sha256=GItrJrtU34lGzamSD1ryEfL-Aq46W_J-4eDBZ3Pr_Wo,10218
|
|
6
|
+
sqlite_graph_memory/onnx_backend.py,sha256=1P4sy5LrI_j4dgB-taFoakrDbn2JQIQnnmOuH7bA0ZM,5377
|
|
7
|
+
sqlite_graph_memory/ppr.py,sha256=L7VSAiliXr8j3PH2hQqKbdgm08BPm6pZkLcckoMxAro,10001
|
|
8
|
+
sqlite_graph_memory/schema.sql,sha256=8aySXKw3Azaxyzqbd76mKTfOaDP7FlpkLXtgwA8ZVK4,2543
|
|
9
|
+
sqlite_graph_memory/turnstate_hook.py,sha256=fypGmUcHQkzlRN74tvIG07lr9uAXpp2GjetqthkuMc8,8641
|
|
10
|
+
sqlite_graph_memory/turnstate_show.py,sha256=Bij4POJNSbJunHwGgm4i2NzkJQms8QBpR0mM9VVeKy4,3251
|
|
11
|
+
sqlite_graph_memory/vault_stats.py,sha256=qYU-uzH_W4ME4Qf71UQrExb91cgyTEnjBJDqzwyh0e0,8946
|
|
12
|
+
sqlite_graph_memory-0.3.6.dist-info/METADATA,sha256=1Ev-QC7Ld4y0cd6UTqg3fdBGGGT3OpQChFDwbL3tPOM,37431
|
|
13
|
+
sqlite_graph_memory-0.3.6.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
14
|
+
sqlite_graph_memory-0.3.6.dist-info/entry_points.txt,sha256=lpoCm-jNjhBEtcQ16iIUd0ivr92Gr4c_fSRls2Zvbb0,432
|
|
15
|
+
sqlite_graph_memory-0.3.6.dist-info/licenses/LICENSE,sha256=p88nZdrfMUiES3_MpUEwhGmqz2hQFpyMh0k0cqdpfU8,1082
|
|
16
|
+
sqlite_graph_memory-0.3.6.dist-info/RECORD,,
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
sqlite_graph_memory/__init__.py,sha256=tqMLjmtW62GpxsI1IGGe5TYwaXqkVx0d1-bmFxOy2iE,1151
|
|
2
|
-
sqlite_graph_memory/brain_ask.py,sha256=rcXquak8fIYzKLPJL0GhrQGvbA0cVIcj805lNUjvcTY,19392
|
|
3
|
-
sqlite_graph_memory/doctor.py,sha256=zCdiOo9FIh_DKrDCUL3trI3q44xrtZTNVcFjL_XcD0o,5366
|
|
4
|
-
sqlite_graph_memory/index_notes.py,sha256=blm9lLlB5MSLB39tNYVtjVGULLQXTQGOth_LV4utyic,5378
|
|
5
|
-
sqlite_graph_memory/mcp_server.py,sha256=GItrJrtU34lGzamSD1ryEfL-Aq46W_J-4eDBZ3Pr_Wo,10218
|
|
6
|
-
sqlite_graph_memory/ppr.py,sha256=L7VSAiliXr8j3PH2hQqKbdgm08BPm6pZkLcckoMxAro,10001
|
|
7
|
-
sqlite_graph_memory/schema.sql,sha256=8aySXKw3Azaxyzqbd76mKTfOaDP7FlpkLXtgwA8ZVK4,2543
|
|
8
|
-
sqlite_graph_memory/turnstate_hook.py,sha256=fypGmUcHQkzlRN74tvIG07lr9uAXpp2GjetqthkuMc8,8641
|
|
9
|
-
sqlite_graph_memory/turnstate_show.py,sha256=IED7fmJQM5VgBNwxmEoNSZtujRmWja-qVPg5ckbWVnY,2909
|
|
10
|
-
sqlite_graph_memory/vault_stats.py,sha256=QYNGck556RDyLIVFH1C864su5tWehep1DHE21sSTi9g,8596
|
|
11
|
-
sqlite_graph_memory-0.3.5.dist-info/METADATA,sha256=ATapZ36CIk5AOwyHevNLQX3YqB7MTy7WX2j6JqNJV_I,36912
|
|
12
|
-
sqlite_graph_memory-0.3.5.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
13
|
-
sqlite_graph_memory-0.3.5.dist-info/entry_points.txt,sha256=lpoCm-jNjhBEtcQ16iIUd0ivr92Gr4c_fSRls2Zvbb0,432
|
|
14
|
-
sqlite_graph_memory-0.3.5.dist-info/licenses/LICENSE,sha256=p88nZdrfMUiES3_MpUEwhGmqz2hQFpyMh0k0cqdpfU8,1082
|
|
15
|
-
sqlite_graph_memory-0.3.5.dist-info/RECORD,,
|
|
File without changes
|
{sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.6.dist-info}/entry_points.txt
RENAMED
|
File without changes
|
{sqlite_graph_memory-0.3.5.dist-info → sqlite_graph_memory-0.3.6.dist-info}/licenses/LICENSE
RENAMED
|
File without changes
|