nexusmem 0.9.0 → 0.10.0

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.
package/README.md CHANGED
@@ -1,529 +1,550 @@
1
- # NexusMem
2
-
3
- [![CI](https://github.com/yaminbkk/NexusMem/actions/workflows/ci.yml/badge.svg)](https://github.com/yaminbkk/NexusMem/actions/workflows/ci.yml)
4
- [![npm](https://img.shields.io/npm/v/nexusmem)](https://www.npmjs.com/package/nexusmem)
5
- [![npm downloads](https://img.shields.io/npm/dm/nexusmem)](https://www.npmjs.com/package/nexusmem)
6
- [![License: MIT](https://img.shields.io/badge/license-MIT-informational)](LICENSE)
7
- ![Node](https://img.shields.io/badge/node-%3E%3D22-brightgreen)
8
-
9
- ![NexusMem: init, sync, status, and a query against this repo's own history](docs/demo.gif)
10
-
11
- Your coding agent can read `git log`. It cannot read the four things you tried last Tuesday that
12
- didn't work.
13
-
14
- NexusMem records what actually happened on your machine (shell commands and their exit codes, git
15
- history down to the patch of each changed file, project docs, optionally your assistant transcripts)
16
- into a local SQLite database, and
17
- serves back a ranked, token-budgeted slice of it on demand. Everything stays on disk. No account, no
18
- cloud, no telemetry.
19
-
20
- The shell history is the part worth caring about. Git tells an agent what shipped. Shell history
21
- tells it what was attempted, in what order, and which commands exited non-zero. That information
22
- exists nowhere else, and it disappears when your terminal scrollback rolls over.
23
-
24
- **Contents:** [Try it](#try-it) · [Exact shell capture](#optional-exact-shell-capture) ·
25
- [Failure → fix chains](#failure--fix-chains-opt-in) · [How retrieval works](#how-retrieval-works) ·
26
- [Session summaries](#session-summaries-optional-local-model) · [Use it from an agent](#use-it-from-an-agent)
27
- · [What it costs you](#what-it-costs-you) · [Staleness & provenance](#staleness--provenance) ·
28
- [Where it breaks](#where-it-breaks) · [Commands](#commands) · [Cross-project recall](#recall-across-projects)
29
- · [On disk](#on-disk) · [Development](#development)
30
-
31
- ## Try it
32
-
33
- From inside any git repository:
34
-
35
- ```
36
- npx nexusmem init
37
- npx nexusmem sync
38
- ```
39
-
40
- Then ask it something. Real output from this repository, top 2 of 5 hits:
41
-
42
- ```
43
- $ nexusmem query "windows spawn failure"
44
-
45
- Relevant history for: windows spawn failure
46
-
47
- - 2026-08-09 [observed] fix: distinguish a failed git spawn from "not a git repository"
48
- readRepoInfo collapsed three unrelated failures into one error: git running and reporting
49
- the path is not a work tree, git not being installed, and the process failing to spawn at
50
- all. Dogfooding hit the third case in two separate sessions...
51
- - 2026-08-09 [authored] README.md — Before a tagged release
52
- - [ ] Retry on transient process-spawn failures on Windows
53
- ```
54
-
55
- `[observed]`/`[authored]` is the provenance tag (see [Staleness & provenance](#staleness--provenance))
56
- — a commit is a directly observed event, a doc section is a written claim that could go stale.
57
-
58
- A commit and a docs section, ranked against each other, inside whatever token budget you gave it.
59
- Nothing was summarized by a model on the way out; the ranker just decided what not to send. (One
60
- optional source, session summaries, does run a local model — but at ingest time, never on the way
61
- out. What you query is always stored text.)
62
-
63
- For a sense of what actually accumulates, here is `nexusmem status` on this repo after two days:
64
-
65
- ```
66
- 527 node(s) 2026-08-08 .. 2026-08-09
67
- 321 shell_command
68
- 130 conversation_turn
69
- 60 doc_section
70
- 16 git_commit
71
- ```
72
-
73
- Sixteen commits. Three hundred and twenty-one shell commands. The commits were already retrievable
74
- by any agent with a terminal. The rest was not.
75
-
76
- That `conversation_turn` row only appears because this corpus was synced with `--conversation`.
77
- Assistant transcripts are the one source that is off by default and stays off until you opt in, since
78
- they are the likeliest place for a pasted credential to be sitting. A default install indexes git
79
- commits, their diffs, shell and docs.
80
-
81
- Requirements: Node 22 or newer, and git. Node 20 will not work, because `better-sqlite3` ships no
82
- prebuilt binary for it and Node 20 went end-of-life in April 2026. Ollama is optional and only
83
- affects semantic search (see below).
84
-
85
- ## Optional: exact shell capture
86
-
87
- Scraped history files (PSReadLine, `.bash_history`, `.zsh_history`) give you command text and not
88
- much else. The hook gives you working directory, exit code and a real timestamp:
89
-
90
- ```bash
91
- nexusmem hook install
92
- ```
93
-
94
- It wraps your existing PowerShell prompt rather than replacing it, is idempotent, and
95
- `nexusmem hook remove` undoes it cleanly.
96
-
97
- Exit codes are what make this worth installing. A failed command is a stronger signal than a
98
- successful one, and without the hook there is no way to tell them apart.
99
-
100
- ## Failure → fix chains (opt-in)
101
-
102
- ```bash
103
- nexusmem sync --link-failures
104
- ```
105
-
106
- After a normal sync, this walks every failed `shell_command` (non-zero exit code) and looks for
107
- whatever later resolved it, using two independent heuristics: a later command in the same project
108
- and working directory, exact same normalized text, that exited `0` within 24h (**same-command
109
- retry**); and, separately, the best full-text match among nearby conversation turns or session
110
- summaries, requiring every significant word of the failing command to appear, not just one
111
- (**conversation bridge**). A failure can be linked by either, both, or neither.
112
-
113
- Both links are surfaced in query results. The conversation-bridge heuristic originally matched on
114
- any shared word, and dogfooding against this repo's own real history found it wrong on roughly half
115
- its links — a shared word as generic as "npm" was enough to link an unrelated discussion. Requiring
116
- every significant word fixed that: re-dogfooded against the same corpus, every resulting link (the
117
- full set produced, not a sample) checked out correct on manual review of the full text, not just the
118
- summary.
119
-
120
- When a linked failure appears in a result set, its fix rides along immediately after it, inheriting
121
- the failure's own relevance score rather than needing to match the query on its own merits. That is
122
- the point: a query about why something failed shouldn't need to separately guess the words used in
123
- whatever fixed it. This works across projects too — `query --all-projects` chains a failure to its
124
- fix using whichever project's own database recorded the link, since links are always local to the
125
- project they were found in.
126
-
127
- ```
128
- $ nexusmem query "why did npm whoami fail"
129
-
130
- - 2026-08-12 [observed] shell: npm whoami (exit 1)
131
- - 2026-08-12 [observed] shell: npm login (exit 0) -- linked as the fix
132
- ```
133
-
134
- ## How retrieval works
135
-
136
- Every source normalizes to the same `MemoryNode` shape, so a commit, a shell command and a docs
137
- section compete on equal terms. Retrieval runs BM25 over FTS5 and, if an embedding model is
138
- reachable, a vector search over `sqlite-vec`, fused with Reciprocal Rank Fusion on rank *position*
139
- only, never raw scores — a BM25 cost and a vector distance live on unrelated, unbounded scales, and
140
- position is the only thing they agree on.
141
-
142
- Ranking then multiplies three factors:
143
-
144
- ```
145
- score = relevance × signal^0.215 × recency^0.288
146
- ```
147
-
148
- `relevance` comes from the query. `signal` (a `fix:` commit outranks a `chore:`; a failed command
149
- outranks a successful one) and `recency` are priors that hold before any query exists. Each factor is
150
- floored into `[floor, 1]` rather than `[0, 1]`, so one weak dimension can't zero out a strong match.
151
-
152
- The exponents bound how far signal and recency, *together*, may overturn relevance: at most a 2× gap
153
- across their whole range, applied jointly rather than per-prior. That's deliberate — the score
154
- *multiplies* the two priors, so capping each at 2× separately still let the pair overturn 4×, and
155
- that hit hardest on fresh, high-signal commits made during an active working day. The bug that
156
- exposed this: two unrelated same-day `fix:` commits outranked the docs section that actually answered
157
- the query. See [`retrieval/rank.ts`](src/retrieval/rank.ts) for the full derivation.
158
-
159
- Without Ollama, vector search is skipped and you get BM25 only — fully supported, not a degraded
160
- state; `sync` and `query` both succeed and simply do less.
161
-
162
- ## Session summaries (optional, local model)
163
-
164
- With `sources.session.enabled`, each finished session becomes one distilled node next to the raw
165
- exchanges — what was decided and why, rather than forty individual turns. It runs a local Ollama
166
- chat model (`qwen2.5:3b` by default); nothing is downloaded automatically and nothing leaves the
167
- machine.
168
-
169
- ```bash
170
- nexusmem scan-session --dry-run
171
- ```
172
-
173
- That prints the exact prompt a session would produce, after redaction and budget trimming, without
174
- calling the model.
175
-
176
- Three things bound the cost. A session is only summarized once it has been quiet for
177
- `settleMinutes` (default 30), so a session in progress is not re-summarized on every sync. The
178
- prompt is hashed, and an unchanged hash skips the model entirely — on this repo a steady-state sync
179
- of 14 summarized sessions takes 0.25s and makes no model calls. And `maxSessions` (default 10) caps
180
- how many reach the model per run; the rest are reported as queued and picked up next sync.
181
-
182
- **What it is actually like, measured on 14 real sessions with `qwen2.5:3b`.** The summaries
183
- themselves are good: decisions with their reasons, in the shape the prompt asks for. Titles are less
184
- reliable — the model returned a usable one about a third of the time, and otherwise produced a
185
- conversational preamble, a stray bullet, or a bare "Summary of the Session". Those are rejected and
186
- the title falls back to the first line of the question that opened the session, which is always
187
- specific even when it is not elegant. Compliance was worst on long sessions and on transcripts not
188
- in English. A larger model (`qwen2.5:7b`) is the lever if the titles matter to you; set
189
- `sources.session.model`.
190
-
191
- ## Use it from an agent
192
-
193
- ```json
194
- {
195
- "mcpServers": {
196
- "nexusmem": {
197
- "command": "npx",
198
- "args": ["-y", "nexusmem", "mcp"]
199
- }
200
- }
201
- }
202
- ```
203
-
204
- Three tools over stdio: `search_memory` returns the packed context block, `sync_project` ingests, and
205
- `get_status` reports what is currently remembered. Each takes an explicit `projectRoot`, because an
206
- MCP tool call carries no shell working directory. `sync_project` runs `init` for you if the
207
- repository has not been set up.
208
-
209
- ## What it costs you
210
-
211
- Two numbers get conflated in tools like this, so they are kept apart here.
212
-
213
- **Packer efficiency** is how much the ranker trims from its own candidate set. On this repository's
214
- corpus it runs 81–84%. It is useful for tuning the ranker and useless as a claim about your bill,
215
- because the baseline is hypothetical: without NexusMem those candidates were never going into your
216
- context window in the first place.
217
-
218
- **End-to-end saving** compares the packed context NexusMem actually sends against reading, in full,
219
- the same files its own ranking identified as relevant to the query. Measured with
220
- [`scripts/benchmark.ts`](scripts/benchmark.ts) (`npm run bench`), which anyone who clones this repo
221
- and points it at a synced corpus can re-run from scratch:
222
-
223
- | Corpus | Commits | Query set | vs. full file content | vs. `git log -p` on those files |
224
- | --- | --- | --- | --- | --- |
225
- | This repo | 62 | 16 real prompts, verbatim from this project's own history | 95% (median 94%) | 98% (median 97%) |
226
- | [`vitejs/vite`](https://github.com/vitejs/vite) | 9,567 | 16, mechanically sampled — see below | 99% (median 98%) | ~100% (median ~100%) — see caveat |
227
-
228
- Both clear the original >70% target ("cut API token spend versus sending full context"), and the vite
229
- run is the first measurement at the scale that target was always described as applying to.
230
-
231
- **Read the methodology before quoting either number — it's a narrower claim than it looks:**
232
-
233
- - **Graded against NexusMem's own ranking**, not an outside answer key: the file set is whichever
234
- files the packed nodes for that query touch. This measures what the pack step saves once retrieval
235
- already picked a candidate set; it doesn't independently verify that set was the right one.
236
- - **Query sets are mechanical, not cherry-picked** (see `scripts/benchmark.ts`): vite's is an even
237
- sample of well-explained `fix`/`feat`/`perf`/`refactor` commits plus rationale-bearing doc headings;
238
- this repo's reuses real historical prompts verbatim, several of which are broad task instructions
239
- rather than narrow questions — part of why its number sits below vite's.
240
- - **`git log -p` baselines can be enormous** — one vite query's baseline hit 7.5M tokens because a
241
- file in its resolved set has that much history. At that scale, "just read the file's history
242
- instead" stops being a viable alternative at all.
243
- - **Supersedes the old ~40% figure**, which was hand-tallied from two hand-picked queries against
244
- this repo alone with an unstated baseline. Not wrong, just underspecified — this replaces it with a
245
- stated method and a script that reproduces it.
246
-
247
- One thing that is not a percentage: shell commands and conversation turns have no cheap `grep`
248
- equivalent. Without something recording them, they are gone, not merely more expensive to find.
249
-
250
- For how these numbers compare to a similar tool's own claims, see
251
- [`docs/competitor-comparison.md`](docs/competitor-comparison.md) (vs. projectmem) and
252
- [`docs/competitor-comparison-yesmem.md`](docs/competitor-comparison-yesmem.md) (vs. YesMem, including
253
- native Windows support vs. its documented WSL2 requirement).
254
-
255
- Latency on a ~530-node corpus, warm, p50 over 10 runs:
256
-
257
- | Operation | |
258
- | --- | --- |
259
- | BM25 retrieval (FTS5) | ~1.1 ms |
260
- | Vector KNN (`sqlite-vec`) | ~3.2 ms |
261
- | Fuse, rank, pack | ~0.6 ms |
262
- | Query embedding (local Ollama) | ~55–77 ms |
263
- | **End-to-end hybrid** | **~56 ms** |
264
-
265
- All the SQLite work totals about 5 ms. The embedding call is the only thing on this path worth
266
- optimizing, and it is somebody else's process.
267
-
268
- ## Staleness & provenance
269
-
270
- Two things a memory layer needs and this one only partly has: a way to tell an observed fact from a
271
- guess, and a way to retire a conclusion once something contradicts it. This section is what exists
272
- and what doesn't.
273
-
274
- Every node carries a `provenance`, a four-tier trust hierarchy set once per collector at ingest
275
- time: `observed` (a commit that landed, a shell command's real exit code) > `authored` (a doc
276
- section — a human's own written claim) > `recorded` (a conversation turn — verbatim, but talk about
277
- events rather than the events) > `derived` (a session summary — a model's distillation). The tier is
278
- shown as a tag on every query result and decays retrieval weight — the lower the trust, the faster a
279
- node fades from ranking as it ages. The ordering is the design claim; the exact decay ratios are
280
- judgment calls, not measured optima.
281
-
282
- ```bash
283
- nexusmem stale
284
- ```
285
-
286
- Lists non-`observed` nodes old enough (45+ days by default) that nothing has confirmed they still
287
- hold — a heuristic on age and provenance, not on content. It writes nothing; you decide which
288
- candidates are actually wrong. Any candidate the SLM has already flagged (see below) is decorated
289
- with its standing `likely superseded by` suggestion — reading those costs nothing, so the plain
290
- command stays instant and offline.
291
-
292
- ```bash
293
- nexusmem mark-stale <oldNodeId> --supersedes <newNodeId>
294
- ```
295
-
296
- Links `newNodeId` as the replacement for `oldNodeId`. The ranker down-weights the old node from then
297
- on (it stays queryable, just usually loses to its replacement) — nothing is deleted, unlike `forget`.
298
-
299
- ```bash
300
- nexusmem stale --check-contradictions
301
- ```
302
-
303
- For each candidate, finds the most similar newer node (local embedding search) and asks a local SLM
304
- (Ollama, `qwen2.5:3b` by default) whether it actually contradicts the older one — real content
305
- comparison, not just age. A match is printed as `likely superseded by <id> <title> -- <reason>`
306
- under the candidate. Every judgment (either verdict) is memoized, so a judged pair is never sent to
307
- the model again; nothing else is written — `supersedes` stays yours to set via `mark-stale`.
308
-
309
- **This also runs automatically during `sync`** — at most 3 new judgments per run (configurable via
310
- the `contradictions` block in `.nexusmem/config.json`; set `autoCheck: false` to turn it off), only
311
- when the embedding provider was reachable anyway, and free on repeat syncs thanks to the
312
- memoization. New and open suggestions show up in the sync summary, `nexusmem status` (a `flagged`
313
- line), and plain `nexusmem stale`.
314
-
315
- **What this doesn't do:** it is one small model's yes/no judgment on one older/newer pair, not a
316
- verified fact — treat a match as a lead to check, not a conclusion. It also only ever compares a
317
- candidate against nodes *found by embedding similarity*; a contradiction from an unrelated-sounding
318
- node would never surface. Comprehensive contradiction detection (not just for the pair the vector
319
- search happens to surface) is still an open problem, and nothing here supersedes a node on its own.
320
-
321
- `provenance` is a separate question from `trust_state`: provenance says where a claim came from,
322
- never whether anyone checked it.
323
-
324
- ```bash
325
- nexusmem review <nodeId> --verify
326
- nexusmem review <nodeId> --reject
327
- ```
328
-
329
- Records your own verdict on one node, independent of the SLM contradiction checker above (which only
330
- ever writes a suggestion, never a verdict). `--reject` down-weights the node in ranking — same
331
- demote-not-delete rule as `mark-stale`, it stays queryable, just usually loses to better matches —
332
- and both verdicts are shown as a `[verified]`/`[rejected]` tag on every query result that returns the
333
- node afterward. `--verify` is a label only; it does not boost ranking. Every node starts `candidate`
334
- (untagged) until reviewed, and a re-sync never overwrites a verdict once one is set.
335
-
336
- ## Where it breaks
337
-
338
- - **Shell history without the hook is unscoped.** Scraped history has no directory context, so it is
339
- attributed to whichever repository you ran `sync` from. Bounded to a tail window, and an
340
- approximation rather than a guarantee.
341
- - **Japanese and Chinese depend on the vector pass.** FTS5's `unicode61` tokenizer splits on
342
- whitespace, so languages without space boundaries get no useful BM25 recall.
343
- - **Rebasing strands nodes.** Rewritten history leaves nodes for unreachable commits. They describe
344
- real events so they are not wrong, but a targeted prune does not exist yet. `sync --rebuild`
345
- forces a clean re-scan.
346
- - **Multi-line PowerShell input is read as separate commands.** A function typed across several lines
347
- at the prompt is not reconstructed.
348
- - **Scrape-fallback ids drift** if the history file is trimmed from the front between syncs.
349
- Installing the hook fixes this.
350
- - **Session-summary titles depend on the model following instructions**, and a 3B model often does
351
- not. The fallback keeps them specific rather than generic, but see the section above for what to
352
- expect.
353
- - **Changing the embedding model re-embeds everything.** Vectors from two models are not comparable
354
- and `nodes_vec` records no per-row provenance, so `sync` drops the lot and rebuilds rather than
355
- ranking across a mixture. It says so when it happens. Nodes are untouched and BM25 keeps working
356
- throughout.
357
- - **Diff indexing is bounded, and deliberately lossy.** A first sync indexes the patches of the most
358
- recent 200 commits (later syncs only walk `cursor..HEAD`); merge commits contribute none, since
359
- their patch exists only in a combined format this parser does not read; and binaries, lockfiles and
360
- build output are skipped so a dependency bump cannot bury the corpus. All of it is still recorded
361
- as a `git_commit` node. A patch longer than `limits.maxBodyChars` is truncated, so the tail of a
362
- very large change is not indexed. The caps live under `sources.diff` in `config.json`.
363
- - **Cross-project recall favours breadth.** Each repository's hits are fused by rank, so a project
364
- whose best match is mediocre still contributes a rank-1 item, and rank 1 is worth the same in
365
- every list. Adding a repository that has little to say about your question still pushes a few of
366
- its results into the budget. Signal, recency and the budget are what hold that in check; there is
367
- no per-project quality weight.
368
- - **The project registry is an index, not a source of truth.** It can point at a database that has
369
- moved or been deleted; those are reported and skipped, never silently pruned, because an
370
- unmounted drive is not a deleted project.
371
- - **Conversation chunking is unevaluated.** Splitting long replies at heading boundaries measurably
372
- helped, but it has never been tested systematically.
373
- - **A chunked node's sibling count in one result is capped, not tuned.** `conversation_turn` and
374
- `doc_section` both split one reply or file into several nodes; at most 2 of them may appear
375
- together in a packed result. Found live: a query for "token" returned 9 of its top 12 hits as
376
- different pieces of one heavily-sectioned reply, crowding out the node that actually answered it.
377
- The cap of 2 is a judgement call, not a measured optimum, same as the ranking priors' budget above.
378
- - **The size of the prior budget is a judgement call, not a measured optimum.** Priors are now
379
- bounded jointly rather than one at a time, which closed a real 4× hole (see the ranking section),
380
- but the 2× budget itself has never been tuned against a labelled relevance set — there isn't one.
381
- It is a defensible constant, not a result. What is measured is the direction: on four real queries
382
- against this repo's own memory, switching to the joint cap moved the section that answered the
383
- question up in three of them (the rationale section for "why BM25 before vector search" went from
384
- rank 4 to rank 1) and displaced no query's correct top hit.
385
- - **`forget` is per-repository, not global.** Its deny-list lives in the one `.nexusmem/memory.db` it
386
- ran against (plus that repo's stale prior identities, same scope `--prune-source` already uses). A
387
- value that leaked into shell history from several repositories needs `forget` run once per repo —
388
- there is no shared, machine-wide deny-list across every project you have synced.
389
- - **A deny-list doesn't survive a clone or restore on its own.** `.nexusmem/` is gitignored by design,
390
- so `deny_list` never travels with `git clone`/`git push` — while git history itself, the thing a
391
- fresh `sync` re-derives from, is fully portable and copied by every clone. A teammate's fresh
392
- checkout, a new machine, or a restored backup starts with zero protection: the forgotten value comes
393
- right back on the first sync. Confirmed live 2026-08-17, not just a theoretical read of the code.
394
- `forget --export <path>` / `forget --import <path>` close this: export writes the active entries to
395
- a plaintext JSON file you move through a channel you control (never git — the file is exactly as
396
- sensitive as the value it holds), and import re-applies them in the new checkout, deleting any
397
- copies that already synced back in. It is deliberately manual, not automatic on every `sync`.
398
-
399
- ## Commands
400
-
401
- `init`, `sync`, `query <text>` (add `--as-of <date>` for a bi-temporal read, see below), `status` (add
402
- `--share` for a plain-text summary worth pasting somewhere), `projects`, `mcp`, `forget <value>`,
403
- `stale` (add `--check-contradictions` for a local-SLM content check, see above), `mark-stale
404
- <nodeId> --supersedes <newNodeId>`, `review <nodeId> --verify|--reject` (record a human verdict on
405
- one node, see above), `precheck` (advisory — warns about staged files with an unresolved past
406
- failure or high recent churn; exits 0 unless `--strict`), `hook install|remove|status` (the
407
- PowerShell exit-code hook), and `hook git install|remove|status` (a git pre-commit hook that runs
408
- `precheck` before each commit).
409
-
410
- There are also seven dry-run previews (`scan-git`, `scan-diff`, `scan-shell`, `scan-docs`,
411
- `scan-conversation`, `scan-session`, `scan-structure`) that write nothing and print what ingestion
412
- *would* produce — nodes and their signal scores for the first six, import-graph edges for
413
- `scan-structure`. That is the intended way to tune scoring against a real repository before
414
- committing to a change. Add `--json` to pipe them somewhere.
415
-
416
- Every command takes `-C <path>` to target another repository. On `sync`, `--conversation` opts the
417
- transcript source in for one run without persisting it, `--no-embed` skips the vector pass,
418
- `--link-failures` builds the failure → fix chains described above, and `--rebuild` drops the
419
- project's nodes and re-ingests from scratch.
420
-
421
- `sync --prune-source <name>` deletes an entire collector source (e.g. `shell:pwsh`); `forget <value>`
422
- is the finer-grained complement — it deletes every node matching one exact string (or `--regex`
423
- pattern) *and* writes a standing deny-list entry so the value can never be re-ingested, even by a
424
- later `sync --rebuild` re-reading the append-only shell-hook log or a full transcript scan. Every
425
- removal leaves a hash-only tombstone, never the forgotten content itself. Both are dry-run by
426
- default; `--yes` confirms. `forget --list` shows active entries; `forget --export <path>` /
427
- `forget --import <path>` carry them to another checkout of the same repo (see the limitation above).
428
- See [`docs/forget-mechanism.md`](docs/forget-mechanism.md) for why this exists.
429
-
430
- ## Recall across projects
431
-
432
- `query --all-projects` searches every repository you have run NexusMem in, not just the current one,
433
- and tags each result with the repository it came from:
434
-
435
- ```
436
- $ nexusmem query --all-projects "why was the retry budget raised"
437
- scope 2 project(s): NexusMem, uploader
438
-
439
- - 2026-08-12 [observed] [uploader] fix: raise the retry budget after the S3 upload timeouts
440
- - 2026-08-12 [observed] [uploader] retry.ts @ 8d0f98b — fix: raise the retry budget after the S3 upload timeouts
441
- @@ -1 +1 @@
442
- -export const RETRY_BUDGET = 3;
443
- +export const RETRY_BUDGET = 5;
444
- - 2026-08-09 [observed] [NexusMem] fix(git): retry a transient failure to spawn git
445
- ```
446
-
447
- ## Bi-temporal reads
448
-
449
- Every node carries two clocks: `ts`, the event's own time ("what happened then"), and `created_at`,
450
- the moment the store actually recorded it ("what did the store hold then") — normally the same
451
- question, but not when a sync runs late, a backfill lands weeks after the events it describes, or a
452
- teammate's clone catches up all at once. `query`/`search_memory` answer the first by default;
453
- `--as-of <date>` switches to the second:
454
-
455
- ```bash
456
- nexusmem query "why does the ranker cap joint priors" --as-of 2026-08-10
457
- ```
458
-
459
- Only nodes recorded at or before that instant are considered, even if the events they describe are
460
- older still. There is no equivalent write — this is a read-time filter over `created_at`, not a
461
- snapshot or a way to query a value that has since changed, since nodes are write-once (see
462
- [Staleness & provenance](#staleness--provenance) for what changes a node's *weight*, not its
463
- record).
464
-
465
- Databases stay per-repository — there is no shared global store, and deleting one repo's
466
- `.nexusmem/` still removes exactly that repo's memory. What makes the others findable is a plain
467
- index at `~/.nexusmem/projects.json`, written by `init` and refreshed by every `sync`. `nexusmem
468
- projects` shows what is in it, and `--prune` forgets entries whose database is gone.
469
-
470
- Ranking across repositories uses reciprocal rank fusion per project rather than raw BM25, because a
471
- BM25 cost is computed against its own corpus and means different things in a 50-node and a
472
- 50,000-node database. The trade is stated in *Where it breaks*.
473
-
474
- The MCP `search_memory` tool takes the same switch as `allProjects: true`.
475
-
476
- ## On disk
477
-
478
- ```
479
- <repo>/.nexusmem/
480
- .gitignore '*' — the workspace ignores itself, so init never edits a file it doesn't own
481
- config.json validated on read; a corrupt config fails loudly rather than silently
482
- memory.db SQLite in WAL mode
483
-
484
- ~/.nexusmem/
485
- projects.json which repositories exist, for cross-project recall; a corrupt one reads as empty
486
- shell-history.jsonl the hook's log, if you installed it
487
- ```
488
-
489
- `NEXUSMEM_HOME` overrides the user-scoped directory.
490
-
491
- Node ids are content-addressed from `sha256(projectId + kind + naturalKey)`, so running `sync` twice
492
- cannot produce duplicates and ingestion stays correct even if a cursor is lost. Project identity
493
- comes from the normalized origin URL when there is one, falling back to the absolute path, so two
494
- clones of the same repo share one memory namespace.
495
-
496
- Deleting `.nexusmem/` loses nothing that `sync` cannot rebuild.
497
-
498
- ## Status
499
-
500
- Ingestion, hybrid retrieval, budgeted packing and the MCP server all work and are covered by 701
501
- tests running on Linux and Windows across Node 22 and 24.
502
-
503
- ## Development
504
-
505
- ```bash
506
- npm install
507
- npm run typecheck
508
- npm test
509
- npm run build
510
- ```
511
-
512
- Tests are behavioral rather than snapshot-based, and several are regressions tied to specific
513
- observed failures. `tests/git-errors.test.ts` injects a fake `spawn` to exercise the Windows
514
- process-spawn faults, which cannot be provoked on demand.
515
-
516
- ## On how this was built
517
-
518
- This started as an experiment in whether a local context-memory engine for coding agents was viable,
519
- prototyped with Claude Code. The code was written through AI-assisted workflows; the architecture,
520
- the design decisions and the specifications were human-directed.
521
-
522
- That is worth stating plainly because it should change how you read the code, not whether you trust
523
- it. Audits, corrections and PRs are genuinely welcome, and the commit history is deliberately
524
- detailed about *why* things are the way they are, including the times an earlier assumption turned
525
- out to be wrong.
526
-
527
- ## License
528
-
529
- MIT
1
+ # NexusMem
2
+
3
+ [![CI](https://github.com/yaminbkk/NexusMem/actions/workflows/ci.yml/badge.svg)](https://github.com/yaminbkk/NexusMem/actions/workflows/ci.yml)
4
+ [![npm](https://img.shields.io/npm/v/nexusmem)](https://www.npmjs.com/package/nexusmem)
5
+ [![npm downloads](https://img.shields.io/npm/dm/nexusmem)](https://www.npmjs.com/package/nexusmem)
6
+ [![License: MIT](https://img.shields.io/badge/license-MIT-informational)](LICENSE)
7
+ ![Node](https://img.shields.io/badge/node-%3E%3D22-brightgreen)
8
+
9
+ ![NexusMem: init, sync, status, and a query against this repo's own history](docs/demo.gif)
10
+
11
+ Your coding agent can read `git log`. It cannot read the four things you tried last Tuesday that
12
+ didn't work.
13
+
14
+ NexusMem records what actually happened on your machine (shell commands and their exit codes, git
15
+ history down to the patch of each changed file, project docs, optionally your assistant transcripts)
16
+ into a local SQLite database, and
17
+ serves back a ranked, token-budgeted slice of it on demand. Everything stays on disk. No account, no
18
+ cloud, no telemetry.
19
+
20
+ The shell history is the part worth caring about. Git tells an agent what shipped. Shell history
21
+ tells it what was attempted, in what order, and which commands exited non-zero. That information
22
+ exists nowhere else, and it disappears when your terminal scrollback rolls over.
23
+
24
+ **Contents:** [Try it](#try-it) · [Exact shell capture](#optional-exact-shell-capture) ·
25
+ [Failure → fix chains](#failure--fix-chains-opt-in) · [How retrieval works](#how-retrieval-works) ·
26
+ [Session summaries](#session-summaries-optional-local-model) ·
27
+ [GitHub issues & PRs](#github-issues--prs-optional) · [Use it from an agent](#use-it-from-an-agent)
28
+ · [What it costs you](#what-it-costs-you) · [Staleness & provenance](#staleness--provenance) ·
29
+ [Where it breaks](#where-it-breaks) · [Commands](#commands) · [Cross-project recall](#recall-across-projects)
30
+ · [On disk](#on-disk) · [Development](#development)
31
+
32
+ ## Try it
33
+
34
+ From inside any git repository:
35
+
36
+ ```
37
+ npx nexusmem init
38
+ npx nexusmem sync
39
+ ```
40
+
41
+ Then ask it something. Real output from this repository, top 2 of 5 hits:
42
+
43
+ ```
44
+ $ nexusmem query "windows spawn failure"
45
+
46
+ Relevant history for: windows spawn failure
47
+
48
+ - 2026-08-09 [observed] fix: distinguish a failed git spawn from "not a git repository"
49
+ readRepoInfo collapsed three unrelated failures into one error: git running and reporting
50
+ the path is not a work tree, git not being installed, and the process failing to spawn at
51
+ all. Dogfooding hit the third case in two separate sessions...
52
+ - 2026-08-09 [authored] README.md — Before a tagged release
53
+ - [ ] Retry on transient process-spawn failures on Windows
54
+ ```
55
+
56
+ `[observed]`/`[authored]` is the provenance tag (see [Staleness & provenance](#staleness--provenance))
57
+ — a commit is a directly observed event, a doc section is a written claim that could go stale.
58
+
59
+ A commit and a docs section, ranked against each other, inside whatever token budget you gave it.
60
+ Nothing was summarized by a model on the way out; the ranker just decided what not to send. (One
61
+ optional source, session summaries, does run a local model — but at ingest time, never on the way
62
+ out. What you query is always stored text.)
63
+
64
+ For a sense of what actually accumulates, here is `nexusmem status` on this repo after two days:
65
+
66
+ ```
67
+ 527 node(s) 2026-08-08 .. 2026-08-09
68
+ 321 shell_command
69
+ 130 conversation_turn
70
+ 60 doc_section
71
+ 16 git_commit
72
+ ```
73
+
74
+ Sixteen commits. Three hundred and twenty-one shell commands. The commits were already retrievable
75
+ by any agent with a terminal. The rest was not.
76
+
77
+ That `conversation_turn` row only appears because this corpus was synced with `--conversation`.
78
+ Assistant transcripts are the one source that is off by default and stays off until you opt in, since
79
+ they are the likeliest place for a pasted credential to be sitting. A default install indexes git
80
+ commits, their diffs, shell and docs.
81
+
82
+ Requirements: Node 22 or newer, and git. Node 20 will not work, because `better-sqlite3` ships no
83
+ prebuilt binary for it and Node 20 went end-of-life in April 2026. Ollama is optional and only
84
+ affects semantic search (see below).
85
+
86
+ ## Optional: exact shell capture
87
+
88
+ Scraped history files (PSReadLine, `.bash_history`, `.zsh_history`) give you command text and not
89
+ much else. The hook gives you working directory, exit code and a real timestamp:
90
+
91
+ ```bash
92
+ nexusmem hook install
93
+ ```
94
+
95
+ It wraps your existing PowerShell prompt rather than replacing it, is idempotent, and
96
+ `nexusmem hook remove` undoes it cleanly.
97
+
98
+ Exit codes are what make this worth installing. A failed command is a stronger signal than a
99
+ successful one, and without the hook there is no way to tell them apart.
100
+
101
+ ## Failure → fix chains (opt-in)
102
+
103
+ ```bash
104
+ nexusmem sync --link-failures
105
+ ```
106
+
107
+ After a normal sync, this walks every failed `shell_command` (non-zero exit code) and looks for
108
+ whatever later resolved it, using two independent heuristics: a later command in the same project
109
+ and working directory, exact same normalized text, that exited `0` within 24h (**same-command
110
+ retry**); and, separately, the best full-text match among nearby conversation turns or session
111
+ summaries, requiring every significant word of the failing command to appear, not just one
112
+ (**conversation bridge**). A failure can be linked by either, both, or neither.
113
+
114
+ Both links are surfaced in query results. The conversation-bridge heuristic originally matched on
115
+ any shared word, and dogfooding against this repo's own real history found it wrong on roughly half
116
+ its links — a shared word as generic as "npm" was enough to link an unrelated discussion. Requiring
117
+ every significant word fixed that: re-dogfooded against the same corpus, every resulting link (the
118
+ full set produced, not a sample) checked out correct on manual review of the full text, not just the
119
+ summary.
120
+
121
+ When a linked failure appears in a result set, its fix rides along immediately after it, inheriting
122
+ the failure's own relevance score rather than needing to match the query on its own merits. That is
123
+ the point: a query about why something failed shouldn't need to separately guess the words used in
124
+ whatever fixed it. This works across projects too — `query --all-projects` chains a failure to its
125
+ fix using whichever project's own database recorded the link, since links are always local to the
126
+ project they were found in.
127
+
128
+ ```
129
+ $ nexusmem query "why did npm whoami fail"
130
+
131
+ - 2026-08-12 [observed] shell: npm whoami (exit 1)
132
+ - 2026-08-12 [observed] shell: npm login (exit 0) -- linked as the fix
133
+ ```
134
+
135
+ ## How retrieval works
136
+
137
+ Every source normalizes to the same `MemoryNode` shape, so a commit, a shell command and a docs
138
+ section compete on equal terms. Retrieval runs BM25 over FTS5 and, if an embedding model is
139
+ reachable, a vector search over `sqlite-vec`, fused with Reciprocal Rank Fusion on rank *position*
140
+ only, never raw scores — a BM25 cost and a vector distance live on unrelated, unbounded scales, and
141
+ position is the only thing they agree on.
142
+
143
+ Ranking then multiplies three factors:
144
+
145
+ ```
146
+ score = relevance × signal^0.215 × recency^0.288
147
+ ```
148
+
149
+ `relevance` comes from the query. `signal` (a `fix:` commit outranks a `chore:`; a failed command
150
+ outranks a successful one) and `recency` are priors that hold before any query exists. Each factor is
151
+ floored into `[floor, 1]` rather than `[0, 1]`, so one weak dimension can't zero out a strong match.
152
+
153
+ The exponents bound how far signal and recency, *together*, may overturn relevance: at most a 2× gap
154
+ across their whole range, applied jointly rather than per-prior. That's deliberate — the score
155
+ *multiplies* the two priors, so capping each at 2× separately still let the pair overturn 4×, and
156
+ that hit hardest on fresh, high-signal commits made during an active working day. The bug that
157
+ exposed this: two unrelated same-day `fix:` commits outranked the docs section that actually answered
158
+ the query. See [`retrieval/rank.ts`](src/retrieval/rank.ts) for the full derivation.
159
+
160
+ Without Ollama, vector search is skipped and you get BM25 only — fully supported, not a degraded
161
+ state; `sync` and `query` both succeed and simply do less.
162
+
163
+ ## Session summaries (optional, local model)
164
+
165
+ With `sources.session.enabled`, each finished session becomes one distilled node next to the raw
166
+ exchanges — what was decided and why, rather than forty individual turns. It runs a local Ollama
167
+ chat model (`qwen2.5:3b` by default); nothing is downloaded automatically and nothing leaves the
168
+ machine.
169
+
170
+ ```bash
171
+ nexusmem scan-session --dry-run
172
+ ```
173
+
174
+ That prints the exact prompt a session would produce, after redaction and budget trimming, without
175
+ calling the model.
176
+
177
+ Three things bound the cost. A session is only summarized once it has been quiet for
178
+ `settleMinutes` (default 30), so a session in progress is not re-summarized on every sync. The
179
+ prompt is hashed, and an unchanged hash skips the model entirely — on this repo a steady-state sync
180
+ of 14 summarized sessions takes 0.25s and makes no model calls. And `maxSessions` (default 10) caps
181
+ how many reach the model per run; the rest are reported as queued and picked up next sync.
182
+
183
+ **What it is actually like, measured on 14 real sessions with `qwen2.5:3b`.** The summaries
184
+ themselves are good: decisions with their reasons, in the shape the prompt asks for. Titles are less
185
+ reliable — the model returned a usable one about a third of the time, and otherwise produced a
186
+ conversational preamble, a stray bullet, or a bare "Summary of the Session". Those are rejected and
187
+ the title falls back to the first line of the question that opened the session, which is always
188
+ specific even when it is not elegant. Compliance was worst on long sessions and on transcripts not
189
+ in English. A larger model (`qwen2.5:7b`) is the lever if the titles matter to you; set
190
+ `sources.session.model`.
191
+
192
+ ## GitHub issues & PRs (optional)
193
+
194
+ With `sources.github.enabled`, each issue and PR on this repo's github.com remote becomes one node
195
+ (title, opening post and every comment, folded together) alongside the raw discourse a discussion
196
+ already leaves in shell/conversation history. Off by default — not for a sensitivity reason, but
197
+ because it's the first source with a real external dependency: it reads via the `gh` CLI, so it
198
+ needs `gh` installed and authenticated (`gh auth login`), and it makes live network calls instead of
199
+ only reading what's already on disk. A repo with no github.com remote, or an unauthenticated `gh`,
200
+ is a silent no-op either way.
201
+
202
+ ```bash
203
+ nexusmem scan-github
204
+ ```
205
+
206
+ previews the nodes a sync would produce, same as the other `scan-*` commands. `maxThreads` (default
207
+ 100) and `maxCommentsPerThread` (default 100) bound one sync's cost; `since` is tracked as its own
208
+ cursor, so a repeat sync only re-reads threads that changed. Dogfooded against this repo's own 14
209
+ real issues/PRs: ingest took under a second, and a query for "labelled retrieval regression corpus"
210
+ correctly ranked issue #8 — the one that asked for it — first.
211
+
212
+ ## Use it from an agent
213
+
214
+ ```json
215
+ {
216
+ "mcpServers": {
217
+ "nexusmem": {
218
+ "command": "npx",
219
+ "args": ["-y", "nexusmem", "mcp"]
220
+ }
221
+ }
222
+ }
223
+ ```
224
+
225
+ Three tools over stdio: `search_memory` returns the packed context block, `sync_project` ingests, and
226
+ `get_status` reports what is currently remembered. Each takes an explicit `projectRoot`, because an
227
+ MCP tool call carries no shell working directory. `sync_project` runs `init` for you if the
228
+ repository has not been set up.
229
+
230
+ ## What it costs you
231
+
232
+ Two numbers get conflated in tools like this, so they are kept apart here.
233
+
234
+ **Packer efficiency** is how much the ranker trims from its own candidate set. On this repository's
235
+ corpus it runs 81–84%. It is useful for tuning the ranker and useless as a claim about your bill,
236
+ because the baseline is hypothetical: without NexusMem those candidates were never going into your
237
+ context window in the first place.
238
+
239
+ **End-to-end saving** compares the packed context NexusMem actually sends against reading, in full,
240
+ the same files its own ranking identified as relevant to the query. Measured with
241
+ [`scripts/benchmark.ts`](scripts/benchmark.ts) (`npm run bench`), which anyone who clones this repo
242
+ and points it at a synced corpus can re-run from scratch:
243
+
244
+ | Corpus | Commits | Query set | vs. full file content | vs. `git log -p` on those files |
245
+ | --- | --- | --- | --- | --- |
246
+ | This repo | 62 | 16 real prompts, verbatim from this project's own history | 95% (median 94%) | 98% (median 97%) |
247
+ | [`vitejs/vite`](https://github.com/vitejs/vite) | 9,567 | 16, mechanically sampled — see below | 99% (median 98%) | ~100% (median ~100%) — see caveat |
248
+
249
+ Both clear the original >70% target ("cut API token spend versus sending full context"), and the vite
250
+ run is the first measurement at the scale that target was always described as applying to.
251
+
252
+ **Read the methodology before quoting either number — it's a narrower claim than it looks:**
253
+
254
+ - **Graded against NexusMem's own ranking**, not an outside answer key: the file set is whichever
255
+ files the packed nodes for that query touch. This measures what the pack step saves once retrieval
256
+ already picked a candidate set; it doesn't independently verify that set was the right one.
257
+ - **Query sets are mechanical, not cherry-picked** (see `scripts/benchmark.ts`): vite's is an even
258
+ sample of well-explained `fix`/`feat`/`perf`/`refactor` commits plus rationale-bearing doc headings;
259
+ this repo's reuses real historical prompts verbatim, several of which are broad task instructions
260
+ rather than narrow questions — part of why its number sits below vite's.
261
+ - **`git log -p` baselines can be enormous** — one vite query's baseline hit 7.5M tokens because a
262
+ file in its resolved set has that much history. At that scale, "just read the file's history
263
+ instead" stops being a viable alternative at all.
264
+ - **Supersedes the old ~40% figure**, which was hand-tallied from two hand-picked queries against
265
+ this repo alone with an unstated baseline. Not wrong, just underspecified — this replaces it with a
266
+ stated method and a script that reproduces it.
267
+
268
+ One thing that is not a percentage: shell commands and conversation turns have no cheap `grep`
269
+ equivalent. Without something recording them, they are gone, not merely more expensive to find.
270
+
271
+ For how these numbers compare to a similar tool's own claims, see
272
+ [`docs/competitor-comparison.md`](docs/competitor-comparison.md) (vs. projectmem) and
273
+ [`docs/competitor-comparison-yesmem.md`](docs/competitor-comparison-yesmem.md) (vs. YesMem, including
274
+ native Windows support vs. its documented WSL2 requirement).
275
+
276
+ Latency on a ~530-node corpus, warm, p50 over 10 runs:
277
+
278
+ | Operation | |
279
+ | --- | --- |
280
+ | BM25 retrieval (FTS5) | ~1.1 ms |
281
+ | Vector KNN (`sqlite-vec`) | ~3.2 ms |
282
+ | Fuse, rank, pack | ~0.6 ms |
283
+ | Query embedding (local Ollama) | ~55–77 ms |
284
+ | **End-to-end hybrid** | **~56 ms** |
285
+
286
+ All the SQLite work totals about 5 ms. The embedding call is the only thing on this path worth
287
+ optimizing, and it is somebody else's process.
288
+
289
+ ## Staleness & provenance
290
+
291
+ Two things a memory layer needs and this one only partly has: a way to tell an observed fact from a
292
+ guess, and a way to retire a conclusion once something contradicts it. This section is what exists
293
+ and what doesn't.
294
+
295
+ Every node carries a `provenance`, a four-tier trust hierarchy set once per collector at ingest
296
+ time: `observed` (a commit that landed, a shell command's real exit code) > `authored` (a doc
297
+ section — a human's own written claim) > `recorded` (a conversation turn — verbatim, but talk about
298
+ events rather than the events) > `derived` (a session summary — a model's distillation). The tier is
299
+ shown as a tag on every query result and decays retrieval weight — the lower the trust, the faster a
300
+ node fades from ranking as it ages. The ordering is the design claim; the exact decay ratios are
301
+ judgment calls, not measured optima.
302
+
303
+ ```bash
304
+ nexusmem stale
305
+ ```
306
+
307
+ Lists non-`observed` nodes old enough (45+ days by default) that nothing has confirmed they still
308
+ hold — a heuristic on age and provenance, not on content. It writes nothing; you decide which
309
+ candidates are actually wrong. Any candidate the SLM has already flagged (see below) is decorated
310
+ with its standing `likely superseded by` suggestion — reading those costs nothing, so the plain
311
+ command stays instant and offline.
312
+
313
+ ```bash
314
+ nexusmem mark-stale <oldNodeId> --supersedes <newNodeId>
315
+ ```
316
+
317
+ Links `newNodeId` as the replacement for `oldNodeId`. The ranker down-weights the old node from then
318
+ on (it stays queryable, just usually loses to its replacement) — nothing is deleted, unlike `forget`.
319
+
320
+ ```bash
321
+ nexusmem stale --check-contradictions
322
+ ```
323
+
324
+ For each candidate, finds the most similar newer node (local embedding search) and asks a local SLM
325
+ (Ollama, `qwen2.5:3b` by default) whether it actually contradicts the older one — real content
326
+ comparison, not just age. A match is printed as `likely superseded by <id> <title> -- <reason>`
327
+ under the candidate. Every judgment (either verdict) is memoized, so a judged pair is never sent to
328
+ the model again; nothing else is written — `supersedes` stays yours to set via `mark-stale`.
329
+
330
+ **This also runs automatically during `sync`** — at most 3 new judgments per run (configurable via
331
+ the `contradictions` block in `.nexusmem/config.json`; set `autoCheck: false` to turn it off), only
332
+ when the embedding provider was reachable anyway, and free on repeat syncs thanks to the
333
+ memoization. New and open suggestions show up in the sync summary, `nexusmem status` (a `flagged`
334
+ line), and plain `nexusmem stale`.
335
+
336
+ **What this doesn't do:** it is one small model's yes/no judgment on one older/newer pair, not a
337
+ verified fact — treat a match as a lead to check, not a conclusion. It also only ever compares a
338
+ candidate against nodes *found by embedding similarity*; a contradiction from an unrelated-sounding
339
+ node would never surface. Comprehensive contradiction detection (not just for the pair the vector
340
+ search happens to surface) is still an open problem, and nothing here supersedes a node on its own.
341
+
342
+ `provenance` is a separate question from `trust_state`: provenance says where a claim came from,
343
+ never whether anyone checked it.
344
+
345
+ ```bash
346
+ nexusmem review <nodeId> --verify
347
+ nexusmem review <nodeId> --reject
348
+ ```
349
+
350
+ Records your own verdict on one node, independent of the SLM contradiction checker above (which only
351
+ ever writes a suggestion, never a verdict). `--reject` down-weights the node in ranking — same
352
+ demote-not-delete rule as `mark-stale`, it stays queryable, just usually loses to better matches —
353
+ and both verdicts are shown as a `[verified]`/`[rejected]` tag on every query result that returns the
354
+ node afterward. `--verify` is a label only; it does not boost ranking. Every node starts `candidate`
355
+ (untagged) until reviewed, and a re-sync never overwrites a verdict once one is set.
356
+
357
+ ## Where it breaks
358
+
359
+ - **Shell history without the hook is unscoped.** Scraped history has no directory context, so it is
360
+ attributed to whichever repository you ran `sync` from. Bounded to a tail window, and an
361
+ approximation rather than a guarantee.
362
+ - **Japanese and Chinese depend on the vector pass.** FTS5's `unicode61` tokenizer splits on
363
+ whitespace, so languages without space boundaries get no useful BM25 recall.
364
+ - **Rebasing strands nodes.** Rewritten history leaves nodes for unreachable commits. They describe
365
+ real events so they are not wrong, but a targeted prune does not exist yet. `sync --rebuild`
366
+ forces a clean re-scan.
367
+ - **Multi-line PowerShell input is read as separate commands.** A function typed across several lines
368
+ at the prompt is not reconstructed.
369
+ - **Scrape-fallback ids drift** if the history file is trimmed from the front between syncs.
370
+ Installing the hook fixes this.
371
+ - **Session-summary titles depend on the model following instructions**, and a 3B model often does
372
+ not. The fallback keeps them specific rather than generic, but see the section above for what to
373
+ expect.
374
+ - **Changing the embedding model re-embeds everything.** Vectors from two models are not comparable
375
+ and `nodes_vec` records no per-row provenance, so `sync` drops the lot and rebuilds rather than
376
+ ranking across a mixture. It says so when it happens. Nodes are untouched and BM25 keeps working
377
+ throughout.
378
+ - **Diff indexing is bounded, and deliberately lossy.** A first sync indexes the patches of the most
379
+ recent 200 commits (later syncs only walk `cursor..HEAD`); merge commits contribute none, since
380
+ their patch exists only in a combined format this parser does not read; and binaries, lockfiles and
381
+ build output are skipped so a dependency bump cannot bury the corpus. All of it is still recorded
382
+ as a `git_commit` node. A patch longer than `limits.maxBodyChars` is truncated, so the tail of a
383
+ very large change is not indexed. The caps live under `sources.diff` in `config.json`.
384
+ - **Cross-project recall favours breadth.** Each repository's hits are fused by rank, so a project
385
+ whose best match is mediocre still contributes a rank-1 item, and rank 1 is worth the same in
386
+ every list. Adding a repository that has little to say about your question still pushes a few of
387
+ its results into the budget. Signal, recency and the budget are what hold that in check; there is
388
+ no per-project quality weight.
389
+ - **The project registry is an index, not a source of truth.** It can point at a database that has
390
+ moved or been deleted; those are reported and skipped, never silently pruned, because an
391
+ unmounted drive is not a deleted project.
392
+ - **Conversation chunking is unevaluated.** Splitting long replies at heading boundaries measurably
393
+ helped, but it has never been tested systematically.
394
+ - **A chunked node's sibling count in one result is capped, not tuned.** `conversation_turn` and
395
+ `doc_section` both split one reply or file into several nodes; at most 2 of them may appear
396
+ together in a packed result. Found live: a query for "token" returned 9 of its top 12 hits as
397
+ different pieces of one heavily-sectioned reply, crowding out the node that actually answered it.
398
+ The cap of 2 is a judgement call, not a measured optimum, same as the ranking priors' budget above.
399
+ - **The size of the prior budget is a judgement call, not a measured optimum.** Priors are now
400
+ bounded jointly rather than one at a time, which closed a real 4× hole (see the ranking section),
401
+ but the 2× budget itself has never been tuned against a labelled relevance set — there isn't one.
402
+ It is a defensible constant, not a result. What is measured is the direction: on four real queries
403
+ against this repo's own memory, switching to the joint cap moved the section that answered the
404
+ question up in three of them (the rationale section for "why BM25 before vector search" went from
405
+ rank 4 to rank 1) and displaced no query's correct top hit.
406
+ - **`forget` is per-repository, not global.** Its deny-list lives in the one `.nexusmem/memory.db` it
407
+ ran against (plus that repo's stale prior identities, same scope `--prune-source` already uses). A
408
+ value that leaked into shell history from several repositories needs `forget` run once per repo —
409
+ there is no shared, machine-wide deny-list across every project you have synced.
410
+ - **A deny-list doesn't survive a clone or restore on its own.** `.nexusmem/` is gitignored by design,
411
+ so `deny_list` never travels with `git clone`/`git push` — while git history itself, the thing a
412
+ fresh `sync` re-derives from, is fully portable and copied by every clone. A teammate's fresh
413
+ checkout, a new machine, or a restored backup starts with zero protection: the forgotten value comes
414
+ right back on the first sync. Confirmed live 2026-08-17, not just a theoretical read of the code.
415
+ `forget --export <path>` / `forget --import <path>` close this: export writes the active entries to
416
+ a plaintext JSON file you move through a channel you control (never git — the file is exactly as
417
+ sensitive as the value it holds), and import re-applies them in the new checkout, deleting any
418
+ copies that already synced back in. It is deliberately manual, not automatic on every `sync`.
419
+
420
+ ## Commands
421
+
422
+ `init`, `sync`, `query <text>` (add `--as-of <date>` for a bi-temporal read, see below), `status` (add
423
+ `--share` for a plain-text summary worth pasting somewhere), `projects`, `mcp`, `forget <value>`,
424
+ `stale` (add `--check-contradictions` for a local-SLM content check, see above), `mark-stale
425
+ <nodeId> --supersedes <newNodeId>`, `review <nodeId> --verify|--reject` (record a human verdict on
426
+ one node, see above), `precheck` (advisory — warns about staged files with an unresolved past
427
+ failure or high recent churn; exits 0 unless `--strict`), `hook install|remove|status` (the
428
+ PowerShell exit-code hook), and `hook git install|remove|status` (a git pre-commit hook that runs
429
+ `precheck` before each commit).
430
+
431
+ There are also eight dry-run previews (`scan-git`, `scan-diff`, `scan-shell`, `scan-docs`,
432
+ `scan-conversation`, `scan-session`, `scan-github`, `scan-structure`) that write nothing and print
433
+ what ingestion *would* produce — nodes and their signal scores for the first seven, import-graph
434
+ edges for `scan-structure`. That is the intended way to tune scoring against a real repository
435
+ before committing to a change. Add `--json` to pipe them somewhere.
436
+
437
+ Every command takes `-C <path>` to target another repository. On `sync`, `--conversation` and
438
+ `--github` opt their (opt-in) sources in for one run without persisting it, `--no-embed` skips the
439
+ vector pass, `--link-failures` builds the failure → fix chains described above, and `--rebuild`
440
+ drops the project's nodes and re-ingests from scratch.
441
+
442
+ `sync --prune-source <name>` deletes an entire collector source (e.g. `shell:pwsh`); `forget <value>`
443
+ is the finer-grained complement — it deletes every node matching one exact string (or `--regex`
444
+ pattern) *and* writes a standing deny-list entry so the value can never be re-ingested, even by a
445
+ later `sync --rebuild` re-reading the append-only shell-hook log or a full transcript scan. Every
446
+ removal leaves a hash-only tombstone, never the forgotten content itself. Both are dry-run by
447
+ default; `--yes` confirms. `forget --list` shows active entries; `forget --export <path>` /
448
+ `forget --import <path>` carry them to another checkout of the same repo (see the limitation above).
449
+ See [`docs/forget-mechanism.md`](docs/forget-mechanism.md) for why this exists.
450
+
451
+ ## Recall across projects
452
+
453
+ `query --all-projects` searches every repository you have run NexusMem in, not just the current one,
454
+ and tags each result with the repository it came from:
455
+
456
+ ```
457
+ $ nexusmem query --all-projects "why was the retry budget raised"
458
+ scope 2 project(s): NexusMem, uploader
459
+
460
+ - 2026-08-12 [observed] [uploader] fix: raise the retry budget after the S3 upload timeouts
461
+ - 2026-08-12 [observed] [uploader] retry.ts @ 8d0f98b — fix: raise the retry budget after the S3 upload timeouts
462
+ @@ -1 +1 @@
463
+ -export const RETRY_BUDGET = 3;
464
+ +export const RETRY_BUDGET = 5;
465
+ - 2026-08-09 [observed] [NexusMem] fix(git): retry a transient failure to spawn git
466
+ ```
467
+
468
+ ## Bi-temporal reads
469
+
470
+ Every node carries two clocks: `ts`, the event's own time ("what happened then"), and `created_at`,
471
+ the moment the store actually recorded it ("what did the store hold then") — normally the same
472
+ question, but not when a sync runs late, a backfill lands weeks after the events it describes, or a
473
+ teammate's clone catches up all at once. `query`/`search_memory` answer the first by default;
474
+ `--as-of <date>` switches to the second:
475
+
476
+ ```bash
477
+ nexusmem query "why does the ranker cap joint priors" --as-of 2026-08-10
478
+ ```
479
+
480
+ Only nodes recorded at or before that instant are considered, even if the events they describe are
481
+ older still. There is no equivalent write — this is a read-time filter over `created_at`, not a
482
+ snapshot or a way to query a value that has since changed, since nodes are write-once (see
483
+ [Staleness & provenance](#staleness--provenance) for what changes a node's *weight*, not its
484
+ record).
485
+
486
+ Databases stay per-repository — there is no shared global store, and deleting one repo's
487
+ `.nexusmem/` still removes exactly that repo's memory. What makes the others findable is a plain
488
+ index at `~/.nexusmem/projects.json`, written by `init` and refreshed by every `sync`. `nexusmem
489
+ projects` shows what is in it, and `--prune` forgets entries whose database is gone.
490
+
491
+ Ranking across repositories uses reciprocal rank fusion per project rather than raw BM25, because a
492
+ BM25 cost is computed against its own corpus and means different things in a 50-node and a
493
+ 50,000-node database. The trade is stated in *Where it breaks*.
494
+
495
+ The MCP `search_memory` tool takes the same switch as `allProjects: true`.
496
+
497
+ ## On disk
498
+
499
+ ```
500
+ <repo>/.nexusmem/
501
+ .gitignore '*' — the workspace ignores itself, so init never edits a file it doesn't own
502
+ config.json validated on read; a corrupt config fails loudly rather than silently
503
+ memory.db SQLite in WAL mode
504
+
505
+ ~/.nexusmem/
506
+ projects.json which repositories exist, for cross-project recall; a corrupt one reads as empty
507
+ shell-history.jsonl the hook's log, if you installed it
508
+ ```
509
+
510
+ `NEXUSMEM_HOME` overrides the user-scoped directory.
511
+
512
+ Node ids are content-addressed from `sha256(projectId + kind + naturalKey)`, so running `sync` twice
513
+ cannot produce duplicates and ingestion stays correct even if a cursor is lost. Project identity
514
+ comes from the normalized origin URL when there is one, falling back to the absolute path, so two
515
+ clones of the same repo share one memory namespace.
516
+
517
+ Deleting `.nexusmem/` loses nothing that `sync` cannot rebuild.
518
+
519
+ ## Status
520
+
521
+ Ingestion, hybrid retrieval, budgeted packing and the MCP server all work and are covered by 701
522
+ tests running on Linux and Windows across Node 22 and 24.
523
+
524
+ ## Development
525
+
526
+ ```bash
527
+ npm install
528
+ npm run typecheck
529
+ npm test
530
+ npm run build
531
+ ```
532
+
533
+ Tests are behavioral rather than snapshot-based, and several are regressions tied to specific
534
+ observed failures. `tests/git-errors.test.ts` injects a fake `spawn` to exercise the Windows
535
+ process-spawn faults, which cannot be provoked on demand.
536
+
537
+ ## On how this was built
538
+
539
+ This started as an experiment in whether a local context-memory engine for coding agents was viable,
540
+ prototyped with Claude Code. The code was written through AI-assisted workflows; the architecture,
541
+ the design decisions and the specifications were human-directed.
542
+
543
+ That is worth stating plainly because it should change how you read the code, not whether you trust
544
+ it. Audits, corrections and PRs are genuinely welcome, and the commit history is deliberately
545
+ detailed about *why* things are the way they are, including the times an earlier assumption turned
546
+ out to be wrong.
547
+
548
+ ## License
549
+
550
+ MIT