nexusmem 0.10.2 → 0.10.3

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