sqlite-graph-memory 0.3.7__py3-none-any.whl → 0.3.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -21,6 +21,6 @@ the indexer and the reranker will tell you what is missing instead of failing
21
21
  on an ``ImportError`` at startup.
22
22
  """
23
23
 
24
- __version__ = "0.3.7"
24
+ __version__ = "0.3.8"
25
25
 
26
26
  __all__ = ["__version__"]
@@ -9,11 +9,13 @@ USAGE:
9
9
  python brain_ask.py --graph "question" # vector + graph expansion (Associative)
10
10
  python brain_ask.py --ab "question" # run BOTH, diff, log to SQLite (ab_recall)
11
11
  python brain_ask.py --ask "question" # emit a context bundle for an LLM agent
12
+ python brain_ask.py --pool 15 --graph "q" # override dense candidate pool size (default: 60)
12
13
  python brain_ask.py --ppr --graph "question" # + PageRank lane in the ORDERING (see ppr.py)
13
14
  python brain_ask.py --rerank "question" # opt in to the cross-encoder rerank (off by default)
14
15
 
15
16
  Config (env, all optional):
16
17
  BRAIN_INDEX_DIR dir holding the embedding index (default: ./index)
18
+ BRAIN_TOPK_RETRIEVE dense candidate pool size before rerank (default: 60; CLI --pool overrides)
17
19
  TURNSTATE_DB SQLite db for A/B telemetry (default: ./turnstate.db)
18
20
  BRAIN_ANSWER_OUT file to mirror the answer into (default: ./_brain_answer.txt)
19
21
  BRAIN_AB_JSON if set, --ab also writes a structured JSON diff to this path
@@ -150,6 +152,31 @@ def _links_in(path):
150
152
  return [m.strip() for m in WIKILINK_RX.findall(t)]
151
153
 
152
154
 
155
+ FRONTMATTER_RX = re.compile(r'^---\r?\n(.*?)\r?\n---', re.DOTALL)
156
+ SUPERSEDED_BY_RX = re.compile(r'^superseded_by\s*:\s*"?(.+?)"?\s*$', re.MULTILINE)
157
+
158
+
159
+ def _superseded_links_in(path):
160
+ """The `superseded_by` TARGET(s) from a note's YAML frontmatter (issue #93).
161
+
162
+ Followed regardless of the entity gate: a query that trips looks_like_entity()
163
+ still needs to reach the replacement of an outdated note, even though general
164
+ wikilink expansion is gated off for that query."""
165
+ try: t = Path(path).read_text(encoding='utf-8', errors='ignore')
166
+ except Exception: return []
167
+ fm = FRONTMATTER_RX.match(t)
168
+ if not fm:
169
+ return []
170
+ m = SUPERSEDED_BY_RX.search(fm.group(1))
171
+ if not m:
172
+ return []
173
+ val = m.group(1).strip().strip('"').strip("'").strip()
174
+ if not val:
175
+ return []
176
+ links = [l.strip() for l in WIKILINK_RX.findall(val) if l.strip()]
177
+ return links if links else [val]
178
+
179
+
153
180
 
154
181
  # --------------------------------------------------------------------------- pipeline
155
182
  # The retrieval pipeline lives in these functions so that anything measuring it
@@ -306,10 +333,15 @@ def _resolve_target_chunks(tgt, by_base, meta, root=None):
306
333
  return exact if exact else suffix_matches
307
334
 
308
335
 
309
- def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX, root=None):
336
+ def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX, root=None,
337
+ only_superseded=False):
310
338
  """Follow 1-hop OUTGOING wikilinks from the top vector hits and return the neighbour
311
339
  chunks to ADD to the candidate set; the reranker decides whether they are relevant.
312
340
 
341
+ only_superseded=True follows only a note's superseded_by frontmatter target instead
342
+ of every wikilink (issue #93): the entity gate uses this to still reach a replacement
343
+ note while leaving general wikilink expansion gated off.
344
+
313
345
  Bounded by ghops/gmax. CRASH-SAFETY: any failure returns [] and the caller degrades to
314
346
  vector-only -- worst case you get the old result, never an empty or broken recall."""
315
347
  added = []
@@ -322,7 +354,8 @@ def expand_1hop(sims, meta, base_order, by_base=None, ghops=GHOPS, gmax=GMAX, ro
322
354
  root = vault_root(meta)
323
355
  in_order = set(base_order)
324
356
  for i in base_order[:ghops]:
325
- for tgt in _links_in(meta[i]['path']):
357
+ targets = _superseded_links_in(meta[i]['path']) if only_superseded else _links_in(meta[i]['path'])
358
+ for tgt in targets:
326
359
  idxs = _resolve_target_chunks(tgt, by_base, meta, root=root)
327
360
  if not idxs: continue
328
361
  best = max(idxs, key=lambda j: sims[j]) # best chunk of neighbour for THIS query
@@ -449,12 +482,56 @@ def maybe_star_prompt(stream=None, env=None, interactive=None):
449
482
  return False
450
483
 
451
484
 
485
+ def _parse_pool(args, env=None):
486
+ """Extract optional `--pool N` / `--topk-retrieve N` (or BRAIN_TOPK_RETRIEVE) -> (int|None, remaining_args)."""
487
+ env = os.environ if env is None else env
488
+ pool = None
489
+ env_val = (env.get('BRAIN_TOPK_RETRIEVE') or '').strip()
490
+ if env_val:
491
+ try:
492
+ pool = int(env_val)
493
+ except ValueError as exc:
494
+ sys.stderr.write('invalid BRAIN_TOPK_RETRIEVE=%r (expected positive integer)\n' % env_val)
495
+ raise SystemExit(2) from exc
496
+ if pool < 1:
497
+ sys.stderr.write('invalid BRAIN_TOPK_RETRIEVE=%r (must be >= 1)\n' % env_val)
498
+ raise SystemExit(2)
499
+ rest = []
500
+ i = 0
501
+ while i < len(args):
502
+ a = args[i]
503
+ if a in ('--pool', '--topk-retrieve'):
504
+ if i + 1 >= len(args):
505
+ sys.stderr.write('%s requires a positive integer argument\n' % a)
506
+ raise SystemExit(2)
507
+ raw = args[i + 1]
508
+ i += 2
509
+ elif a.startswith('--pool=') or a.startswith('--topk-retrieve='):
510
+ flag, _, raw = a.partition('=')
511
+ a = flag
512
+ i += 1
513
+ else:
514
+ rest.append(a)
515
+ i += 1
516
+ continue
517
+ try:
518
+ pool = int(raw)
519
+ except ValueError as exc:
520
+ sys.stderr.write('invalid %s value %r (expected positive integer)\n' % (a, raw))
521
+ raise SystemExit(2) from exc
522
+ if pool < 1:
523
+ sys.stderr.write('invalid %s value %r (must be >= 1)\n' % (a, raw))
524
+ raise SystemExit(2)
525
+ return pool, rest
526
+
527
+
452
528
  def main():
453
529
  args = sys.argv[1:]
454
530
  if '--version' in args:
455
531
  from sqlite_graph_memory import __version__
456
532
  print('sgm-ask %s' % __version__)
457
533
  return
534
+ pool, args = _parse_pool(args)
458
535
  ask = '--ask' in args
459
536
  graph = '--graph' in args; ab = '--ab' in args
460
537
  flags = {'--ask', '--graph', '--ab', '--ppr', '--rerank'}
@@ -471,7 +548,7 @@ def main():
471
548
  sims = query_sims(enc, emb, query)
472
549
 
473
550
  # dense retrieve -> dedup by path (best chunk per file) -> top-K unique files
474
- order = retrieve_candidates(sims, meta)
551
+ order = retrieve_candidates(sims, meta) if pool is None else retrieve_candidates(sims, meta, topk=pool)
475
552
 
476
553
  # Graph expansion: follow 1-hop OUTGOING wikilinks from the top vector hits, pull in
477
554
  # those neighbour notes (resolved to already-indexed chunks), then let the reranker
@@ -560,10 +637,16 @@ def main():
560
637
  return
561
638
 
562
639
  # GATE: wiki-graph helps THEME queries, hurts ENTITY/name queries -> skip graph for entities.
640
+ # Exception (issue #93): a superseded_by target still resolves even when gated, so an
641
+ # outdated note's replacement isn't dropped just because the query looks entity-like.
563
642
  gated = graph and looks_like_entity(query)
564
643
  if gated:
565
- sys.stderr.write("wiki-graph gated OFF (entity-like query) -> Direct only\n")
566
- order = graph_order if (graph and not gated) else base_order
644
+ sys.stderr.write("wiki-graph gated OFF (entity-like query) -> Direct only, except superseded_by\n")
645
+ sup_added = expand_1hop(sims, meta, base_order, only_superseded=True)
646
+ order = base_order + sup_added
647
+ graph_set = set(sup_added)
648
+ else:
649
+ order = graph_order if graph else base_order
567
650
  reranked = rerank(order)
568
651
  scope = 'all' + (' /graph+%d' % len(graph_set) if graph else '') + (' /ppr' if ppr_stems else '')
569
652
  lines = [f'QUERY: {query}', f'(scope={scope}; e5 {len(order)} files -> {"rerank" if ce is not None else "dense"}; {len(meta)} chunks)', '']
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlite-graph-memory
3
- Version: 0.3.7
3
+ Version: 0.3.8
4
4
  Summary: Associative memory for LLM agents: Graph RAG over a folder of markdown notes, in one SQLite file, with no server to run.
5
5
  Project-URL: Homepage, https://github.com/tonydzi/sqlite-graph-memory
6
6
  Project-URL: Repository, https://github.com/tonydzi/sqlite-graph-memory
@@ -62,6 +62,8 @@ misses by following the links between your notes. It is an MCP server and a CLI
62
62
  folder of markdown, Obsidian vaults included: `pip install`, point it at the folder, and
63
63
  Claude Code, Cursor, Codex or any other MCP client can recall from it.
64
64
 
65
+ It fits [Andrej Karpathy's LLM Wiki pattern](https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f) (April 2026), where an agent maintains an interlinked markdown wiki and a search tool over the pages is the first helper he suggests adding: sgm is that search layer, read-only, and it follows your `[[wikilinks]]` as a graph. Independent project, not affiliated with or endorsed by him.
66
+
65
67
  ![sgm-index builds the index of the 202-note bench vault, then sgm-ask --ab shows tool-lanternfish entering the top 5 only through a graph hop; the one-minute CPU indexing wait is cut](docs/demo.gif)
66
68
 
67
69
  **Your agent forgets everything between sessions, and plain vector search gives it back
@@ -1,5 +1,5 @@
1
- sqlite_graph_memory/__init__.py,sha256=k3Jab-cnKnZpQ2RoYkXY57NDDrtKZJZ9AXegsm09LhA,1151
2
- sqlite_graph_memory/brain_ask.py,sha256=ri60NrgRSVcAj89sLVmpGZBmfgJmAWq-p4VwOvyzHV8,26008
1
+ sqlite_graph_memory/__init__.py,sha256=QCN9lXNZb7O0BUmBobR0XGrQUJyConcxQGEXAVO8C9E,1151
2
+ sqlite_graph_memory/brain_ask.py,sha256=TeQTZI74muSve84ESv4lBsSUyCLhr58unHpqIFXRoJ4,29535
3
3
  sqlite_graph_memory/doctor.py,sha256=fOHoCV7XdDfYNIb3-tpa6sJtwzKBSH-EhsTpA0uQ9Qo,6005
4
4
  sqlite_graph_memory/index_notes.py,sha256=yhlpdAhi9mGBSdiE2xJI3soMT4s12A15XZX37ZIIU88,10958
5
5
  sqlite_graph_memory/mcp_server.py,sha256=Oza1UFA0V8OEhDbFrHDYdexbxwnq99N1xbTTjhmAhss,10251
@@ -9,8 +9,8 @@ sqlite_graph_memory/schema.sql,sha256=8aySXKw3Azaxyzqbd76mKTfOaDP7FlpkLXtgwA8ZVK
9
9
  sqlite_graph_memory/turnstate_hook.py,sha256=fypGmUcHQkzlRN74tvIG07lr9uAXpp2GjetqthkuMc8,8641
10
10
  sqlite_graph_memory/turnstate_show.py,sha256=Bij4POJNSbJunHwGgm4i2NzkJQms8QBpR0mM9VVeKy4,3251
11
11
  sqlite_graph_memory/vault_stats.py,sha256=zlJm1b7HTiYIpZe8_7OUM-ywszeQjsQrj8zvkqnuI5w,9496
12
- sqlite_graph_memory-0.3.7.dist-info/METADATA,sha256=x3ENDEHqZwJjrBG9mPzlyNHf5mKI7uerOL_EIjl87wQ,41619
13
- sqlite_graph_memory-0.3.7.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
14
- sqlite_graph_memory-0.3.7.dist-info/entry_points.txt,sha256=lpoCm-jNjhBEtcQ16iIUd0ivr92Gr4c_fSRls2Zvbb0,432
15
- sqlite_graph_memory-0.3.7.dist-info/licenses/LICENSE,sha256=p88nZdrfMUiES3_MpUEwhGmqz2hQFpyMh0k0cqdpfU8,1082
16
- sqlite_graph_memory-0.3.7.dist-info/RECORD,,
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,,