coldmemory 0.3.6__tar.gz → 0.3.7__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 (53) hide show
  1. {coldmemory-0.3.6/coldmemory.egg-info → coldmemory-0.3.7}/PKG-INFO +33 -5
  2. coldmemory-0.3.6/PKG-INFO → coldmemory-0.3.7/README.md +31 -34
  3. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/__init__.py +1 -1
  4. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/__main__.py +6 -0
  5. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/disk_index.py +40 -94
  6. coldmemory-0.3.7/coldmemory/doctor.py +149 -0
  7. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/hooks_snippet.py +11 -3
  8. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/hybrid.py +0 -7
  9. coldmemory-0.3.6/README.md → coldmemory-0.3.7/coldmemory.egg-info/PKG-INFO +62 -3
  10. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory.egg-info/SOURCES.txt +2 -0
  11. {coldmemory-0.3.6 → coldmemory-0.3.7}/integrations/hermes/coldmemory/plugin.yaml +1 -1
  12. {coldmemory-0.3.6 → coldmemory-0.3.7}/pyproject.toml +16 -1
  13. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_coldmemory.py +8 -0
  14. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_disk_index.py +0 -1
  15. coldmemory-0.3.7/tests/test_doctor_and_snippet.py +199 -0
  16. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_hermes_entry_point.py +2 -0
  17. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_hybrid_retrieval.py +24 -3
  18. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_init_onboarding.py +1 -2
  19. {coldmemory-0.3.6 → coldmemory-0.3.7}/LICENSE +0 -0
  20. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/adversarial_ingest_bench.py +0 -0
  21. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/bench_v1.py +0 -0
  22. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/benchmark.py +0 -0
  23. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/cartridge_spec.py +0 -0
  24. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/citations.py +0 -0
  25. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/hermes_provider.py +0 -0
  26. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/ingest.py +0 -0
  27. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/ingest_policy.py +0 -0
  28. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/init_cmd.py +0 -0
  29. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/ledger.py +0 -0
  30. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/mcp_server.py +0 -0
  31. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/multihop_retriever.py +0 -0
  32. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/push.py +0 -0
  33. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/redact.py +0 -0
  34. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/scope_keys.py +0 -0
  35. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/sessions.py +0 -0
  36. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory/verifier.py +0 -0
  37. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory.egg-info/dependency_links.txt +0 -0
  38. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory.egg-info/entry_points.txt +0 -0
  39. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory.egg-info/requires.txt +0 -0
  40. {coldmemory-0.3.6 → coldmemory-0.3.7}/coldmemory.egg-info/top_level.txt +0 -0
  41. {coldmemory-0.3.6 → coldmemory-0.3.7}/integrations/hermes/coldmemory/__init__.py +0 -0
  42. {coldmemory-0.3.6 → coldmemory-0.3.7}/setup.cfg +0 -0
  43. {coldmemory-0.3.6 → coldmemory-0.3.7}/skills/coldmemory/SKILL.md +0 -0
  44. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_adversarial_ingest.py +0 -0
  45. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_bench_v1.py +0 -0
  46. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_brief_allocation.py +0 -0
  47. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_chat_prf.py +0 -0
  48. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_l0_brief.py +0 -0
  49. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_ledger_push.py +0 -0
  50. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_multihop_v02.py +0 -0
  51. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_scope_keys.py +0 -0
  52. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_scope_stacks.py +0 -0
  53. {coldmemory-0.3.6 → coldmemory-0.3.7}/tests/test_sessions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: coldmemory
3
- Version: 0.3.6
3
+ Version: 0.3.7
4
4
  Summary: Local-first AI agent memory with live file:line disk grounding, Keyed Decision Ledger, and local MCP — pure Python stdlib.
5
5
  Author: ColdStack
6
6
  License: Apache-2.0
@@ -8,7 +8,7 @@ Project-URL: Homepage, https://coldstack.dev
8
8
  Project-URL: Documentation, https://coldstack.dev/proof
9
9
  Project-URL: Repository, https://github.com/coldstack-dev/coldstack
10
10
  Project-URL: Issues, https://github.com/coldstack-dev/coldstack/issues
11
- Keywords: mcp,memory,ai-agents,claude-code,codex,sqlite,local-first
11
+ Keywords: mcp,memory,agent-memory,ai-agents,claude-code,codex,cursor,cline,goose,hermes,openbot,markdown,sqlite,local-first
12
12
  Classifier: Development Status :: 4 - Beta
13
13
  Classifier: Intended Audience :: Developers
14
14
  Classifier: License :: OSI Approved :: Apache Software License
@@ -41,17 +41,43 @@ ColdMemory gives any MCP client short answers from your notes and repos. Each an
41
41
 
42
42
  ## Quickstart
43
43
 
44
- Install the `coldmemory` CLI into a virtual environment (system Python on Linux is often PEP 668 externally managed; zero runtime dependencies), then initialize your notes in one command:
44
+ Install `coldmemory` from [PyPI](https://pypi.org/project/coldmemory/) (Apache-2.0, Python 3.11+, zero runtime dependencies) and initialize your notes in one command:
45
+
46
+ ```bash
47
+ pip install coldmemory # or: uv tool install coldmemory
48
+ coldmemory init /path/to/notes # creates 0700 store, verifies 1 live file:line quote, previews client wiring
49
+ coldmemory init /path/to/notes --apply # backs up & wires detected clients automatically (idempotent)
50
+ coldmemory doctor # verifies Python, git, 0700 store, bundles, and a live memory_ask query
51
+ ```
52
+
53
+ ### Client Setup (`--tools memory_ask`: 234 `o200k_base` schema tokens)
54
+
55
+ All examples below use `STORE="${XDG_DATA_HOME:-$HOME/.local/share}/coldmemory"` (the default store created by `coldmemory init`).
56
+
57
+ | Client | Setup or Config Command |
58
+ |---|---|
59
+ | **Claude Code** | `claude mcp add coldmemory -- uvx coldmemory mcp --local-unsigned --tools memory_ask --store "$STORE"` |
60
+ | **Cursor / Cline** | `coldmemory snippet cline --store "$STORE" --local-unsigned --tools memory_ask` (`cursor` also supported) |
61
+ | **Goose** | `coldmemory snippet goose --store "$STORE" --local-unsigned --tools memory_ask` |
62
+ | **OpenBot** | `coldmemory snippet openbot --store "$STORE" --local-unsigned --tools memory_ask` |
63
+ | **Hermes** | Install into Hermes's Python environment (`pip install coldmemory`) so `hermes_agent.memory_providers` auto-registers; run `hermes memory setup` and set `COLDMEMORY_LOCAL_UNSIGNED=1` for unsigned private-store archive recall |
64
+ | **Codex / Grok CLI** | `coldmemory snippet codex ...` or `coldmemory snippet grok ...` (or `coldmemory init /path/to/notes --apply`) |
65
+
66
+ `server.json` provides Official MCP Registry metadata (`io.github.coldstack-dev/coldmemory`). For step-by-step agent installation (for example in Cline), see [llms-install.md](https://github.com/coldstack-dev/coldstack/blob/main/memory/llms-install.md).
67
+
68
+ <details>
69
+ <summary>Install from a local source checkout (including PEP 668 / offline Linux hosts)</summary>
45
70
 
46
71
  ```bash
47
72
  python3 -m venv .venv
48
73
  .venv/bin/python -m pip install --no-deps -e .
49
- .venv/bin/coldmemory init /path/to/notes # creates 0700 store, verifies 1 live file:line quote, previews client wiring
50
- .venv/bin/coldmemory init /path/to/notes --apply # backs up & wires Claude/Codex automatically + copies Hermes plugin (idempotent)
74
+ .venv/bin/coldmemory init /path/to/notes
51
75
  ```
52
76
 
53
77
  For offline installs where `setuptools>=70.1` (which includes `bdist_wheel`) is already on the host, create the venv with `python3 -m venv --system-site-packages .venv` and pass `--no-build-isolation` to `pip install` (or install a prebuilt wheel with `--no-deps`).
54
78
 
79
+ </details>
80
+
55
81
  `coldmemory init` auto-detects Claude Code, Codex, OpenBot, Hermes and Grok CLI (override with `--clients claude,codex,openbot,hermes,grok`, `--clients none`, or `--dry-run`). It never overwrites an existing bundle ID for different sources unless you pass `--force` (with `--apply`, `--force` also replaces existing signed or remote ColdMemory entries in selected clients), reuses unchanged revisions on re-run, creates timestamped backups before editing any client config (close running clients before `--apply` so they cannot race config saves), wires `--tools memory_ask` (234 schema tokens) plus `coldmemory.push` hooks for Claude Code and Codex (in Codex, run `/hooks` once to review and trust the generated hooks), copies the Hermes plugin files (printing its remaining env/config step), prints OpenBot Desktop's MCP form fields, and adds the same `memory_ask` server to `${GROK_HOME:-~/.grok}/config.toml` for Grok CLI (no hooks: Grok's session, prompt and compact hooks cannot inject model context, and Grok loads ColdMemory's MCP instructions natively).
56
82
 
57
83
  ## Try it on the synthetic company
@@ -280,6 +306,8 @@ python3 -m coldmemory approve --store ~/.local/share/coldmemory --id work <entry
280
306
  ## Files and compatibility
281
307
 
282
308
  ```text
309
+ <store>/_ledger/<scope>/ Keyed Decision Ledger notes (live authoritative rules + --why-not)
310
+ <store>/.coldmemory-index/idx-*.{sqlite,bin} SQLite metadata/trigrams + mmap binary postings (COLDMEMORY_INDEX_CACHE)
283
311
  <store>/<id>/current.json live and previous revisions
284
312
  <store>/<id>/queue.jsonl notes waiting for approval
285
313
  <store>/<id>/<revision>/memory.json base model, source hashes, build time, scope and file hashes
@@ -1,34 +1,3 @@
1
- Metadata-Version: 2.4
2
- Name: coldmemory
3
- Version: 0.3.6
4
- Summary: Local-first AI agent memory with live file:line disk grounding, Keyed Decision Ledger, and local MCP — pure Python stdlib.
5
- Author: ColdStack
6
- License: Apache-2.0
7
- Project-URL: Homepage, https://coldstack.dev
8
- Project-URL: Documentation, https://coldstack.dev/proof
9
- Project-URL: Repository, https://github.com/coldstack-dev/coldstack
10
- Project-URL: Issues, https://github.com/coldstack-dev/coldstack/issues
11
- Keywords: mcp,memory,ai-agents,claude-code,codex,sqlite,local-first
12
- Classifier: Development Status :: 4 - Beta
13
- Classifier: Intended Audience :: Developers
14
- Classifier: License :: OSI Approved :: Apache Software License
15
- Classifier: Operating System :: POSIX :: Linux
16
- Classifier: Programming Language :: Python :: 3
17
- Classifier: Programming Language :: Python :: 3.11
18
- Classifier: Programming Language :: Python :: 3.12
19
- Classifier: Programming Language :: Python :: 3.13
20
- Classifier: Programming Language :: Python :: 3.14
21
- Classifier: Topic :: Software Development :: Libraries
22
- Classifier: Topic :: Text Processing :: Indexing
23
- Requires-Python: >=3.11
24
- Description-Content-Type: text/markdown
25
- License-File: LICENSE
26
- Provides-Extra: hybrid
27
- Requires-Dist: numpy; extra == "hybrid"
28
- Requires-Dist: onnxruntime; extra == "hybrid"
29
- Requires-Dist: tokenizers; extra == "hybrid"
30
- Dynamic: license-file
31
-
32
1
  # ColdMemory v0.3
33
2
 
34
3
  <!-- mcp-name: io.github.coldstack-dev/coldmemory -->
@@ -41,17 +10,43 @@ ColdMemory gives any MCP client short answers from your notes and repos. Each an
41
10
 
42
11
  ## Quickstart
43
12
 
44
- Install the `coldmemory` CLI into a virtual environment (system Python on Linux is often PEP 668 externally managed; zero runtime dependencies), then initialize your notes in one command:
13
+ Install `coldmemory` from [PyPI](https://pypi.org/project/coldmemory/) (Apache-2.0, Python 3.11+, zero runtime dependencies) and initialize your notes in one command:
14
+
15
+ ```bash
16
+ pip install coldmemory # or: uv tool install coldmemory
17
+ coldmemory init /path/to/notes # creates 0700 store, verifies 1 live file:line quote, previews client wiring
18
+ coldmemory init /path/to/notes --apply # backs up & wires detected clients automatically (idempotent)
19
+ coldmemory doctor # verifies Python, git, 0700 store, bundles, and a live memory_ask query
20
+ ```
21
+
22
+ ### Client Setup (`--tools memory_ask`: 234 `o200k_base` schema tokens)
23
+
24
+ All examples below use `STORE="${XDG_DATA_HOME:-$HOME/.local/share}/coldmemory"` (the default store created by `coldmemory init`).
25
+
26
+ | Client | Setup or Config Command |
27
+ |---|---|
28
+ | **Claude Code** | `claude mcp add coldmemory -- uvx coldmemory mcp --local-unsigned --tools memory_ask --store "$STORE"` |
29
+ | **Cursor / Cline** | `coldmemory snippet cline --store "$STORE" --local-unsigned --tools memory_ask` (`cursor` also supported) |
30
+ | **Goose** | `coldmemory snippet goose --store "$STORE" --local-unsigned --tools memory_ask` |
31
+ | **OpenBot** | `coldmemory snippet openbot --store "$STORE" --local-unsigned --tools memory_ask` |
32
+ | **Hermes** | Install into Hermes's Python environment (`pip install coldmemory`) so `hermes_agent.memory_providers` auto-registers; run `hermes memory setup` and set `COLDMEMORY_LOCAL_UNSIGNED=1` for unsigned private-store archive recall |
33
+ | **Codex / Grok CLI** | `coldmemory snippet codex ...` or `coldmemory snippet grok ...` (or `coldmemory init /path/to/notes --apply`) |
34
+
35
+ `server.json` provides Official MCP Registry metadata (`io.github.coldstack-dev/coldmemory`). For step-by-step agent installation (for example in Cline), see [llms-install.md](https://github.com/coldstack-dev/coldstack/blob/main/memory/llms-install.md).
36
+
37
+ <details>
38
+ <summary>Install from a local source checkout (including PEP 668 / offline Linux hosts)</summary>
45
39
 
46
40
  ```bash
47
41
  python3 -m venv .venv
48
42
  .venv/bin/python -m pip install --no-deps -e .
49
- .venv/bin/coldmemory init /path/to/notes # creates 0700 store, verifies 1 live file:line quote, previews client wiring
50
- .venv/bin/coldmemory init /path/to/notes --apply # backs up & wires Claude/Codex automatically + copies Hermes plugin (idempotent)
43
+ .venv/bin/coldmemory init /path/to/notes
51
44
  ```
52
45
 
53
46
  For offline installs where `setuptools>=70.1` (which includes `bdist_wheel`) is already on the host, create the venv with `python3 -m venv --system-site-packages .venv` and pass `--no-build-isolation` to `pip install` (or install a prebuilt wheel with `--no-deps`).
54
47
 
48
+ </details>
49
+
55
50
  `coldmemory init` auto-detects Claude Code, Codex, OpenBot, Hermes and Grok CLI (override with `--clients claude,codex,openbot,hermes,grok`, `--clients none`, or `--dry-run`). It never overwrites an existing bundle ID for different sources unless you pass `--force` (with `--apply`, `--force` also replaces existing signed or remote ColdMemory entries in selected clients), reuses unchanged revisions on re-run, creates timestamped backups before editing any client config (close running clients before `--apply` so they cannot race config saves), wires `--tools memory_ask` (234 schema tokens) plus `coldmemory.push` hooks for Claude Code and Codex (in Codex, run `/hooks` once to review and trust the generated hooks), copies the Hermes plugin files (printing its remaining env/config step), prints OpenBot Desktop's MCP form fields, and adds the same `memory_ask` server to `${GROK_HOME:-~/.grok}/config.toml` for Grok CLI (no hooks: Grok's session, prompt and compact hooks cannot inject model context, and Grok loads ColdMemory's MCP instructions natively).
56
51
 
57
52
  ## Try it on the synthetic company
@@ -280,6 +275,8 @@ python3 -m coldmemory approve --store ~/.local/share/coldmemory --id work <entry
280
275
  ## Files and compatibility
281
276
 
282
277
  ```text
278
+ <store>/_ledger/<scope>/ Keyed Decision Ledger notes (live authoritative rules + --why-not)
279
+ <store>/.coldmemory-index/idx-*.{sqlite,bin} SQLite metadata/trigrams + mmap binary postings (COLDMEMORY_INDEX_CACHE)
283
280
  <store>/<id>/current.json live and previous revisions
284
281
  <store>/<id>/queue.jsonl notes waiting for approval
285
282
  <store>/<id>/<revision>/memory.json base model, source hashes, build time, scope and file hashes
@@ -5,7 +5,7 @@ from pathlib import Path
5
5
 
6
6
  from .citations import Citation, parse_citations
7
7
 
8
- __version__ = "0.3.6"
8
+ __version__ = "0.3.7"
9
9
  __all__ = ["Citation", "parse_citations", "resolve_v2_spec_path"]
10
10
 
11
11
 
@@ -112,13 +112,19 @@ def main(argv=None):
112
112
  sub.add_argument("--out", type=Path, help="default: $XDG_DATA_HOME/coldmemory-sessions")
113
113
  sub.add_argument("root", nargs="*", type=Path, help="default: ~/.claude/projects and ~/.codex/sessions")
114
114
  init_cmd.register(commands)
115
+ from . import doctor as doctor_cmd
116
+ doctor_cmd.register(commands)
115
117
  for name in ("decide", "decisions", "forget"):
116
118
  commands.add_parser(name, add_help=False, help=f"decision ledger: python -m coldmemory.ledger {name} --help")
119
+ commands.add_parser("snippet", add_help=False, help="print MCP config snippet for a client: coldmemory snippet --help")
117
120
  commands.add_parser("mcp", add_help=False, help="run the stdio MCP server: coldmemory mcp --help")
118
121
  argv = sys.argv[1:] if argv is None else argv
119
122
  if argv[:1] == ["mcp"]:
120
123
  from . import mcp_server
121
124
  return mcp_server.main(argv[1:])
125
+ if argv[:1] == ["snippet"]:
126
+ from . import hooks_snippet
127
+ return hooks_snippet.main(argv[1:])
122
128
  if argv[:1] and argv[0] in ("decide", "decisions", "forget"):
123
129
  from . import ledger
124
130
  return ledger.main(["list" if argv[0] == "decisions" else argv[0], *argv[1:]])
@@ -36,7 +36,6 @@ import time
36
36
  import zlib
37
37
 
38
38
  from .ingest import (
39
- PARALLEL_READS,
40
39
  PARSER,
41
40
  STALE,
42
41
  Note,
@@ -45,9 +44,6 @@ from .ingest import (
45
44
  StaleNoteRead,
46
45
  _NOTION_ID,
47
46
  _candidates,
48
- _named,
49
- _signature,
50
- _state,
51
47
  check_rel,
52
48
  frontmatter,
53
49
  parse_note,
@@ -139,6 +135,26 @@ def _compress_blob(raw):
139
135
  return b"\x00" + raw
140
136
 
141
137
 
138
+ def _pad8(bf):
139
+ rem = (-bf.tell()) & 7
140
+ if rem:
141
+ bf.write(b"\x00" * rem)
142
+ return bf.tell()
143
+
144
+
145
+ def _flush_trigrams(con, tri_buckets):
146
+ if not tri_buckets:
147
+ return
148
+ con.executemany(
149
+ "INSERT INTO trigrams VALUES (?,?,?,?)",
150
+ (
151
+ (fc, tl, tri, _compress_blob("\n".join(words_list).encode("utf-8")))
152
+ for (fc, tl, tri), words_list in tri_buckets.items()
153
+ ),
154
+ )
155
+ tri_buckets.clear()
156
+
157
+
142
158
  def _decompress_blob(blob):
143
159
  if not isinstance(blob, (bytes, bytearray, memoryview)):
144
160
  raise IndexInvalid("corrupt blob storage type in SQLite index")
@@ -509,8 +525,6 @@ class NoteLinesCache:
509
525
  return len(self._cache)
510
526
 
511
527
 
512
- # ---- Read-only Mapping / Sequence views backed by DiskIndex ----
513
-
514
528
 
515
529
  class _PostingsView(Mapping):
516
530
  def __init__(self, index):
@@ -1183,8 +1197,6 @@ class DiskIndex:
1183
1197
  except OSError:
1184
1198
  pass
1185
1199
 
1186
- # ---- Low-level mmap array slices ----
1187
-
1188
1200
  @staticmethod
1189
1201
  def _validate_term_row(row):
1190
1202
  if row is None:
@@ -1234,8 +1246,6 @@ class DiskIndex:
1234
1246
  ids = self._postings[off + dbytes : off + dbytes + 4 * count].cast("I")
1235
1247
  return ids, shares
1236
1248
 
1237
- # ---- Term & posting lookups ----
1238
-
1239
1249
  def term_row(self, term):
1240
1250
  with self._lock:
1241
1251
  if term in self._term_lru:
@@ -1315,8 +1325,6 @@ class DiskIndex:
1315
1325
  for (t,) in rows:
1316
1326
  yield t
1317
1327
 
1318
- # ---- Fuzzy OOV trigram lookup ----
1319
-
1320
1328
  def fuzzy_candidates(self, oov_term):
1321
1329
  """Return Counter({vocab_term: shared_trigram_count}) matching first_char & len within 1."""
1322
1330
  length = len(oov_term)
@@ -1343,8 +1351,6 @@ class DiskIndex:
1343
1351
  cand_hits[vocab] += mult
1344
1352
  return cand_hits
1345
1353
 
1346
- # ---- Doc / section / note lookups ----
1347
-
1348
1354
  def _decode_heading(self, h_off, h_len):
1349
1355
  if not h_len:
1350
1356
  return ""
@@ -1993,7 +1999,6 @@ class DiskIndex:
1993
1999
  here = posixpath.dirname(key)
1994
2000
  return min(found, key=lambda cand: (posixpath.dirname(cand) != here, cand.count("/"), cand), default=None)
1995
2001
 
1996
- # Compute exact live supersession targets from all unchanged disk notes
1997
2002
  live_older = {}
1998
2003
  live_newer = {}
1999
2004
  verified_signed_keys = set()
@@ -2019,7 +2024,6 @@ class DiskIndex:
2019
2024
  for dst in newer_set:
2020
2025
  extra_superseded[dk].add(dst)
2021
2026
 
2022
- # Re-resolve wikilinks on unchanged disk notes whose target was deleted or affected by added/renamed notes
2023
2027
  for dk, d_src, d_rel, base_links, d_raw_links in disk_link_candidates:
2024
2028
  new_links = sorted({dst for dst in (resolve(d_src, d_rel, dk, t) for t in d_raw_links) if dst and dst != dk})
2025
2029
  old_live_links = sorted(k for k in base_links if k not in removed)
@@ -2032,7 +2036,6 @@ class DiskIndex:
2032
2036
  for dst in old_set - new_set:
2033
2037
  drop_backlinks[dst].add(dk)
2034
2038
 
2035
- # Compute live supersession & link targets from override notes
2036
2039
  ov_older = {}
2037
2040
  for k, note in overrides.items():
2038
2041
  new_older = {dst for dst in (resolve(note.source.label, note.rel, k, t) for t in note.raw_older) if dst and dst != k}
@@ -2144,8 +2147,6 @@ class DiskIndex:
2144
2147
  out[key] = (path, sig)
2145
2148
  return out
2146
2149
 
2147
- # ---- Bundle graph lookups ----
2148
-
2149
2150
  def has_bundle_graph_key(self, key):
2150
2151
  with self._lock:
2151
2152
  return self._con.execute("SELECT 1 FROM bundle_graph WHERE key = ?", (key,)).fetchone() is not None
@@ -2167,8 +2168,6 @@ class DiskIndex:
2167
2168
  for (k,) in batch:
2168
2169
  yield k
2169
2170
 
2170
- # ---- LinkGraph lookups ----
2171
-
2172
2171
  @staticmethod
2173
2172
  def _unpack_uint32_blob(blob, max_bytes=None):
2174
2173
  if not isinstance(blob, (bytes, bytearray, memoryview)) or len(blob) % 4 != 0:
@@ -2276,8 +2275,6 @@ class DiskIndex:
2276
2275
  return out
2277
2276
 
2278
2277
 
2279
- # ---- SQLite schema creation & atomic writer helpers ----
2280
-
2281
2278
 
2282
2279
  def _create_schema(con):
2283
2280
  con.executescript(
@@ -2452,7 +2449,6 @@ def build_disk_index_in_memory(
2452
2449
  pair_id = os.urandom(16)
2453
2450
  source_idx_map = {(s.kind, s.label, s.root): idx for idx, s in enumerate(bundle.sources)}
2454
2451
 
2455
- # Collect per-note and per-section stats in exact pre-PR _candidates() walk order
2456
2452
  keys = sorted(
2457
2453
  corpus.notes.keys(),
2458
2454
  key=lambda k: (
@@ -2592,7 +2588,6 @@ def build_disk_index_in_memory(
2592
2588
  max_date_ord = max(dated_ords) if dated_ords else None
2593
2589
  max_date_str = datetime.date.fromordinal(max_date_ord).isoformat() if max_date_ord else ""
2594
2590
 
2595
- # Write binary + sqlite atomically to temp files
2596
2591
  bin_fd = -1
2597
2592
  tmp_bin = tmp_sql = None
2598
2593
 
@@ -2628,32 +2623,24 @@ def build_disk_index_in_memory(
2628
2623
  expected_graph_sha = bundle.manifest.get("files", {}).get("graph.json")
2629
2624
  has_bg, n_bg = _populate_bundle_graph(con, bundle.path / "graph.json", expected_graph_sha)
2630
2625
 
2631
- # Write binary sections
2632
2626
  with os.fdopen(bin_fd, "wb") as bf:
2633
2627
  bin_fd = -1
2634
2628
  bf.write(b"\x00" * BIN_HEADER_SIZE)
2635
2629
 
2636
- def pad8():
2637
- pos = bf.tell()
2638
- rem = (-pos) & 7
2639
- if rem:
2640
- bf.write(b"\x00" * rem)
2641
- return bf.tell()
2642
-
2643
- norm_off = pad8()
2630
+ norm_off = _pad8(bf)
2644
2631
  bf.write(norm.tobytes())
2645
- note_norm_off = pad8()
2632
+ note_norm_off = _pad8(bf)
2646
2633
  bf.write(note_norm.tobytes())
2647
- spans_off = pad8()
2634
+ spans_off = _pad8(bf)
2648
2635
  bf.write(spans.tobytes())
2649
- date_ord_off = pad8()
2636
+ date_ord_off = _pad8(bf)
2650
2637
  bf.write(note_date_ords.tobytes())
2651
- doc_meta_off = pad8()
2638
+ doc_meta_off = _pad8(bf)
2652
2639
  bf.write(doc_meta.tobytes())
2653
- headings_off = pad8()
2640
+ headings_off = _pad8(bf)
2654
2641
  bf.write(headings_buf)
2655
2642
  headings_len = len(headings_buf)
2656
- postings_off = pad8()
2643
+ postings_off = _pad8(bf)
2657
2644
 
2658
2645
  # Write terms in sorted alphabetical order so trigram buckets flush per first_char
2659
2646
  term_rows = []
@@ -2661,18 +2648,6 @@ def build_disk_index_in_memory(
2661
2648
  cur_char = None
2662
2649
  tri_buckets = defaultdict(list)
2663
2650
 
2664
- def flush_trigrams():
2665
- if not tri_buckets:
2666
- return
2667
- con.executemany(
2668
- "INSERT INTO trigrams VALUES (?,?,?,?)",
2669
- (
2670
- (fc, tl, tri, _compress_blob("\n".join(words_list).encode("utf-8")))
2671
- for (fc, tl, tri), words_list in tri_buckets.items()
2672
- ),
2673
- )
2674
- tri_buckets.clear()
2675
-
2676
2651
  sorted_terms = sorted(sec_postings.keys() | note_postings.keys())
2677
2652
  n_sec_terms = 0
2678
2653
  for term in sorted_terms:
@@ -2709,7 +2684,7 @@ def build_disk_index_in_memory(
2709
2684
  d_arr, c_arr, owners, norm, n_arr, nc_arr, note_norm, idf_val, note_idf_val, note_blend
2710
2685
  )
2711
2686
  ceil_cnt = len(c_nums)
2712
- ceil_rel = pad8() - postings_off
2687
+ ceil_rel = _pad8(bf) - postings_off
2713
2688
  bf.write(c_shares.tobytes())
2714
2689
  bf.write(c_nums.tobytes())
2715
2690
  else:
@@ -2727,7 +2702,7 @@ def build_disk_index_in_memory(
2727
2702
  if df > 0 and len(term) >= 5 and term.isalpha():
2728
2703
  fc = term[0]
2729
2704
  if cur_char is not None and fc != cur_char:
2730
- flush_trigrams()
2705
+ _flush_trigrams(con, tri_buckets)
2731
2706
  cur_char = fc
2732
2707
  tl = len(term)
2733
2708
  for i in range(tl - 2):
@@ -2735,7 +2710,7 @@ def build_disk_index_in_memory(
2735
2710
 
2736
2711
  if term_rows:
2737
2712
  con.executemany("INSERT INTO terms VALUES (?,?,?,?,?,?,?,?)", term_rows)
2738
- flush_trigrams()
2713
+ _flush_trigrams(con, tri_buckets)
2739
2714
 
2740
2715
  postings_len = bf.tell() - postings_off
2741
2716
  total_bytes = bf.tell()
@@ -2816,8 +2791,6 @@ def build_disk_index_in_memory(
2816
2791
  raise
2817
2792
 
2818
2793
 
2819
- # ---- Streaming External-Merge Builder for Large Vaults (>= STREAM_THRESHOLD notes) ----
2820
-
2821
2794
 
2822
2795
  def _worker_parse_and_tokenize(item):
2823
2796
  """Run in worker process: read, parse, tokenize, extract LinkGraph labels, discard lines immediately."""
@@ -3007,7 +2980,6 @@ def _streaming_build_worker(args):
3007
2980
  pinned_shas = {k: v["sha256"] for k, v in raw_g.items()}
3008
2981
  del raw_g
3009
2982
 
3010
- # Stage 1: Walk candidates
3011
2983
  walked_at = time.time()
3012
2984
  todo = []
3013
2985
  skipped = Counter()
@@ -3027,10 +2999,8 @@ def _streaming_build_worker(args):
3027
2999
  except FileNotFoundError:
3028
3000
  continue
3029
3001
  todo.append((s_idx, source, rel, pinned_shas[key] if pinned_shas is not None else None))
3030
- # Exact pre-PR _candidates() walk order matching build_disk_index_in_memory for identical tie-breaking
3031
3002
  todo.sort(key=lambda item: (item[0], _canonical_rel_key(item[1].kind, item[2])))
3032
3003
 
3033
- # Stage 2: Parallel parse + tokenize in chunks, flushing sorted posting runs to a private temp dir
3034
3004
  pair_id = os.urandom(16)
3035
3005
  run_dir = Path(tempfile.mkdtemp(prefix=".runs-", dir=folder))
3036
3006
  os.chmod(run_dir, 0o700)
@@ -3172,7 +3142,6 @@ def _streaming_build_worker(args):
3172
3142
  flush_run()
3173
3143
  del todo
3174
3144
 
3175
- # Stage 3: Link resolution over slim metadata
3176
3145
  _link_slim_notes(slim_meta)
3177
3146
 
3178
3147
  spans.append(len(doc_sizes))
@@ -3187,7 +3156,6 @@ def _streaming_build_worker(args):
3187
3156
  max_date_str = datetime.date.fromordinal(max_date_ord).isoformat() if max_date_ord else ""
3188
3157
  del doc_sizes, note_sizes, dated_ords
3189
3158
 
3190
- # Stage 4: Write SQLite + merged .bin atomically
3191
3159
  bin_fd, tmp_bin = _create_private_temp(folder, f".{bin_path.name}.")
3192
3160
  sql_fd, tmp_sql = _create_private_temp(folder, f".{sqlite_path.name}.")
3193
3161
  os.close(sql_fd)
@@ -3196,7 +3164,6 @@ def _streaming_build_worker(args):
3196
3164
  try:
3197
3165
  _create_schema(con)
3198
3166
 
3199
- # Insert notes in chunks & immediately free slim_meta
3200
3167
  note_rows = []
3201
3168
  for e in slim_meta:
3202
3169
  sig = e["sig"] or (0, 0, 0, 0)
@@ -3269,37 +3236,28 @@ def _streaming_build_worker(args):
3269
3236
 
3270
3237
  has_bg, n_bg = _populate_bundle_graph(con, graph_path, expected_graph_sha)
3271
3238
 
3272
- # Write .bin fixed sections + K-way merged postings
3273
3239
  with os.fdopen(bin_fd, "wb") as bf:
3274
3240
  bin_fd = -1
3275
3241
  bf.write(b"\x00" * BIN_HEADER_SIZE)
3276
3242
 
3277
- def pad8():
3278
- pos = bf.tell()
3279
- rem = (-pos) & 7
3280
- if rem:
3281
- bf.write(b"\x00" * rem)
3282
- return bf.tell()
3283
-
3284
- norm_off = pad8()
3243
+ norm_off = _pad8(bf)
3285
3244
  bf.write(norm.tobytes())
3286
- note_norm_off = pad8()
3245
+ note_norm_off = _pad8(bf)
3287
3246
  bf.write(note_norm.tobytes())
3288
- spans_off = pad8()
3247
+ spans_off = _pad8(bf)
3289
3248
  bf.write(spans.tobytes())
3290
3249
  del spans
3291
- date_ord_off = pad8()
3250
+ date_ord_off = _pad8(bf)
3292
3251
  bf.write(note_date_ords.tobytes())
3293
3252
  del note_date_ords
3294
- doc_meta_off = pad8()
3253
+ doc_meta_off = _pad8(bf)
3295
3254
  bf.write(doc_meta.tobytes())
3296
3255
  del doc_meta
3297
- headings_off = pad8()
3256
+ headings_off = _pad8(bf)
3298
3257
  with open(headings_path, "rb") as hf:
3299
3258
  shutil.copyfileobj(hf, bf, 1 << 20)
3300
- postings_off = pad8()
3259
+ postings_off = _pad8(bf)
3301
3260
 
3302
- # K-way merge over sorted run files in alphabetical term order
3303
3261
  iters = [_iter_run_file(rp) for rp in run_paths]
3304
3262
  heap = []
3305
3263
  for r_idx, it in enumerate(iters):
@@ -3313,18 +3271,6 @@ def _streaming_build_worker(args):
3313
3271
  cur_char = None
3314
3272
  tri_buckets = defaultdict(list)
3315
3273
 
3316
- def flush_trigrams():
3317
- if not tri_buckets:
3318
- return
3319
- con.executemany(
3320
- "INSERT INTO trigrams VALUES (?,?,?,?)",
3321
- (
3322
- (fc, tl, tri, _compress_blob("\n".join(words_list).encode("utf-8")))
3323
- for (fc, tl, tri), words_list in tri_buckets.items()
3324
- ),
3325
- )
3326
- tri_buckets.clear()
3327
-
3328
3274
  while heap:
3329
3275
  term = heap[0][0]
3330
3276
  sd_parts = []
@@ -3386,7 +3332,7 @@ def _streaming_build_worker(args):
3386
3332
  d_arr, c_arr, owners, norm, n_arr, nc_arr, note_norm, idf_val, note_idf_val, NOTE_BLEND
3387
3333
  )
3388
3334
  ceil_cnt = len(c_nums)
3389
- ceil_rel = pad8() - postings_off
3335
+ ceil_rel = _pad8(bf) - postings_off
3390
3336
  bf.write(c_shares.tobytes())
3391
3337
  bf.write(c_nums.tobytes())
3392
3338
  n_terms += 1
@@ -3405,7 +3351,7 @@ def _streaming_build_worker(args):
3405
3351
  if df and len(term) >= 5 and term.isalpha():
3406
3352
  fc = term[0]
3407
3353
  if cur_char is not None and fc != cur_char:
3408
- flush_trigrams()
3354
+ _flush_trigrams(con, tri_buckets)
3409
3355
  cur_char = fc
3410
3356
  tl = len(term)
3411
3357
  for i in range(tl - 2):
@@ -3413,7 +3359,7 @@ def _streaming_build_worker(args):
3413
3359
 
3414
3360
  if term_rows:
3415
3361
  con.executemany("INSERT INTO terms VALUES (?,?,?,?,?,?,?,?)", term_rows)
3416
- flush_trigrams()
3362
+ _flush_trigrams(con, tri_buckets)
3417
3363
 
3418
3364
  postings_len = bf.tell() - postings_off
3419
3365
  total_bytes = bf.tell()