claude-mem-lite 6.30.15 → 6.32.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.
@@ -9,7 +9,7 @@
9
9
  "plugins": [
10
10
  {
11
11
  "name": "claude-mem-lite",
12
- "version": "6.30.15",
12
+ "version": "6.32.0",
13
13
  "source": "./",
14
14
  "homepage": "https://github.com/sdsrss/claude-mem-lite",
15
15
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. FTS5 BM25 keyword search with episode batching. Single SQLite DB, no external services. A lighter, lower-cost alternative to claude-mem (episode batching + a smaller model; cost savings are an internal estimate, not a measured benchmark)."
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "6.30.15",
3
+ "version": "6.32.0",
4
4
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. FTS5 BM25 keyword search with episode batching. Single SQLite DB, no external services. A lighter, lower-cost alternative to claude-mem (episode batching + a smaller model; cost savings are an internal estimate, not a measured benchmark).",
5
5
  "author": {
6
6
  "name": "sdsrss"
package/README.md CHANGED
@@ -167,9 +167,9 @@ Plugin mode manages its own hooks/runtime. On session start it only **checks and
167
167
 
168
168
  > **The plugin install is complete on its own** — hooks, MCP tools, and the bundled slash commands (`/mem`, `/lesson`, `/claude-mem-lite:bug`, `/adopt`) all run from the plugin with no second step. The slash commands invoke the bundled CLI by an absolute path resolved from the plugin directory (`node "${CLAUDE_PLUGIN_ROOT}/cli.mjs" <cmd>`), so they work without anything on your `PATH`. A global `claude-mem-lite` **shell** command (for running queries yourself in a terminal) is **optional** — `npm i -g claude-mem-lite` — and is a *separate* npm install: the plugin's auto-update does **not** refresh it, so re-run `npm i -g claude-mem-lite@latest` if you want that shell command kept in sync. You do **not** need it for the plugin to be fully functional.
169
169
 
170
- > **Auto-adopt no longer adds its block to your project's `CLAUDE.md` (next release after 6.19.4).** On every SessionStart the plugin delivers its steering text — the trigger table that boosts Claude's proactive use of `mem_recall` / `mem_save`. In a git repository that does not already carry the block it keeps a managed block in `CLAUDE.local.md` at the repository root (Claude Code loads that file like `CLAUDE.md`, also in subagents that load project instructions; the built-in Explore and Plan agents load none) and adds the file to the repository's `.git/info/exclude` unless your ignore rules already cover it, so git does not list or commit it; you get a **one-time notice** the first time it is written. Claude Code reads instruction files before the plugin's startup hook runs, so the session that creates the file gets the text added to its context instead, once (its subagents do not see it). Where Claude Code reads an `AGENTS.md` as the project's instructions, it stops reading it once a `CLAUDE.md` or `CLAUDE.local.md` exists in the session's directory or above, so there nothing is written and the text is **injected** (subagents do not see it), with a one-time notice that names that `AGENTS.md`. With `CLAUDE_MEM_RULES_STEERING=1` the block goes to `.claude/rules/claude-mem-lite.md` at the repository root instead — excluded from git the same way, loaded by Claude Code as project instructions, also in subagents that load project instructions, and it leaves `AGENTS.md` loading — with its own one-time notice; it is not the default because in a pre-registered A/B it did not beat injection by the bar set in advance (`docs/audits/20261006-d212-ab.md`). Outside git, in a repository rooted at `$HOME`, where `CLAUDE.local.md` is tracked or a symbolic link, or where the repository root is an npm package that `npm publish` would ship it with (no `"private": true`, no `files` list leaving it out, and without one no `.npmignore` naming it), nothing is written and the text is **injected** into each session's context, with a one-time notice suggesting `/adopt` (not at `$HOME`). With the variable set, the same holds where the rules file cannot be written (a symbolic link on its path, a tracked or foreign file of that name, an npm package that would ship it). The notice beside an `AGENTS.md` names it, why there is no file, and the ways to a file that keep it loading, each only where it works: Project instructions = `claude-md-and-agents-md` in `/config`, after which `CLAUDE.local.md` is written (not where `CLAUDE.local.md` is refused too: a package root, or a file you removed), and `/adopt`, whose `CLAUDE.md` imports the `AGENTS.md` beside it (not offered when an `AGENTS.md` above that directory or in a subdirectory would stop loading). The detail file the block points at lives in the plugin's data directory, named with a `~/` path. `.git/info/exclude` is read by git only: docker build contexts, archives and other packagers can pick `CLAUDE.local.md` or the rules file up (a publishable npm package root does not keep `CLAUDE.local.md`: a block written before is taken out at the next session start; in a project whose `AGENTS.md` it would switch off, the block comes out and is injected, or, with `CLAUDE_MEM_RULES_STEERING=1`, moves to the rules file where that can be written). Earlier versions added the block to your project's own `<cwd>/CLAUDE.md` (a file that is normally committed) plus a `<cwd>/.claude/plugin_claude_mem_lite.md` detail file, unasked, in every project you opened; those projects keep the block, and the first session of this version refreshes it because the text changed — to move one to the local file, run `claude-mem-lite unadopt` there and commit the removal. Why not inject everywhere: in our sandbox evaluation (one project, Claude Opus 5.5) the agent made 1.5 proactive memory saves per 8-session run with injected steering against 5.25 with the block in `CLAUDE.local.md` or `CLAUDE.md`, and subagents never saw injected text. It applies regardless of install path (npm, npx, `/plugin`, manual); silence these notices with `MEM_NO_ADOPT_HINT=1`.
170
+ > **Auto-adopt no longer adds its block to your project's `CLAUDE.md` (next release after 6.19.4).** On every SessionStart the plugin delivers its steering text — the trigger table that boosts Claude's proactive use of `mem_recall` / `mem_save`. In a git repository that does not already carry the block it keeps a managed block in `CLAUDE.local.md` at the repository root (Claude Code loads that file like `CLAUDE.md`, also in subagents that load project instructions; the built-in Explore and Plan agents load none) and adds the file to the repository's `.git/info/exclude` unless your ignore rules already cover it, so git does not list or commit it; you get a **one-time notice** the first time it is written. Where Claude Code already loads the current block from a `CLAUDE.md` or `CLAUDE.local.md` above the repository root (outside git, above the session's directory) — a directory you ran `adopt` in, or, in a `claude --worktree` session, the main checkout's `CLAUDE.local.md` — nothing is written or injected and an untracked copy the plugin wrote before is taken out (with `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1` it stays), except while `claudeMdExcludes` is set in your user or project settings. Claude Code reads instruction files before the plugin's startup hook runs, so the session that creates the file gets the text added to its context instead, once (its subagents do not see it). Where Claude Code reads an `AGENTS.md` as the project's instructions, it stops reading it once a `CLAUDE.md` or `CLAUDE.local.md` exists in the session's directory or above, so there nothing is written and the text is **injected** (subagents do not see it), with a one-time notice that names that `AGENTS.md`. With `CLAUDE_MEM_RULES_STEERING=1` the block goes to `.claude/rules/claude-mem-lite.md` at the repository root instead — excluded from git the same way, loaded by Claude Code as project instructions, also in subagents that load project instructions, and it leaves `AGENTS.md` loading — with its own one-time notice; it is not the default because in a pre-registered A/B it did not beat injection by the bar set in advance (`docs/audits/20261006-d212-ab.md`). Outside git, in a repository rooted at `$HOME`, or where the repository root is an npm package that `npm publish` would ship it with (no `"private": true`, no `files` list leaving it out, and without one no `.npmignore` naming it), nothing is written and, unless a current block above already loads (see above), the text is **injected** into each session's context, with a one-time notice suggesting `/adopt` (not at `$HOME`). With the variable set, the same holds where the rules file cannot be written (a symbolic link on its path, a tracked or foreign file of that name, an npm package that would ship it). The notice beside an `AGENTS.md` names it, why there is no file, and the ways to a file that keep it loading, each only where it works: Project instructions = `claude-md-and-agents-md` in `/config`, after which `CLAUDE.local.md` is written (not where `CLAUDE.local.md` is refused too: a package root, or a file you removed), and `/adopt`, whose `CLAUDE.md` imports the `AGENTS.md` beside it (not offered when an `AGENTS.md` above that directory or in a subdirectory would stop loading). The detail file the block points at lives in the plugin's data directory, named with a `~/` path. `.git/info/exclude` is read by git only: docker build contexts, archives and other packagers can pick `CLAUDE.local.md` or the rules file up (a publishable npm package root does not keep `CLAUDE.local.md`: a block written before is taken out at the next session start; in a project whose `AGENTS.md` it would switch off, the block comes out and is injected, or, with `CLAUDE_MEM_RULES_STEERING=1`, moves to the rules file where that can be written). Earlier versions added the block to your project's own `<cwd>/CLAUDE.md` (a file that is normally committed) plus a `<cwd>/.claude/plugin_claude_mem_lite.md` detail file, unasked, in every project you opened; those projects keep the block, and the first session of this version refreshes it because the text changed — to move one to the local file, run `claude-mem-lite unadopt` there and commit the removal. Why not inject everywhere: in our sandbox evaluation (one project, Claude Opus 5.5) the agent made 1.5 proactive memory saves per 8-session run with injected steering against 5.25 with the block in `CLAUDE.local.md` or `CLAUDE.md`, and subagents never saw injected text. It applies regardless of install path (npm, npx, `/plugin`, manual); silence these notices with `MEM_NO_ADOPT_HINT=1`.
171
171
  >
172
- > **Want the block in `CLAUDE.md` instead** (for example to share it with your team)? Run `claude-mem-lite adopt`: it writes the slug-scoped managed block into `<cwd>/CLAUDE.md` plus the detail file, preserving everything outside the block, and removes the auto-written local copy (`CLAUDE.local.md` or the rules file). Claude Code stops reading `AGENTS.md` once a `CLAUDE.md` exists, so a `CLAUDE.md` that adopt creates next to an `AGENTS.md` (or `.claude/AGENTS.md`) starts by importing it (`@AGENTS.md`, behind a marker comment Claude Code does not load), and that file keeps loading; an `AGENTS.md` above the directory or tracked below it cannot be imported that way and is named in adopt's output, with the setting that keeps it (Project instructions = `claude-md-and-agents-md`). Nothing is imported where a `CLAUDE.md` of yours already exists, since `AGENTS.md` was not being read there. `unadopt` deletes a `CLAUDE.md` that holds nothing but those lines and the block. A project that carries the block is kept in sync on **every SessionStart** — refreshed when the shipped template changes — and gets no local or injected copy on top of it, also in sessions started from a subdirectory. A `CLAUDE.md` holding nothing but the block (what an earlier version's auto-adopt wrote) gets the same `AGENTS.md` import at the next session started in its directory, with a one-time notice. Seen from a session started in a subdirectory, the import points outside the working directory, so Claude Code asks once to approve it. A local block (`CLAUDE.local.md` or the rules file) the plugin created and you deleted (or `claude-mem-lite unadopt` removed) is not written back — the text is injected instead — until `claude-mem-lite adopt --enable` (beside an `AGENTS.md` that `CLAUDE.local.md` would switch off, a file comes back only with `CLAUDE_MEM_RULES_STEERING=1` too). Turn steering off per project with `claude-mem-lite adopt --disable` (it also removes the local block; a `CLAUDE.md` block stays until `unadopt`; `--enable` re-arms) or globally with `export MEM_NO_AUTO_ADOPT=1` (blocks already written stay and keep loading until `unadopt`); freeze the blocks against template refreshes with `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1`. `claude-mem-lite unadopt` removes the `CLAUDE.md` block, the detail file, and the local block (`CLAUDE.local.md` or `.claude/rules/claude-mem-lite.md`) with its exclude entry.
172
+ > **Want the block in `CLAUDE.md` instead** (for example to share it with your team)? Run `claude-mem-lite adopt`: it writes the slug-scoped managed block into `<cwd>/CLAUDE.md` plus the detail file, preserving everything outside the block, and removes the auto-written local copy (`CLAUDE.local.md` or the rules file). Claude Code stops reading `AGENTS.md` once a `CLAUDE.md` exists, so a `CLAUDE.md` that adopt creates next to an `AGENTS.md` (or `.claude/AGENTS.md`) starts by importing it (`@AGENTS.md`, behind a marker comment Claude Code does not load), and that file keeps loading; an `AGENTS.md` above the directory or tracked below it cannot be imported that way and is named in adopt's output, with the setting that keeps it (Project instructions = `claude-md-and-agents-md`). Nothing is imported where a `CLAUDE.md` of yours already exists, since `AGENTS.md` was not being read there. `unadopt` deletes a `CLAUDE.md` that holds nothing but those lines and the block. While auto-adopt is on, a session started in the directory whose `CLAUDE.md` carries the block refreshes it when the shipped template changes and adds no local or injected copy on top of it. A `CLAUDE.md` holding nothing but the block (what an earlier version's auto-adopt wrote) gets the same `AGENTS.md` import at the next session started in its directory, with a one-time notice. Seen from a session started in a subdirectory, the import points outside the working directory, so Claude Code asks once to approve it. A local block (`CLAUDE.local.md` or the rules file) the plugin created and you deleted (or `claude-mem-lite unadopt` removed) is not written back — the text is injected instead — until `claude-mem-lite adopt --enable` (beside an `AGENTS.md` that `CLAUDE.local.md` would switch off, a file comes back only with `CLAUDE_MEM_RULES_STEERING=1` too). Turn steering off per project with `claude-mem-lite adopt --disable` (it also removes the local block; a `CLAUDE.md` block stays until `unadopt`; `--enable` re-arms) or globally with `export MEM_NO_AUTO_ADOPT=1` (blocks already written stay and keep loading until `unadopt`); freeze the blocks against template refreshes with `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1`. `claude-mem-lite unadopt` removes the `CLAUDE.md` block, the detail file, and the local block (`CLAUDE.local.md` or `.claude/rules/claude-mem-lite.md`) with its exclude entry.
173
173
 
174
174
  ### Method 2: npx (one-liner)
175
175
 
@@ -239,6 +239,40 @@ rm -rf ~/claude-mem-lite/ # unhidden data dir from before the first release (n
239
239
  repos/ # Shallow-cloned source repos
240
240
  ```
241
241
 
242
+ ## Upgrading to 6.32.0
243
+
244
+ **The steering sync looks above the repository before writing its copy; nothing to run, and the
245
+ schema version stays 49.** To go back, pin `claude-mem-lite@6.31.0`; its next session writes the
246
+ local copy back. Both changes below hold unless `claudeMdExcludes` is set in your user or project
247
+ settings.
248
+
249
+ - **No `CLAUDE.local.md` where Claude Code already loads the current block from above the
250
+ repository root**: in a `claude --worktree` session, the main checkout's `CLAUDE.local.md`; below a
251
+ directory you ran `adopt` in, its `CLAUDE.md`. An untracked copy the plugin wrote there before is
252
+ taken out (kept with `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1`), and comes back if that block goes.
253
+ `claude-mem-lite adopt --status` names the file that carries it.
254
+ - **Outside git, nothing is injected below a directory whose `CLAUDE.md` carries the current block.**
255
+ - Details in CHANGELOG.md.
256
+
257
+ ## Upgrading to 6.31.0
258
+
259
+ **Recall injects less that does not apply to the step at hand; nothing to run, and the schema
260
+ version stays 49.** Each change that drops an injection has a switch back; to undo the text
261
+ changes, pin `claude-mem-lite@6.30.15`.
262
+
263
+ - **PreToolUse recall no longer injects the lesson of a same-named file in another directory of
264
+ the project** (`src/mcp/server/mod.rs` when you edit `src/snapshot/mod.rs`). Bare names, worktree
265
+ copies, paths outside the project, spellings that cannot be placed and paths that name no file
266
+ now (a file that moved) still match. Back: `CLAUDE_MEM_PRETOOL_PATH_PRECISION=off`.
267
+ - **Error recall shows a thread a memory once while the thread lasts**, not once per 30 minutes.
268
+ Back: `CLAUDE_MEM_ERROR_RECALL_REPEAT_MIN=30`.
269
+ - **Error recall reads an exit-0 git command's output without the commit records git prints** (a
270
+ subject such as `fix: a traceback on …`) and stays silent when nothing left reads as a failure;
271
+ the record shapes are listed under `CLAUDE_MEM_ERROR_RECALL_GIT_RECORD` below. Back:
272
+ `CLAUDE_MEM_ERROR_RECALL_GIT_RECORD=off`.
273
+ - **Text only:** the error-recall block no longer ends with `→ Use mem_get(…)`; the MCP server
274
+ instructions list the flags of `defer add` and `save`. Details in CHANGELOG.md.
275
+
242
276
  ## Upgrading to 6.29.0
243
277
 
244
278
  **Chinese text in lessons, facts, concepts and aliases becomes searchable, and the database opens
@@ -749,8 +783,8 @@ Slash commands `/adopt` and `/unadopt` wrap the same CLI.
749
783
 
750
784
  **Safety:**
751
785
  - Regenerated, not hand-edit-safe: `adopt` rewrites the managed block to the shipped
752
- template, and so does every SessionStart whenever the block differs from it — hand edits
753
- included. Keep your own notes outside the `claude-mem-lite:begin…end` markers, or set
786
+ template, and so does a later session started in that directory (while auto-adopt is on)
787
+ whenever the block differs from it — hand edits included. Keep your own notes outside the `claude-mem-lite:begin…end` markers, or set
754
788
  `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1` to freeze the block.
755
789
  - Slug-scoped & dedup-guarded: only the `claude-mem-lite:begin…end` region is
756
790
  ever rewritten, and duplicate / CRLF-orphaned copies are collapsed to one.
@@ -759,13 +793,13 @@ Slash commands `/adopt` and `/unadopt` wrap the same CLI.
759
793
  - **Auto-adopt runs on EVERY SessionStart, for any install path, and no longer adds
760
794
  the block to `CLAUDE.md` (next release after 6.19.4).** A git project without the
761
795
  block gets it in `CLAUDE.local.md` at the git root (kept out of git via
762
- `.git/info/exclude`), or in SessionStart context where `CLAUDE.local.md` would stop
796
+ `.git/info/exclude`; not where the current block already loads from above the root), or in SessionStart context where `CLAUDE.local.md` would stop
763
797
  Claude Code reading the project's `AGENTS.md` (in `.claude/rules/claude-mem-lite.md`
764
- with `CLAUDE_MEM_RULES_STEERING=1`), outside git, and where no file can be written; a project that
798
+ with `CLAUDE_MEM_RULES_STEERING=1`), and where no file can be written; a project that
765
799
  carries the `CLAUDE.md` block (explicit `adopt`, or an older version's auto-adopt)
766
- has it kept in sync — refreshed when the shipped template changes (freeze with
767
- `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1`) — and gets no local or injected copy, also in
768
- sessions started from a subdirectory; a `CLAUDE.md` holding only the block also gets
800
+ has it refreshed by a session started in that directory when the shipped template
801
+ changes (freeze with `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1`), and that session adds no
802
+ local or injected copy; a `CLAUDE.md` holding only the block also gets
769
803
  adopt's `AGENTS.md` import when an `AGENTS.md` is beside it. A local block (`CLAUDE.local.md` or
770
804
  the rules file) the plugin created and you (or `unadopt`) removed is not written back;
771
805
  `adopt --enable` re-arms it (beside such an `AGENTS.md`, together with
@@ -1205,6 +1239,7 @@ claude-mem-lite.
1205
1239
  | `CLAUDE_MEM_SUMMARY_TAIL` | `0`/`off` stops Stop from using the head of the final reply (first 120 characters, code blocks and line-leading markers removed) as a session's Completed line when that reply has no Done / Not done / Failed / Uncertain section; Completed then falls back to observation titles, as before v6.18.0; a line already written gives way to the titles at the session's next turn. A later reply under 400 characters does not replace an earlier one. | _(on)_ |
1206
1240
  | `CLAUDE_MEM_EPISODE_INPUT_FILTER` | What the episode summarizer may learn from. A subagent's tool calls stay out of the episode buffer unless they edit a file inside the project, and mutation probes (mutate → RED run → restore) and the agent's own failing inline scripts (a patch's `anchor not found`) are dropped before a window is saved or summarized — replayed over the 30 audited events, this removes 3 of the 16 that were wrong outright; with `CLAUDE_MEM_LESSON_GROUNDING` none of the 16 lessons is injected. `off` restores the unfiltered input. | _(on)_ |
1207
1241
  | `CLAUDE_MEM_BASH_RECALL` | File recall before a Bash command that views (`cat`, `sed -n`, `head`…) or writes (`sed -i`, `cat > f`, a python patch…) a file, like the Read / Edit recall. A bash prefilter keeps Node from starting for other commands. `off` disables this leg only. | _(on)_ |
1242
+ | `CLAUDE_MEM_PRETOOL_PATH_PRECISION` | `off` restores the name-only file match of PreToolUse recall. **On by default** (R3 O1): a lesson recorded for a same-named file in another directory of the project (`src/mcp/server/mod.rs` when you edit `src/snapshot/mod.rs`, the root `README.md` when you edit `tasks/x/README.md`) is not injected; bare names, Claude Code worktree copies, paths outside the project, spellings that cannot be placed (`../`, `~/`, a drive letter) and paths that name no file now (a file that moved) still match. Paths are compared as POSIX paths, so on a native Windows host the match is unchanged. 210 of 4,037 injected rows on 194 transcripts were such a different file. | _(on)_ |
1208
1243
  | `CLAUDE_MEM_LESSON_GROUNDING` | An auto-captured event keeps its lesson only when the lesson quotes the window's own diagnosis (a failing output line, a comment the edit added, or the commit message); otherwise the row is kept without it at importance 1, below every injection face. `off` keeps unquoted lessons. | _(on)_ |
1209
1244
  | `CLAUDE_MEM_LESSON_OUTPUT_CAP` | An auto-captured lesson that shares four consecutive words with TOOL OUTPUT (a command's printed text or a tool's response, which whoever controls that output can write) is kept off the injection faces: an event keeps its row and lesson, searchable, at importance 1; a `change` observation, whose importance later reads can raise, loses the lesson, and the lesson-less row is then dropped like any other (kept only with `CLAUDE_MEM_KEEP_LOW_SIGNAL=1`). Four shared words of filler ("is not in the") count too, so a lesson quoting your own comment or commit message is demoted when it also happens to share such a run with output in the same window. The row's title is not checked. `off` restores the model's importance and the lesson. | _(on)_ |
1210
1245
  | `MEM_NO_AUTO_ADOPT` | Global opt-out for auto-adopt (v2.82.0+). `1` stops auto-adopt across **all** projects — no injected steering, no new local file (`CLAUDE.local.md` or `.claude/rules/claude-mem-lite.md`), and no sync of an existing `CLAUDE.md` or local block (those stay, and keep loading, until `claude-mem-lite unadopt`). For per-project opt-out use `claude-mem-lite adopt --disable` instead (writes a durable `<memdir>/.mem-no-auto-adopt` sentinel that survives marker deletion). | _(disabled)_ |
@@ -1244,6 +1279,8 @@ benchmark and A/B harness are calibrated against — changing them invalidates t
1244
1279
  | `CLAUDE_MEM_ERROR_RECALL_BM25_MIN` | Relevance floor for the error-recall surface (memories injected after a failed Bash command). **Off by default.** Setting it to `10.5` (the calibrated value) makes the surface stay silent when its best-matching memory is not actually about the failure — the whole set is dropped, never trimmed row-by-row. **It is a real trade, not a free win:** measured on a live database at that threshold, injections fall ~37% and ~39% of firings go silent, concentrated in projects with few memories. Off by default because nothing shows the dropped rows were noise. Explore with `node benchmark/error-recall-suite.mjs --sweep`. | `0` (off) |
1245
1280
  | `CLAUDE_MEM_ERROR_RECALL_RERANK` | `off` restores the flat keyword ordering of the error-recall surface. **On by default**, and unlike the floor above it removes nothing: memories that share only the failed command's vocabulary are demoted below memories that mention the failure itself, and when a project has none of the latter the result is unchanged. Measured on a live database over 52 real failing commands × 15 projects: the lead memory matched no error term in 42.3% of firings before, 21.5% after, with the injected row count identical. | _(on)_ |
1246
1281
  | `CLAUDE_MEM_ERROR_RECALL_ON_FAILURE` | `off` stops the plugin from recalling memories when a Bash command **fails at the host level**. On by default. Claude Code delivers failed tool calls to a separate `PostToolUseFailure` hook event, so before this the surface only ever saw commands that exited `0` while printing error-ish text — a genuinely failing build recalled nothing. Denials from your own guardrails (sandbox, policy hooks, declined permission prompts) and commands you interrupted are never recalled for. | _(on)_ |
1282
+ | `CLAUDE_MEM_ERROR_RECALL_REPEAT_MIN` | Minutes after which error recall may show a thread a memory it already showed. **By default not again while the thread lasts**: the record is cleared when the main thread's context starts over (`/compact`, `/clear`, a new session) and by the 24 h runtime GC; a subagent keeps its own record for its whole run (R3 O3; the earlier default was 30 minutes). `30` restores the old window. | _(whole thread)_ |
1283
+ | `CLAUDE_MEM_ERROR_RECALL_GIT_RECORD` | `off` lets error recall fire again on an exit-0 git command whose output no longer reads as a failure once the commit records git prints are set aside. **On by default** (D#717): 6 of 422 exit-0 firings on the maintainer's transcripts (2026-11-03) turned on such records alone. The records set aside are a line starting `[<branch> <sha>] `, a one-line log entry `<sha> subject` whose sha holds a letter (after any `--graph` columns), and a line starting `commit <40-hex sha>` with the header fields and indented message under it; the command must run `git log`, `show`, `commit`, `cherry-pick`, `revert`, `merge`, `rebase` or `reflog`. The rest of the output is judged as before. | _(on)_ |
1247
1284
  | `CLAUDE_MEM_UPS_IDENTIFIER_BYPASS` | `0` disables the bypass that lets an exact identifier match skip the score floors. | _(on)_ |
1248
1285
  | `CLAUDE_MEM_UPS_PROMPT_FALLBACK_LIMIT` | How many past-prompt rows the fallback arm may return. | `1` |
1249
1286
  | `MEM_COVERAGE_THRESHOLD` | Fraction of query terms a memory must cover to qualify (∈ [0,1]). | `0.4` |
package/README.zh-CN.md CHANGED
@@ -154,9 +154,9 @@ node install.mjs install
154
154
  1. **安装依赖** -- `npm install --omit=dev`(编译原生 `better-sqlite3`)
155
155
  2. **注册 MCP 服务器** -- `mem-lite` 服务器定义 19 个工具(10 个核心 + 9 个隐藏但可调;`mem_search_feedback` 仅在启用搜索遥测时注册)。v2.78 前服务器名为通用的 `mem`,现已改名为 `mem-lite` 避免与用户其它 `.mcp.json` 冲突;工具名(`mem_search`/`mem_recall` 等)保持不变。
156
156
 
157
- > **自动 adopt 不再把托管块加进你项目的 `CLAUDE.md`(6.19.4 之后的下一个版本起)。** 每次 SessionStart,插件都会送达引导文本(提升 Claude 主动调用 `mem_recall` / `mem_save` 的触发表)。在还没有托管块的 git 仓库里,它把托管块写进仓库根目录的 `CLAUDE.local.md`(Claude Code 像加载 `CLAUDE.md` 一样加载它,加载项目指令的子代理也能看到;内置的 Explore 和 Plan 子代理不加载这类文件),并把这个文件加进仓库的 `.git/info/exclude`(你的 ignore 规则已覆盖时不加),所以 git 不列出、也不提交它;第一次写入时你会看到一条**一次性提示**。Claude Code 在插件的启动钩子运行之前就读取了指令文件,所以创建这个文件的那个会话改为在上下文里注入一次引导(该会话的子代理看不到)。Claude Code 把某个 `AGENTS.md` 当作项目指令读取时,会话目录或上层只要有 `CLAUDE.md` 或 `CLAUDE.local.md` 它就不再读 `AGENTS.md`,所以在这种仓库里什么都不写,改为**注入**引导(子代理看不到),并给一条点名那个 `AGENTS.md` 的一次性提示。设了 `CLAUDE_MEM_RULES_STEERING=1` 时,托管块改写进仓库根目录的 `.claude/rules/claude-mem-lite.md`:同样经 `.git/info/exclude` 排除在 git 之外,Claude Code 把它当作项目指令加载(加载项目指令的子代理也能看到),而且不会让 `AGENTS.md` 失效;第一次写入时有单独的一次性提示。它不是默认做法,因为在预先登记的 A/B 里它没有达到事先定下的、胜过注入的标准(`docs/audits/20261006-d212-ab.md`)。不在 git 仓库里、仓库根是 `$HOME`、`CLAUDE.local.md` 已被 git 跟踪或是符号链接,或者仓库根是一个 `npm publish` 会把它带上的 npm 包(没有 `"private": true`,没有把它排除在外的 `files` 列表,没有 `files` 列表时也没有列出它的 `.npmignore`)时,什么都不写,改为每个会话把引导**注入**上下文,并一次性提示可以运行 `/adopt`(在 `$HOME` 下不提示)。设了这个变量但 rules 文件写不了时(路径上有符号链接、同名文件被跟踪或是你自己的文件、npm 包会把它带上)同样改为注入。`AGENTS.md` 旁边的提示会说明是哪个 `AGENTS.md`、为什么没有文件,并只给出在这里行得通的、保留 `AGENTS.md` 又能写文件的做法:在 `/config` 里把 Project instructions 设为 `claude-md-and-agents-md`,之后就会写 `CLAUDE.local.md`(`CLAUDE.local.md` 也会被拒写时不提,比如 npm 包根,或你删过的文件);运行 `/adopt`,它写的 `CLAUDE.md` 会导入同目录的 `AGENTS.md`(上层目录或子目录里的 `AGENTS.md` 会因此失效时不提)。托管块指向的详情文件放在插件自己的数据目录,以 `~/` 路径书写。`.git/info/exclude` 只对 git 生效:docker 构建上下文、归档和其他打包工具都可能把 `CLAUDE.local.md` 打进去(rules 文件同样如此;可发布的 npm 包根目录不会保留 `CLAUDE.local.md`:之前写入的托管块会在下一次会话启动时移除;在这个文件会让 `AGENTS.md` 失效的项目里,托管块会被移除、改为注入;设了 `CLAUDE_MEM_RULES_STEERING=1` 时,在写得了的情况下移到 rules 文件)。旧版本会在你打开的每个项目里,未经询问就向项目自己的 `<cwd>/CLAUDE.md`(通常会进 git)写入托管块,外加 `<cwd>/.claude/plugin_claude_mem_lite.md` 详情文件;这些项目保留托管块,本版本的第一个会话会因为文本变化刷新它——想把某个项目迁到本地文件,在那里运行 `claude-mem-lite unadopt` 并提交这次删除。为什么不全部改成注入:沙箱实测中(一个项目,Claude Opus 5.5),8 个会话里模型主动记录的次数,注入时平均 1.5 次,写在 `CLAUDE.local.md` 或 `CLAUDE.md` 时 5.25 次;而且子代理完全看不到注入的文本。**任何安装路径都生效**(npm、npx、`/plugin`、手动);这些提示都可以用 `MEM_NO_ADOPT_HINT=1` 关闭。
157
+ > **自动 adopt 不再把托管块加进你项目的 `CLAUDE.md`(6.19.4 之后的下一个版本起)。** 每次 SessionStart,插件都会送达引导文本(提升 Claude 主动调用 `mem_recall` / `mem_save` 的触发表)。在还没有托管块的 git 仓库里,它把托管块写进仓库根目录的 `CLAUDE.local.md`(Claude Code 像加载 `CLAUDE.md` 一样加载它,加载项目指令的子代理也能看到;内置的 Explore 和 Plan 子代理不加载这类文件),并把这个文件加进仓库的 `.git/info/exclude`(你的 ignore 规则已覆盖时不加),所以 git 不列出、也不提交它;第一次写入时你会看到一条**一次性提示**。Claude Code 已经从仓库根目录之上(不在 git 里时,从会话目录之上)的 `CLAUDE.md` 或 `CLAUDE.local.md` 加载当前版本的托管块时(你运行过 `adopt` 的上级目录;或在 `claude --worktree` 会话里,主检出的 `CLAUDE.local.md`),这里既不写也不注入,插件之前写的、未被 git 跟踪的副本会被移除(设了 `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1` 时保留);用户或项目设置里有 `claudeMdExcludes` 时除外。Claude Code 在插件的启动钩子运行之前就读取了指令文件,所以创建这个文件的那个会话改为在上下文里注入一次引导(该会话的子代理看不到)。Claude Code 把某个 `AGENTS.md` 当作项目指令读取时,会话目录或上层只要有 `CLAUDE.md` 或 `CLAUDE.local.md` 它就不再读 `AGENTS.md`,所以在这种仓库里什么都不写,改为**注入**引导(子代理看不到),并给一条点名那个 `AGENTS.md` 的一次性提示。设了 `CLAUDE_MEM_RULES_STEERING=1` 时,托管块改写进仓库根目录的 `.claude/rules/claude-mem-lite.md`:同样经 `.git/info/exclude` 排除在 git 之外,Claude Code 把它当作项目指令加载(加载项目指令的子代理也能看到),而且不会让 `AGENTS.md` 失效;第一次写入时有单独的一次性提示。它不是默认做法,因为在预先登记的 A/B 里它没有达到事先定下的、胜过注入的标准(`docs/audits/20261006-d212-ab.md`)。不在 git 仓库里、仓库根是 `$HOME`,或者仓库根是一个 `npm publish` 会把它带上的 npm 包(没有 `"private": true`,没有把它排除在外的 `files` 列表,没有 `files` 列表时也没有列出它的 `.npmignore`)时,什么都不写;除非上层已加载当前版本的托管块(见上文),否则每个会话把引导**注入**上下文,并一次性提示可以运行 `/adopt`(在 `$HOME` 下不提示)。设了这个变量但 rules 文件写不了时(路径上有符号链接、同名文件被跟踪或是你自己的文件、npm 包会把它带上)同样改为注入。`AGENTS.md` 旁边的提示会说明是哪个 `AGENTS.md`、为什么没有文件,并只给出在这里行得通的、保留 `AGENTS.md` 又能写文件的做法:在 `/config` 里把 Project instructions 设为 `claude-md-and-agents-md`,之后就会写 `CLAUDE.local.md`(`CLAUDE.local.md` 也会被拒写时不提,比如 npm 包根,或你删过的文件);运行 `/adopt`,它写的 `CLAUDE.md` 会导入同目录的 `AGENTS.md`(上层目录或子目录里的 `AGENTS.md` 会因此失效时不提)。托管块指向的详情文件放在插件自己的数据目录,以 `~/` 路径书写。`.git/info/exclude` 只对 git 生效:docker 构建上下文、归档和其他打包工具都可能把 `CLAUDE.local.md` 打进去(rules 文件同样如此;可发布的 npm 包根目录不会保留 `CLAUDE.local.md`:之前写入的托管块会在下一次会话启动时移除;在这个文件会让 `AGENTS.md` 失效的项目里,托管块会被移除、改为注入;设了 `CLAUDE_MEM_RULES_STEERING=1` 时,在写得了的情况下移到 rules 文件)。旧版本会在你打开的每个项目里,未经询问就向项目自己的 `<cwd>/CLAUDE.md`(通常会进 git)写入托管块,外加 `<cwd>/.claude/plugin_claude_mem_lite.md` 详情文件;这些项目保留托管块,本版本的第一个会话会因为文本变化刷新它——想把某个项目迁到本地文件,在那里运行 `claude-mem-lite unadopt` 并提交这次删除。为什么不全部改成注入:沙箱实测中(一个项目,Claude Opus 5.5),8 个会话里模型主动记录的次数,注入时平均 1.5 次,写在 `CLAUDE.local.md` 或 `CLAUDE.md` 时 5.25 次;而且子代理完全看不到注入的文本。**任何安装路径都生效**(npm、npx、`/plugin`、手动);这些提示都可以用 `MEM_NO_ADOPT_HINT=1` 关闭。
158
158
  >
159
- > **想把托管块改写进 `CLAUDE.md`**(例如与团队共享)?运行 `claude-mem-lite adopt`:它向 `<cwd>/CLAUDE.md` 写入 slug 限定的托管块和详情文件,块以外的内容逐字保留,并删除自动写入的那份本地副本(`CLAUDE.local.md` 或 rules 文件)。`CLAUDE.md` 一存在,Claude Code 就不再读 `AGENTS.md`,所以 adopt 在 `AGENTS.md`(或 `.claude/AGENTS.md`)旁边新建 `CLAUDE.md` 时,会在文件开头导入它(`@AGENTS.md`,前面一行是 Claude Code 不加载的标记注释),`AGENTS.md` 因此继续加载;上层目录里的、或 git 跟踪在子目录里的 `AGENTS.md` 不能这样导入,adopt 会在输出里列出它们,并给出保留它们的设置(Project instructions 设为 `claude-md-and-agents-md`)。已经有你自己的 `CLAUDE.md` 时不导入,因为那里本来就不读 `AGENTS.md`。`unadopt` 会删除只剩这些行和托管块的 `CLAUDE.md`。带托管块的项目在**每次 SessionStart** 都会同步,出货模板变了会刷新,且不会再叠加本地副本或注入,从子目录启动的会话也一样。只有托管块的 `CLAUDE.md`(旧版本自动 adopt 写的)会在下一次从它所在目录启动的会话里补上同样的 `AGENTS.md` 导入,并给一次性提示。从子目录启动的会话看来,这个导入指向工作目录之外,Claude Code 会请你批准一次。插件创建过、又被你删掉(或被 `claude-mem-lite unadopt` 删掉)的本地托管块(`CLAUDE.local.md` 或 rules 文件)不会被写回,改为注入,直到运行 `claude-mem-lite adopt --enable`(在 `CLAUDE.local.md` 会让 `AGENTS.md` 失效的仓库里,还要设 `CLAUDE_MEM_RULES_STEERING=1` 才会再写文件)。关闭方式:项目级 `claude-mem-lite adopt --disable`(同时删除本地托管块;`CLAUDE.md` 托管块保留到 `unadopt`;重新启用用 `--enable`);全局 `export MEM_NO_AUTO_ADOPT=1`(已写入的托管块保留并继续加载,直到 `unadopt`);只冻结模板刷新用 `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1`。`claude-mem-lite unadopt` 会移除 `CLAUDE.md` 托管块、详情文件,以及本地托管块(`CLAUDE.local.md` 或 `.claude/rules/claude-mem-lite.md`)和它的 exclude 条目。
159
+ > **想把托管块改写进 `CLAUDE.md`**(例如与团队共享)?运行 `claude-mem-lite adopt`:它向 `<cwd>/CLAUDE.md` 写入 slug 限定的托管块和详情文件,块以外的内容逐字保留,并删除自动写入的那份本地副本(`CLAUDE.local.md` 或 rules 文件)。`CLAUDE.md` 一存在,Claude Code 就不再读 `AGENTS.md`,所以 adopt 在 `AGENTS.md`(或 `.claude/AGENTS.md`)旁边新建 `CLAUDE.md` 时,会在文件开头导入它(`@AGENTS.md`,前面一行是 Claude Code 不加载的标记注释),`AGENTS.md` 因此继续加载;上层目录里的、或 git 跟踪在子目录里的 `AGENTS.md` 不能这样导入,adopt 会在输出里列出它们,并给出保留它们的设置(Project instructions 设为 `claude-md-and-agents-md`)。已经有你自己的 `CLAUDE.md` 时不导入,因为那里本来就不读 `AGENTS.md`。`unadopt` 会删除只剩这些行和托管块的 `CLAUDE.md`。auto-adopt 开着时,从托管块所在目录启动的会话会在出货模板变化时刷新它,且不会再叠加本地副本或注入。只有托管块的 `CLAUDE.md`(旧版本自动 adopt 写的)会在下一次从它所在目录启动的会话里补上同样的 `AGENTS.md` 导入,并给一次性提示。从子目录启动的会话看来,这个导入指向工作目录之外,Claude Code 会请你批准一次。插件创建过、又被你删掉(或被 `claude-mem-lite unadopt` 删掉)的本地托管块(`CLAUDE.local.md` 或 rules 文件)不会被写回,改为注入,直到运行 `claude-mem-lite adopt --enable`(在 `CLAUDE.local.md` 会让 `AGENTS.md` 失效的仓库里,还要设 `CLAUDE_MEM_RULES_STEERING=1` 才会再写文件)。关闭方式:项目级 `claude-mem-lite adopt --disable`(同时删除本地托管块;`CLAUDE.md` 托管块保留到 `unadopt`;重新启用用 `--enable`);全局 `export MEM_NO_AUTO_ADOPT=1`(已写入的托管块保留并继续加载,直到 `unadopt`);只冻结模板刷新用 `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1`。`claude-mem-lite unadopt` 会移除 `CLAUDE.md` 托管块、详情文件,以及本地托管块(`CLAUDE.local.md` 或 `.claude/rules/claude-mem-lite.md`)和它的 exclude 条目。
160
160
  3. **配置钩子** -- 全部七个生命周期事件:`SessionStart`、`PreCompact`、`PreToolUse`、`PostToolUse`、`PostToolUseFailure`、`Stop`、`UserPromptSubmit`
161
161
  4. **创建数据目录** -- `~/.claude-mem-lite/`(隐藏目录),存放数据库与运行时文件
162
162
  5. **自动迁移** -- `~/.claude-mem/claude-mem.db`(原版 claude-mem)以 `.legacy-backup-<时间>` 文件的形式移入 `~/.claude-mem-lite/`(插件、以及跨文件系统时的 install 改为复制),并新建一个数据库。`~/claude-mem-lite/`(首个发布版 2.0.0 之前的非隐藏目录)里留下的数据库在第一次打开时移入数据目录,前提是数据目录里还没有 claude-mem-lite 的数据库、日志、快照或保留副本;两个目录里的其他文件都不移动、不删除
@@ -201,6 +201,23 @@ rm -rf ~/claude-mem-lite/ # 首个发布版之前的非隐藏目录(不是
201
201
  repos/ # 浅克隆的源代码仓库
202
202
  ```
203
203
 
204
+ ## 升级到 6.32.0
205
+
206
+ **写引导副本之前,插件先看仓库之上的文件;不用执行任何操作,schema 版本仍是 49。** 想退回,请固定 `claude-mem-lite@6.31.0`;它的下一个会话会把本地副本写回来。用户或项目设置里有 `claudeMdExcludes` 时,下面两条都不适用。
207
+
208
+ - **Claude Code 已从仓库根目录之上加载当前版本的托管块时,不再写 `CLAUDE.local.md`**:`claude --worktree` 会话里是主检出的 `CLAUDE.local.md`;在你运行过 `adopt` 的目录下面,是那个目录的 `CLAUDE.md`。插件之前在这里写的、未被 git 跟踪的副本会被移除(设了 `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1` 时保留);上层那份没了,副本会再写回来。`claude-mem-lite adopt --status` 会指出是哪个文件带着它。
209
+ - **不在 git 里时,带当前托管块的 `CLAUDE.md` 所在目录之下的会话不再注入引导。**
210
+ - 详见 CHANGELOG.md。
211
+
212
+ ## 升级到 6.31.0
213
+
214
+ **召回注入的内容里,和当前这一步无关的更少了;不用执行任何操作,schema 版本仍是 49。** 每项会少注入内容的改动都有开关可以退回;要撤销纯文本的改动,请固定 `claude-mem-lite@6.30.15`。
215
+
216
+ - **PreToolUse 召回不再注入项目里另一个目录下同名文件的教训**(编辑 `src/snapshot/mod.rs` 时不再给 `src/mcp/server/mod.rs` 的)。裸文件名、worktree 副本、项目之外的路径、无法定位的写法,以及现在已不存在的路径(文件移走了)仍会匹配。退回:`CLAUDE_MEM_PRETOOL_PATH_PRECISION=off`。
217
+ - **同一条记忆,error recall 在同一个线程里只给一次**,不再是每 30 分钟可以再给一次。退回:`CLAUDE_MEM_ERROR_RECALL_REPEAT_MIN=30`。
218
+ - **error recall 读取退出码为 0 的 git 命令的输出时,先去掉 git 打印的提交记录**(比如标题 `fix: a traceback on …`),剩下的内容不再被判为失败就不注入。去掉的是三种行:以 `[<分支> <sha>] ` 开头的行;一行一条的日志 `<sha> 标题`,sha 里至少有一个字母(前面可以有 `--graph` 的列);以 `commit <40 位 sha>` 开头的行,以及它下面的头字段和缩进的提交说明。命令里必须有 `git log`、`show`、`commit`、`cherry-pick`、`revert`、`merge`、`rebase` 或 `reflog`。退回:`CLAUDE_MEM_ERROR_RECALL_GIT_RECORD=off`。
219
+ - **纯文本改动:** error-recall 块末尾不再有 `→ Use mem_get(…)` 这一行;MCP server instructions 列出了 `defer add` 和 `save` 的参数。详见 CHANGELOG.md。
220
+
204
221
  ## 升级到 6.29.0
205
222
 
206
223
  **lesson、facts、concepts 和 aliases 里的中文变得可以搜到;更新后的数据库打开会逐步补上这些索引,不会拖住钩子。** 没有 schema 版本变化:本版打开过的数据库,6.28.1 仍能打开、搜索和写入。要退回,请等补完之后再退:还没补到的行,在 6.28.1 下会缺少粘在中文上的英文标识符。
@@ -589,19 +606,18 @@ Slash 命令 `/adopt` 和 `/unadopt` 是上述 CLI 的包装。
589
606
  同理。
590
607
 
591
608
  **安全性:**
592
- - 托管块会被重新生成,不保留手改:`adopt` 会把它改写成出货模板,每次 SessionStart
593
- 只要它和模板不同也会改写——手动编辑的内容一样被覆盖。自己的笔记写在
609
+ - 托管块会被重新生成,不保留手改:`adopt` 会把它改写成出货模板,之后从该目录启动的会话
610
+ (auto-adopt 开着时)只要它和模板不同也会改写——手动编辑的内容一样被覆盖。自己的笔记写在
594
611
  `claude-mem-lite:begin…end` 标记之外,或设 `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1` 冻结。
595
612
  - 按 slug 限定、去重:只改写 `claude-mem-lite:begin…end` 这一段,重复或 CRLF 残留的
596
613
  副本会合并成一份。旧的 `MEMORY.md` 方案才有行数预算,`CLAUDE.md` 没有截断上限。
597
614
  - **任何安装路径每次 SessionStart 都自动 adopt,且不再把托管块加进 `CLAUDE.md`(6.19.4
598
615
  之后的下一个版本起)。** 没有托管块的 git 项目,引导写进 git 根目录的 `CLAUDE.local.md`
599
- (经 `.git/info/exclude` 排除在 git 之外);这个文件会让 Claude Code 不再读项目的 `AGENTS.md` 时
616
+ (经 `.git/info/exclude` 排除在 git 之外;根目录之上已加载当前版本的托管块时不写);这个文件会让 Claude Code 不再读项目的 `AGENTS.md` 时
600
617
  注入 SessionStart 上下文(设 `CLAUDE_MEM_RULES_STEERING=1` 时改写进 `.claude/rules/claude-mem-lite.md`),
601
- 不在 git 里、或文件写不了时也注入;带
602
- `CLAUDE.md` 托管块的项目(显式 adopt 或旧版本写入)保持同步,出货模板变化会刷新(用
603
- `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1` 冻结),且不会再叠加本地副本或注入,从子目录启动的会话
604
- 也一样;只有托管块的 `CLAUDE.md` 旁边有 `AGENTS.md` 时,还会补上 adopt 的 `AGENTS.md` 导入。插件创建过、又被你(或 `unadopt`)删掉的本地托管块(`CLAUDE.local.md` 或 rules 文件)不会被写回;
618
+ 文件写不了时也注入;带
619
+ `CLAUDE.md` 托管块的项目(显式 adopt 或旧版本写入),由从该目录启动的会话在出货模板变化时刷新(用
620
+ `CLAUDE_MEM_NO_TEMPLATE_REFRESH=1` 冻结),且该会话不会再叠加本地副本或注入;只有托管块的 `CLAUDE.md` 旁边有 `AGENTS.md` 时,还会补上 adopt 的 `AGENTS.md` 导入。插件创建过、又被你(或 `unadopt`)删掉的本地托管块(`CLAUDE.local.md` 或 rules 文件)不会被写回;
605
621
  `adopt --enable` 可重新启用(在这类 `AGENTS.md` 仓库里还要设 `CLAUDE_MEM_RULES_STEERING=1`)。项目级关闭:`claude-mem-lite adopt --disable`(写
606
622
  `<memdir>/.mem-no-auto-adopt` 哨兵,存活于 marker 删除 / 插件重装;在仓库根目录运行时,对从子目录启动的
607
623
  会话同样生效;并删除本地托管块)。全局关闭:`export MEM_NO_AUTO_ADOPT=1`(已写入的托管块保留,直到 `unadopt`)。
@@ -905,6 +921,7 @@ npm run benchmark:gate # CI 门控:指标回退超过 5% 容差时失败
905
921
  | `CLAUDE_MEM_SESSION_EVENTS` | 设为 `1`/`on` 时恢复 SessionStart 的 `### Key Events` 一节(`events` 表中最近的高重要度条目)。**v6.13.0 起默认关闭**:对 30 条 event 的核验只有 2 条属实、16 条错误。UserPromptSubmit 的 events 块与 PreToolUse 召回按查询匹配,保持开启;`mem_search` 仍可检索全部 event。 | _(关闭)_ |
906
922
  | `CLAUDE_MEM_EPISODE_INPUT_FILTER` | 决定 episode 摘要器能从哪些输入里学。子代理的工具调用不进入 episode 缓冲(修改项目内文件的除外);变异探针(改文件 → 跑红 → 还原)和 agent 自己失败的内联脚本(补丁的 `anchor not found`)在保存或摘要前被剔除——在 30 条已核验 event 上重放,这一项直接去掉 16 条错误中的 3 条;配合 `CLAUDE_MEM_LESSON_GROUNDING`,16 条错误教训一条都不会被注入。设为 `off` 恢复未过滤的输入。 | _(开启)_ |
907
923
  | `CLAUDE_MEM_BASH_RECALL` | 在查看(`cat`、`sed -n`、`head`…)或写入(`sed -i`、`cat > f`、python 补丁…)文件的 Bash 命令执行前做文件召回,与 Read / Edit 召回相同。bash 预过滤让其他命令不启动 Node。设为 `off` 只关闭这一路。 | _(开启)_ |
924
+ | `CLAUDE_MEM_PRETOOL_PATH_PRECISION` | 设为 `off` 恢复 PreToolUse 召回只按文件名匹配的旧行为。**默认开启**(R3 O1):项目里另一个目录下同名文件的教训不再注入(编辑 `src/snapshot/mod.rs` 时不再给 `src/mcp/server/mod.rs` 的,编辑 `tasks/x/README.md` 时不再给根目录 `README.md` 的);裸文件名、Claude Code worktree 副本、项目之外的路径、无法定位的写法(`../`、`~/`、盘符),以及现在已不存在的路径(文件移走了)仍会匹配。路径按 POSIX 规则比较,所以在原生 Windows 主机上匹配行为不变。194 个会话记录里,4,037 个注入行中有 210 个属于这种不同的文件。 | _(开启)_ |
908
925
  | `CLAUDE_MEM_LESSON_GROUNDING` | 自动捕获的 event 只有在教训引用了本窗口自己的诊断文字(失败输出行、编辑新增的注释或提交信息)时才保留教训;否则保留这一行但去掉教训,importance 降为 1,低于所有注入面的门槛。设为 `off` 保留未引用原文的教训。 | _(开启)_ |
909
926
  | `CLAUDE_MEM_LESSON_OUTPUT_CAP` | 自动捕获的教训如果和**工具输出**(命令打印的文字或工具返回的内容,能控制这段输出的人就能写它)有连续 4 个词相同,就不会进入注入面:event 保留这一行和教训、仍可搜索,importance 降为 1;`change` 类 observation 的 importance 之后会被读取次数抬高,所以改为去掉教训,没有教训的这一行随后会像其他同类行一样被丢弃(只有设了 `CLAUDE_MEM_KEEP_LOW_SIGNAL=1` 才保留)。连续 4 个虚词(例如 "is not in the")也算,所以引用你自己的注释或提交信息的教训,只要碰巧和同一窗口的输出共有这样一串词,也会被降级。这一行的标题不在检查范围内。设为 `off` 恢复模型给出的 importance 和教训。 | _(开启)_ |
910
927
  | `MEM_NO_AUTO_ADOPT` | auto-adopt 全局关闭开关(v2.82.0+)。设为 `1` 在**所有**项目停止自动 adopt——不注入引导文本、不新建本地文件(`CLAUDE.local.md` 或 `.claude/rules/claude-mem-lite.md`),也不同步已有的 `CLAUDE.md` 或本地托管块(这些托管块会保留并继续加载,直到 `claude-mem-lite unadopt`)。项目级关闭走 `claude-mem-lite adopt --disable`(写 `<memdir>/.mem-no-auto-adopt` 哨兵,存活于 marker 删除)。 | _(禁用)_ |
package/adopt-cli.mjs CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  realpathSync,
27
27
  } from 'fs';
28
28
  import { claudeConfigDir, claudeStatePath } from './lib/data-paths.mjs';
29
- import { join, isAbsolute, relative, dirname } from 'path';
29
+ import { join, isAbsolute, relative, dirname, resolve, basename } from 'path';
30
30
  import {
31
31
  memdirPath,
32
32
  disableSentinelPath,
@@ -45,6 +45,7 @@ import {
45
45
  hasResidue as claudeMdHasResidue,
46
46
  needsRefresh,
47
47
  readBlock,
48
+ readBlockAt,
48
49
  migrateLegacyMemoryDir,
49
50
  hasLegacyMemdirSentinel,
50
51
  claudeMdPath,
@@ -78,7 +79,9 @@ import {
78
79
  samePath,
79
80
  localFileLinked,
80
81
  userInstructionFiles,
82
+ steeringDetailDocPath,
81
83
  } from './lib/local-steering.mjs';
84
+ import { pluginSettingsScopes } from './lib/plugin-key.mjs';
82
85
  import { CLI_INVOKE } from './cli-path.mjs';
83
86
 
84
87
  /**
@@ -272,6 +275,15 @@ function adoptOne(cwd, { force, dryRun }) {
272
275
  log(`[adopt] ${cwd} → ${r.action}${docNote}${migNote}${localNote}${importNote}`);
273
276
  for (const line of elsewhere('stops')) log(line);
274
277
  for (const line of sharedNote('stops')) log(line);
278
+ // In a subdirectory the root's local copy stays for the root's sessions, and sessions started
279
+ // here load it as an ancestor too. No layout the plugin could pick loads the block once in every
280
+ // session without moving the root's sessions to injection (D#509(4) spec), so say which one does.
281
+ const top = localSteeringRoot(cwd);
282
+ const rootCopy = top && !samePath(top, cwd) ? readLocalSteering(top, PLUGIN_SLUG) : null;
283
+ if (rootCopy && rootCopy.body !== null)
284
+ log(
285
+ ` ⚠ ${rootCopy.path} also carries the block, and sessions started here load both, so they load it twice. For one copy in every session, keep the block in one CLAUDE.md at ${top} (\`${CLI_INVOKE} adopt\` there, \`${CLI_INVOKE} unadopt\` here).`,
286
+ );
275
287
  // The copy that could not come out loads beside CLAUDE.md: said, and not a success (R3-4).
276
288
  if (local.action === 'failed') {
277
289
  if (local.residue) log(` ⚠ ${local.residue}`);
@@ -409,6 +421,22 @@ export function silentAutoAdopt({ cwd, markerDir, markerKey }) {
409
421
  // (delta review P2-2; lib/quiet-scope.mjs mirrors it).
410
422
  if (isAutoAdoptDisabledFor(root)) return { ok: true, action: 'disabled', reason: 'root-disabled' };
411
423
  }
424
+ // The shipped block already loads from above the top-level (an enclosing directory's
425
+ // CLAUDE.md, or in a worktree the main checkout's CLAUDE.local.md): a local copy would be the
426
+ // second (D#509(4)). One the plugin wrote goes and is forgotten, so the file comes back if that
427
+ // block goes or falls behind; one the user removed stays removed. Frozen
428
+ // (CLAUDE_MEM_NO_TEMPLATE_REFRESH=1, how edits inside the markers are kept), it stays: removing
429
+ // it would lose them (v6.32.0 pre-release defects review F2). The detail doc in the data
430
+ // directory, which a CLAUDE.local.md above points at, is kept current as when writing one (F7).
431
+ if (steeringAbove(root, cwd).current) {
432
+ if (
433
+ process.env.CLAUDE_MEM_NO_TEMPLATE_REFRESH !== '1' &&
434
+ removeLocalSteering(root, PLUGIN_SLUG, { keepTracked: true }).action === 'removed'
435
+ )
436
+ forgetLocalSteering(root);
437
+ ensureSteeringDetailDoc();
438
+ return { ok: true, action: 'already-adopted', reason: 'above-root' };
439
+ }
412
440
  const localBlock = buildClaudeMdBlock({ detailDocRef: tildePath(ensureSteeringDetailDoc()) });
413
441
  const r = writeLocalSteering(root, {
414
442
  slug: PLUGIN_SLUG,
@@ -440,9 +468,13 @@ export function silentAutoAdopt({ cwd, markerDir, markerKey }) {
440
468
  }
441
469
  // managed-only loads no project CLAUDE.md, so the hook does not offer /adopt (v6.30.0 pre-tag
442
470
  // claims review P2-5; inside a git work tree the reason is local-managed-only).
443
- return managedOnly
444
- ? { ok: true, action: 'inject', reason: 'managed-only' }
445
- : { ok: true, action: 'inject' };
471
+ if (managedOnly) return { ok: true, action: 'inject', reason: 'managed-only' };
472
+ // Outside git there is no top-level to stop at, and the host loads every CLAUDE.md above the
473
+ // session as an ancestor: the shipped block there already steers it, and injecting was a
474
+ // second copy (D#760). An out-of-date one is not relied on (D#509(4)).
475
+ if (steeringAbove(cwd).current)
476
+ return { ok: true, action: 'already-adopted', reason: 'ancestor-claude-md' };
477
+ return { ok: true, action: 'inject' };
446
478
  }
447
479
  dropLocalSteering(cwd, { atRootOnly: true, keepTracked: true });
448
480
  let action = 'already-adopted';
@@ -532,6 +564,91 @@ function blockAbove(cwd, root) {
532
564
  }
533
565
  }
534
566
 
567
+ // The main checkout of the linked worktree at `top` as Claude Code 2.1.322 finds it from `.git` (its
568
+ // canonical-root lookup), or null. `.git` reads `gitdir: <gitdir>`; that directory's `gitdir` file
569
+ // must point back at `<top>/.git` (a worktree moved without `git worktree repair` does not, and is
570
+ // no worktree to the host); its `commondir` names the common directory, whose parent is the checkout
571
+ // when it is named `.git`, and which is itself the checkout otherwise (a bare repository). A
572
+ // submodule's gitdir has no back-pointer, so null. The host's further checks reject layouts git does
573
+ // not make; where they would differ, this skips more and the block loads twice, never not at all.
574
+ function worktreeMainCheckout(top) {
575
+ try {
576
+ const dotGit = readFileSync(join(top, '.git'), 'utf8').trim();
577
+ if (!dotGit.startsWith('gitdir:')) return null;
578
+ const gitdir = resolve(top, dotGit.slice(7).trim());
579
+ const back = resolve(gitdir, readFileSync(join(gitdir, 'gitdir'), 'utf8').trim());
580
+ if (realpathSync(back) !== join(realpathSync(top), '.git')) return null;
581
+ const common = resolve(gitdir, readFileSync(join(gitdir, 'commondir'), 'utf8').trim());
582
+ return basename(common) === '.git' ? dirname(common) : common;
583
+ } catch {
584
+ return null;
585
+ }
586
+ }
587
+
588
+ // Whether the user settings or a project's settings files set claudeMdExcludes. An excluded file does
589
+ // not load, and its globs are not evaluated here, so with any set nothing above is relied on. One set
590
+ // where these files do not reach (--settings, managed settings) is not seen (D#781, D#787).
591
+ function claudeMdExcludesSet(dirs) {
592
+ const files = new Set(dirs.flatMap((d) => pluginSettingsScopes(claudeConfigDir(), d)));
593
+ for (const f of files) {
594
+ try {
595
+ const v = JSON.parse(readFileSync(f, 'utf8'))?.claudeMdExcludes;
596
+ if (Array.isArray(v) ? v.length > 0 : v !== undefined && v !== null) return true;
597
+ } catch {
598
+ /* absent or unparseable: sets nothing */
599
+ }
600
+ }
601
+ return false;
602
+ }
603
+
604
+ /**
605
+ * The plugin's block in the instruction files Claude Code loads at launch from ABOVE `top` — a git
606
+ * top-level, or outside git the session's directory (D#509(4), D#760). Checked on Claude Code
607
+ * 2.1.322 with InstructionsLoaded and in its source (tasks/specs/d509-steering-above-root.md): the
608
+ * CLAUDE.md and CLAUDE.local.md of every directory above the session load, inside other git
609
+ * repositories too, up to but not including the filesystem root; a worktree session skips the
610
+ * CLAUDE.md (and rules) of every directory from its main checkout down, while still loading their
611
+ * CLAUDE.local.md. Rules files never count here.
612
+ *
613
+ * `current` is the nearest such file whose block is the shipped one — a CLAUDE.md compared as the
614
+ * sync compares it (block and detail doc), a CLAUDE.local.md against the local block — or any block
615
+ * under CLAUDE_MEM_NO_TEMPLATE_REFRESH=1; `stale` the nearest one that is not. Only a current block
616
+ * may stand in for the local copy: an out-of-date one alone would swap the shipped text for an older
617
+ * one (6.19's block lacks the row on checking a memory against the code). Nothing counts under
618
+ * managed-only (no project file loads) or where claudeMdExcludes is set.
619
+ * @returns {{current: string|null, stale: string|null}} file paths
620
+ */
621
+ function steeringAbove(top, cwd = top) {
622
+ const found = { current: null, stale: null };
623
+ if (userInstructionFiles() === 'managed-only') return found;
624
+ const main = worktreeMainCheckout(top);
625
+ if (claudeMdExcludesSet(main ? [cwd, top, main] : [cwd, top])) return found;
626
+ const frozen = process.env.CLAUDE_MEM_NO_TEMPLATE_REFRESH === '1';
627
+ const version = CURRENT_SENTINEL_VERSION;
628
+ const shipped = { slug: PLUGIN_SLUG, version, block: buildClaudeMdBlock(), doc: getDetailDoc() };
629
+ const localBlock = buildClaudeMdBlock({ detailDocRef: tildePath(steeringDetailDocPath()) });
630
+ const note = (file, current) => {
631
+ if (current) found.current ??= file;
632
+ else found.stale ??= file;
633
+ };
634
+ const dirs = [];
635
+ for (let d = dirname(top); dirname(d) !== d; d = dirname(d)) dirs.push(d);
636
+ const lastSkipped = main ? dirs.findIndex((d) => samePath(d, main)) : -1;
637
+ for (const [i, d] of dirs.entries()) {
638
+ if (i > lastSkipped && blockIn(d)) note(claudeMdPath(d), frozen || !needsRefresh(d, shipped));
639
+ let local = null;
640
+ try {
641
+ local = readBlockAt(join(d, LOCAL_MD), PLUGIN_SLUG);
642
+ } catch {
643
+ /* a directory or an unreadable file: no block of ours */
644
+ }
645
+ if (local && local.body !== null)
646
+ note(join(d, LOCAL_MD), frozen || (local.version === version && local.body === localBlock));
647
+ if (found.current) return found;
648
+ }
649
+ return found;
650
+ }
651
+
535
652
  function writeMarker(markerDir, markerKey) {
536
653
  if (!existsSync(markerDir)) mkdirSync(markerDir, { recursive: true });
537
654
  const path = join(markerDir, `.auto-adopt-${markerKey}`);
@@ -669,6 +786,41 @@ function localSteeringStatus(cwd) {
669
786
  return `— none: CLAUDE.md carries the block (the local copy in ${cur.path} is removed at the next session start)`;
670
787
  return `⚠ CLAUDE.md carries the block, and ${cur.path} also does${kept ? ` (${kept}; the plugin leaves it as it is)` : ''}: sessions here load it twice`;
671
788
  }
789
+ // Then the files above the top-level (outside git, above the session), as the session checks them
790
+ // (D#509(4), D#760).
791
+ const above = steeringAbove(root ?? cwd, cwd);
792
+ if (above.current) {
793
+ const cur = root ? readLocalSteering(root, PLUGIN_SLUG) : null;
794
+ if (cur === null || cur.body === null) return `— none: ${above.current} carries the block`;
795
+ const kept = localFileLinked(root, cur.path)
796
+ ? 'behind a symbolic link'
797
+ : trackedByGit(root, relative(root, cur.path))
798
+ ? 'tracked by git'
799
+ : null;
800
+ // A session started here takes the copy out, when the sync runs and where it can, unless a damaged
801
+ // sentinel line in CLAUDE.md stops it first or the template is frozen.
802
+ if (
803
+ !kept &&
804
+ runs &&
805
+ removable(cur.path) &&
806
+ straySentinelLines(claudeMdPath(cwd), PLUGIN_SLUG).length === 0 &&
807
+ process.env.CLAUDE_MEM_NO_TEMPLATE_REFRESH !== '1'
808
+ )
809
+ return `— none: ${above.current} carries the block (the local copy in ${cur.path} is removed at the next session start)`;
810
+ return `⚠ ${above.current} carries the block, and ${cur.path} also does${kept ? ` (${kept}; the plugin leaves it as it is)` : ''}: sessions here load it twice`;
811
+ }
812
+ const line = localFileLine(cwd, root, runs);
813
+ if (!above.stale) return line;
814
+ // Out of date, it does not stand in for the local copy, and it loads here all the same. Only a
815
+ // CLAUDE.md has a remedy that holds in every state: what a session does to a CLAUDE.local.md
816
+ // depends on that directory (refreshed, taken out, or left as it is when tracked).
817
+ const how =
818
+ basename(above.stale) === LOCAL_MD ? '' : `; \`${CLI_INVOKE} adopt\` there brings it up to date`;
819
+ return `${line}\n ⚠ ${above.stale} holds an out-of-date copy of the block, which sessions here load as well${how}`;
820
+ }
821
+
822
+ // The rest of the `local:` line: the local file, or why there is none and what changes it.
823
+ function localFileLine(cwd, root, runs) {
672
824
  if (root) {
673
825
  const cur = readLocalSteering(root, PLUGIN_SLUG);
674
826
  if (cur.body !== null) return currentLocalLine(root, cwd, cur, runs);
package/bash-utils.mjs CHANGED
@@ -75,8 +75,12 @@ const GIT_READ_SUBCMDS = new Set([
75
75
  // intentionally excluded — they appear too often in benign search/log output. Gates
76
76
  // the bugfix-shape save-nudge (lib/cite-back-hint.mjs) so `node cli.mjs search "error"`
77
77
  // + an edit in the same episode no longer looks like an unsaved fix.
78
+ // D#734: only spaces/tabs between the `\n` and `at` (a frame is indented on its own line). With
79
+ // `\s+` there, every newline of a blank run started a match that ran to the run's end and back:
80
+ // 100k newlines took ~2.8 s per call. Replayed over 44,630 real exit-0 Bash results
81
+ // (2026-11-03), the narrower prefix changed no isHardError verdict.
78
82
  const HARD_ERROR_RE =
79
- /\bERR!|\bpanic\b|traceback|segfault|core dumped|\benoent\b|command not found|assertion\s?error|\n\s+at\s+\S|(?:type|reference|range|syntax|eval|uri)error:/i;
83
+ /\bERR!|\bpanic\b|traceback|segfault|core dumped|\benoent\b|command not found|assertion\s?error|\n[ \t]+at\s+\S|(?:type|reference|range|syntax|eval|uri)error:/i;
80
84
 
81
85
  // Commands that only set the shell up for the next one. They neither make a command
82
86
  // read-only nor stop it being one: `cd repo && grep …` is a grep. This matters because
@@ -886,7 +890,7 @@ function collectErrorTerms(cmd, response) {
886
890
  // `fail`, no `not found` — npm says "no such file") and `panic: assignment to entry
887
891
  // in nil map`, while letting `panic: runtime error: …` through purely because that
888
892
  // message happens to contain the substring `error`.
889
- // Note HARD_ERROR_RE's `\n\s+at\s+\S` alternative cannot match a single line (it
893
+ // Note HARD_ERROR_RE's `\n[ \t]+at\s+\S` alternative cannot match a single line (it
890
894
  // needs the preceding newline); that is fine — it is a stack-frame anchor, and the
891
895
  // frames it guards are accompanied by a line the other alternatives do catch.
892
896
  const errLines = String(response || '')
package/claudemd.mjs CHANGED
@@ -15,7 +15,20 @@
15
15
  //
16
16
  // See docs/CLAUDE-MD-STEERING-PLAN.md for rationale + migration.
17
17
 
18
- import { readFileSync, existsSync, unlinkSync, mkdirSync, rmdirSync, readdirSync, lstatSync } from 'fs';
18
+ import {
19
+ readFileSync,
20
+ existsSync,
21
+ unlinkSync,
22
+ mkdirSync,
23
+ rmdirSync,
24
+ readdirSync,
25
+ lstatSync,
26
+ openSync,
27
+ fstatSync,
28
+ closeSync,
29
+ readSync,
30
+ constants as fsConstants,
31
+ } from 'fs';
19
32
  import { atomicWriteFileSync as atomicWrite } from './lib/atomic-write.mjs';
20
33
  import { join, basename } from 'path';
21
34
  import { createHash } from 'crypto';
@@ -174,7 +187,9 @@ function isOwnImportsOnly(rest, slug) {
174
187
  export function holdsOnlyOwnLines(p, slug) {
175
188
  try {
176
189
  if (!existsSync(p)) return false;
177
- const rest = readFileSync(p, 'utf8').replace(blockRegexG(slug), '');
190
+ const text = readRegularText(p);
191
+ if (text === null) return false;
192
+ const rest = text.replace(blockRegexG(slug), '');
178
193
  return rest.trim() === '' || isOwnImportsOnly(rest, slug);
179
194
  } catch {
180
195
  return false;
@@ -199,7 +214,9 @@ const ANY_BLOCK_RE_G =
199
214
  export function holdsOnlyPluginLines(p, slug) {
200
215
  try {
201
216
  if (!existsSync(p)) return false;
202
- const rest = readFileSync(p, 'utf8').replace(blockRegexG(slug), '').replace(ANY_BLOCK_RE_G, '');
217
+ const text = readRegularText(p);
218
+ if (text === null) return false;
219
+ const rest = text.replace(blockRegexG(slug), '').replace(ANY_BLOCK_RE_G, '');
203
220
  return rest.trim() === '' || isOwnImportsOnly(rest, slug);
204
221
  } catch {
205
222
  return false;
@@ -264,6 +281,40 @@ export function readBlock(cwd, slug) {
264
281
  return readBlockAt(claudeMdPath(cwd), slug);
265
282
  }
266
283
 
284
+ // Claude Code 2.1.322 skips an instruction file that is "not a regular file or exceeds 4194304 byte
285
+ // limit" (its own message).
286
+ const INSTRUCTION_FILE_MAX_BYTES = 4194304;
287
+
288
+ // A regular file's text, or null for one Claude Code would not load: a FIFO or a device, or over its
289
+ // size limit. The session sync reads instruction files in every directory above the project
290
+ // (D#509(4)), /tmp among them, where any local user can put a FIFO (a blocking read stalled
291
+ // SessionStart, v6.32.0 pre-release defects review F1) or a huge file (read whole, it filled memory,
292
+ // delta review R2-1). Opened non-blocking and checked on the descriptor, so a file swapped in after
293
+ // the check is not the one read. The size fstat reports is no bound — a /proc file reports 0 and
294
+ // never ends, and a file can grow — so at most one byte past the limit is read, as Claude Code's own
295
+ // bounded read does (round-3 review F1). A directory still throws EISDIR, as a plain read did.
296
+ function readRegularText(p) {
297
+ const fd = openSync(p, fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK ?? 0));
298
+ try {
299
+ const st = fstatSync(fd);
300
+ if (st.isDirectory()) throw Object.assign(new Error(`${p}: is a directory`), { code: 'EISDIR' });
301
+ if (!st.isFile() || st.size > INSTRUCTION_FILE_MAX_BYTES) return null;
302
+ const chunks = [];
303
+ let total = 0;
304
+ for (;;) {
305
+ const chunk = Buffer.allocUnsafe(65536);
306
+ const n = readSync(fd, chunk, 0, chunk.length, null);
307
+ if (n === 0) break;
308
+ total += n;
309
+ if (total > INSTRUCTION_FILE_MAX_BYTES) return null;
310
+ chunks.push(chunk.subarray(0, n));
311
+ }
312
+ return Buffer.concat(chunks, total).toString('utf8');
313
+ } finally {
314
+ closeSync(fd);
315
+ }
316
+ }
317
+
267
318
  /**
268
319
  * readBlock for any instructions file — CLAUDE.md, or the CLAUDE.local.md that auto-adopt
269
320
  * writes (lib/local-steering.mjs). One parser, so both files get the same CRLF, orphan and
@@ -274,7 +325,8 @@ export function readBlock(cwd, slug) {
274
325
  */
275
326
  export function readBlockAt(p, slug) {
276
327
  if (!existsSync(p)) return { exists: false, version: null, body: null, raw: '' };
277
- const raw = readFileSync(p, 'utf8');
328
+ const raw = readRegularText(p);
329
+ if (raw === null) return { exists: true, version: null, body: null, raw: '' };
278
330
  const m = raw.match(blockRegex(slug));
279
331
  if (!m) return { exists: true, version: null, body: null, raw };
280
332
  // Normalize CRLF in the captured body so drift comparison (needsRefresh) is
@@ -374,7 +426,7 @@ export function needsRefresh(cwd, { slug, version, block, doc }) {
374
426
  if (!existsSync(dp)) return true;
375
427
  let cur;
376
428
  try {
377
- cur = readFileSync(dp, 'utf8');
429
+ cur = readRegularText(dp);
378
430
  } catch {
379
431
  return true;
380
432
  }
package/commands/adopt.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: adopt
3
- description: "Use when: user asks to put the claude-mem-lite steering block into the current project's CLAUDE.md (for example to share it with the team), or to (re)install it there. Writes a sentinel-wrapped managed block into <cwd>/CLAUDE.md plus a <cwd>/.claude/plugin_claude_mem_lite.md detail doc, removes the auto-written local copy (CLAUDE.local.md or .claude/rules/claude-mem-lite.md), and migrates away any legacy memory-dir sentinel. Auto-adopt never adds the block to CLAUDE.md itself; it only keeps an existing one in sync. Run /unadopt to remove."
3
+ description: "Use when: user asks to put the claude-mem-lite steering block into the current project's CLAUDE.md (for example to share it with the team), or to (re)install it there. Writes a sentinel-wrapped managed block into <cwd>/CLAUDE.md plus a <cwd>/.claude/plugin_claude_mem_lite.md detail doc, removes the auto-written local copy (CLAUDE.local.md or .claude/rules/claude-mem-lite.md) when run at the repository root, and migrates away any legacy memory-dir sentinel. Auto-adopt never adds the block to CLAUDE.md itself; it only keeps an existing one in sync. Run /unadopt to remove."
4
4
  ---
5
5
 
6
6
  # /adopt
@@ -12,13 +12,17 @@ in the project's memory-dir `MEMORY.md`: that index belongs to the user's own
12
12
  memories.
13
13
 
14
14
  Auto-adopt does not add the block to `CLAUDE.md`: in a git repository it keeps the same block
15
- in `CLAUDE.local.md` at the repository root, excluded from git through `.git/info/exclude`.
16
- Next to an `AGENTS.md` that file would switch off, and where it cannot be written (outside git,
15
+ in `CLAUDE.local.md` at the repository root, excluded from git through `.git/info/exclude`. Where Claude Code already loads the current block from a `CLAUDE.md` or
16
+ `CLAUDE.local.md` above the repository root (outside git, above the session's directory; in a `claude --worktree` session,
17
+ the main checkout's `CLAUDE.local.md`), no local copy is written and nothing is added, unless your user or project settings
18
+ set `claudeMdExcludes`.
19
+ Otherwise, next to an `AGENTS.md` that file would switch off, and where it cannot be written (outside git,
17
20
  for example), it adds the text to each session's context instead; with
18
21
  `CLAUDE_MEM_RULES_STEERING=1` it keeps the block in `.claude/rules/claude-mem-lite.md` next to
19
22
  an `AGENTS.md`, excluded the same way. Run `/adopt` when you want the block in `CLAUDE.md` — a file that is normally committed,
20
- so your team gets it too. It removes the local copy so the text does not load twice. A project that carries the block is kept in sync on every SessionStart, and a
21
- `CLAUDE.md` holding nothing but the block gets the `AGENTS.md` import described below.
23
+ so your team gets it too. Run at the repository root, it removes the local copy so the text does not load twice. While auto-adopt is on, a session started
24
+ in the directory whose `CLAUDE.md` carries the block refreshes it when the shipped template changes and, where that file holds
25
+ nothing but the block, adds the `AGENTS.md` import described below.
22
26
 
23
27
  ## What it writes
24
28
 
package/format-utils.mjs CHANGED
@@ -263,6 +263,11 @@ export function neutralizeSkillDelimiters(s) {
263
263
  * moment a fix is needed. Later rows stay as #ID pointers to keep the injected
264
264
  * payload bounded (one body, not three). Upstream noise gating (low-signal title
265
265
  * exclusion) is the SELECT's job (see triggerErrorRecall).
266
+ *
267
+ * No `→ Use mem_get(ids=[…]) for details.` footer (R3 O4,
268
+ * docs/audits/20261103-r3-optimization-plan.md): on 194 transcripts it closed 622
269
+ * blocks and MCP mem_get was called 3 times. The header line is the surface the
270
+ * citation extractors and benchmark/injection-budget.mjs key on, so it stays.
266
271
  * @param {Array<{id:number,type:string,title:string,lesson_learned?:string}>} rows
267
272
  * @returns {string} stdout block (trailing newline) or '' when there are no rows
268
273
  */
@@ -280,8 +285,7 @@ export function formatErrorRecallHints(rows) {
280
285
  }
281
286
  return head;
282
287
  });
283
- const ids = rows.map((r) => r.id).join(',');
284
- return `[claude-mem-lite] Related memories found for this error:\n${lines.join('\n')}\n \u2192 Use mem_get(ids=[${ids}]) for details.\n`;
288
+ return `[claude-mem-lite] Related memories found for this error:\n${lines.join('\n')}\n`;
285
289
  }
286
290
 
287
291
  /**
package/hook.mjs CHANGED
@@ -1010,7 +1010,8 @@ async function handlePostToolUse() {
1010
1010
 
1011
1011
  /**
1012
1012
  * N2 (session-history analysis r2): stay silent on a deliberate TDD RED and on an exit-0
1013
- * command that merely PRINTS error text. The decision is lib/error-recall-gate.mjs; this
1013
+ * command that merely PRINTS error text; D#717 adds an exit-0 git command whose failure words
1014
+ * all sit in the commit records the gate sets aside. The decision is lib/error-recall-gate.mjs; this
1014
1015
  * hands it the episode buffer the hook already keeps (read without the lock: a snapshot is
1015
1016
  * enough, and writeEpisode replaces the file by rename) and meters what it silenced, so the
1016
1017
  * suppressed volume is readable next to `error_recall` rather than inferred from its drop.
@@ -1070,7 +1071,8 @@ function triggerErrorRecall(db, toolInput, response, opts = {}) {
1070
1071
  });
1071
1072
  if (!selected) return;
1072
1073
  // Per-thread dedup, like the PreToolUse and UserPromptSubmit faces: a red/green loop re-sent
1073
- // the identical block on every failing run (lib/recall-shown.mjs ERROR_RECALL_REPEAT_MS).
1074
+ // the identical block on every failing run (lib/recall-shown.mjs errorRecallRepeatMs: once per
1075
+ // thread until compaction, R3 O3).
1074
1076
  const shownPath = errorRecallShownPath(RUNTIME_DIR, opts.thread);
1075
1077
  const shown = readErrorRecallShown(shownPath);
1076
1078
  const rows = selected.rows.filter((r) => !shown.has(String(r.id)));
package/install.mjs CHANGED
@@ -1341,8 +1341,9 @@ function configureHooks() {
1341
1341
  };
1342
1342
 
1343
1343
  // P0 subagent dispatch-time injection (default off — CLAUDE_MEM_SUBAGENT_INJECT).
1344
- // Fires on the Agent/Task dispatch so a subagent (otherwise memory-blind — #8848)
1345
- // can receive one relevant lesson via updatedInput. Parity with hooks/hooks.json.
1344
+ // Fires on the Agent/Task dispatch so a subagent, which starts without the SessionStart
1345
+ // context, can receive one relevant lesson via updatedInput before its first tool call.
1346
+ // Parity with hooks/hooks.json.
1346
1347
  // Behind the bash prefilter since 2026-08-22 (audit P2-5): the flag is off by
1347
1348
  // default, and a disabled feature was starting a Node interpreter on every single
1348
1349
  // Agent dispatch (22.6ms → 2.4ms; see scripts/pre-agent-inject.sh). The prefilter
@@ -57,9 +57,12 @@ export function readPreRecallFileEdges(runtimeDir, ccSessionId) {
57
57
  * Resolve one session's pre-tool file-edge injections as hit (cited) or miss
58
58
  * (uncited), updating the per-edge counters on observation_files.
59
59
  *
60
- * Edge matching uses the SAME predicate as pre-tool-recall's trigger query —
61
- * lib/file-edge-match.mjs is the shared source — so attribution lands exactly
62
- * on the edges that caused (or would cause) the injection.
60
+ * Edge matching uses the same SQL clause as pre-tool-recall's trigger query —
61
+ * lib/file-edge-match.mjs is the shared source. The clause is name-based, so
62
+ * for an injected row it credits every edge with the file's name, including an
63
+ * edge of a same-named file in another directory that the row also carries.
64
+ * The trigger additionally drops rows whose every same-named edge is another
65
+ * project file (edgesNameOtherFile, R3 O1).
63
66
  *
64
67
  * Semantics mirror applyCitationDecay's split idempotency keys:
65
68
  * - miss: guarded on last_resolved_session_id — never double-streaks a session.
@@ -164,7 +164,7 @@ export function errorRecallSql(limit = ERROR_RECALL_LIMIT) {
164
164
  -- This surface INLINES rows[0].lesson_learned into the model context, so an
165
165
  -- unfiltered SELECT handed a retracted lesson to the agent verbatim while its
166
166
  -- correction trailed as a bare pointer. compressed_into is filtered too, not
167
- -- only for symmetry: the block's own footer is a mem_get(ids=...) pointer, and a
167
+ -- only for symmetry: the block names every row by its #id, and a
168
168
  -- COMPRESSED_PENDING_PURGE row is queued for deletion by maintain purge_stale,
169
169
  -- so that pointer would resolve to nothing.
170
170
  AND ${liveObsFilterSql('o')}
@@ -8,6 +8,8 @@
8
8
  // tdd-red the agent has just written the test and runs it to WATCH it fail.
9
9
  // data-print an exit-0 inline script or `gh … --log-failed` whose OUTPUT is somebody
10
10
  // else's error text (a transcript line, a CI log, the script's own assert).
11
+ // git-record an exit-0 git command whose output reads as a failure only through the commit
12
+ // records withoutGitRecords sets aside (D#717).
11
13
  //
12
14
  // Reach, measured before this shipped (2026-09-26, tree fa66e5d, 196 session transcripts,
13
15
  // pre-DB firings through the shipped trigger): tdd-red 229 of 858 PostToolUse firings and
@@ -95,6 +97,54 @@ function hasRepoSourceFrame(response, projectDir) {
95
97
  return false;
96
98
  }
97
99
 
100
+ // ─── git-record (D#717) ──────────────────────────────────────────────────────
101
+ //
102
+ // `git commit -m "fix: a traceback on …" && git log --oneline` succeeded, and its output is the
103
+ // record of commits whose subjects name failures. The R3 session fired on exactly that;
104
+ // over every transcript on the maintainer's machine (2026-11-03) 6 of 422 exit-0 firings turned on
105
+ // such records alone (docs/audits/20261103-r3-optimization-plan.md §9.3). Only git's own record
106
+ // shapes are removed, and only when the command runs a subcommand that prints them; whatever else
107
+ // the output says is judged again by the shipped trigger.
108
+ // CLAUDE_MEM_ERROR_RECALL_GIT_RECORD=off restores the firing.
109
+
110
+ const GIT_RECORD_CMD_RE =
111
+ /\bgit\s+(?:(?:-[cC]\s+\S+|--?[\w-]+(?:=\S+)?)\s+)*(?:log|show|commit|cherry-pick|revert|merge|rebase|reflog)\b/;
112
+ // `[main 1a2b3c4] subject`, `[main (root-commit) 1a2b3c4] …`, `[detached HEAD 1a2b3c4] …`
113
+ const COMMIT_RESULT_LINE_RE = /^\[[^\]\n]* [0-9a-f]{7,40}\] /;
114
+ // `1a2b3c4 subject`, `1a2b3c4 (HEAD -> main) subject`, behind `--graph`'s `* | / \` columns.
115
+ // No bare leading spaces: an indented hex run is not a record git prints. At least one letter:
116
+ // an all-digit run can be a log line's epoch timestamp, and a sha that happens to be all digits
117
+ // only keeps the old firing.
118
+ const ONELINE_RECORD_RE = /^(?:[*|\\/][*|\\/ ]*)?(?=\d*[a-f])[0-9a-f]{7,40}(?: \([^)\n]*\))? \S/;
119
+ // `commit <sha>` opens the default format: header fields, then the message indented by 4 spaces.
120
+ const COMMIT_HEADER_RE = /^commit [0-9a-f]{40}\b/;
121
+ const COMMIT_FIELD_RE = /^(?:Merge|Author|AuthorDate|Commit|CommitDate|Date):/;
122
+
123
+ /** The output without the commit records git printed: result lines, one-line logs, full headers. */
124
+ function withoutGitRecords(text) {
125
+ const kept = [];
126
+ let inRecord = false;
127
+ for (const line of String(text || '').split('\n')) {
128
+ if (COMMIT_HEADER_RE.test(line)) {
129
+ inRecord = true;
130
+ continue;
131
+ }
132
+ if (inRecord) {
133
+ if (line === '' || line.startsWith(' ') || COMMIT_FIELD_RE.test(line)) continue;
134
+ inRecord = false;
135
+ }
136
+ if (COMMIT_RESULT_LINE_RE.test(line) || ONELINE_RECORD_RE.test(line)) continue;
137
+ kept.push(line);
138
+ }
139
+ return kept.join('\n');
140
+ }
141
+
142
+ function gitRecordGateOn() {
143
+ return !['0', 'off', 'false', 'no'].includes(
144
+ String(process.env.CLAUDE_MEM_ERROR_RECALL_GIT_RECORD ?? '').toLowerCase(),
145
+ );
146
+ }
147
+
98
148
  /**
99
149
  * Should this error-recall firing stay silent?
100
150
  *
@@ -105,7 +155,7 @@ function hasRepoSourceFrame(response, projectDir) {
105
155
  * (extractFileTargets' `writes`), since the call is appended to the buffer only after
106
156
  * recall ran; `exitZero` is true on the PostToolUse path, where the host has routed every
107
157
  * non-zero exit elsewhere.
108
- * @returns {{reason: 'tdd-red'|'data-print'}|null} null ⇒ fire as before.
158
+ * @returns {{reason: 'tdd-red'|'data-print'|'git-record'}|null} null ⇒ fire as before.
109
159
  */
110
160
  export function errorRecallSuppression({
111
161
  cmd,
@@ -124,5 +174,12 @@ export function errorRecallSuppression({
124
174
  // failure path (PostToolUseFailure) keeps it.
125
175
  if (exitZero && isDataPrintingCommand(command) && !hasRepoSourceFrame(response, projectDir))
126
176
  return { reason: 'data-print' };
177
+ if (
178
+ exitZero &&
179
+ GIT_RECORD_CMD_RE.test(command) &&
180
+ gitRecordGateOn() &&
181
+ !detectBashSignificance({ command }, withoutGitRecords(response)).isHardError
182
+ )
183
+ return { reason: 'git-record' };
127
184
  return null;
128
185
  }
@@ -45,10 +45,12 @@
45
45
  // same two lines as `basenameAnySep`; that copy was deleted in the same round once
46
46
  // its only consumer went, so this file is now the sole home.
47
47
  //
48
- // The one import below does not cost that: project-utils.mjs is a leaf over
49
- // `node:path`, and pre-tool-recall.js already imports it for inferProject.
48
+ // The node:path builtin is free, and the project-utils.mjs import does not cost that either: it is
49
+ // a leaf over `node:path`, and pre-tool-recall.js already imports it for inferProject.
50
+ import { existsSync } from 'node:fs';
51
+ import { posix } from 'node:path';
50
52
  import { likeLiteral } from '../project-utils.mjs';
51
- // The second import, and it costs no more than the first: scrub-record.mjs ->
53
+ // The third import, and it costs no more than the second: scrub-record.mjs ->
52
54
  // secret-scrub.mjs -> lib/private-strip.mjs are three regex-only leaves — no
53
55
  // node builtins, no DB handle, nothing child_process-shaped. Checked rather
54
56
  // than asserted, because the dependency note in this file has been wrong twice.
@@ -285,3 +287,90 @@ export function fileMatchParams(rawFilePath) {
285
287
  // written '\\' — so the JS string carries two backslash characters.
286
288
  return [filePath, fname, `%/${escaped}`, `%\\\\${escaped}`];
287
289
  }
290
+
291
+ // ─── R3 O1: a same-named file in another directory is not this file ─────────
292
+ //
293
+ // fileMatchClause's `%/<basename>` arm accepts ANY directory-qualified edge with the target's
294
+ // name, which is how the Stop-side attribution must read a heterogeneous column (bare names,
295
+ // relative and absolute paths). For INJECTION it over-matches: editing src/snapshot/mod.rs pulled
296
+ // the lessons of src/mcp/server/mod.rs, and a README.md under tasks/ pulled the root README's. On
297
+ // 194 transcripts (2026-10-06..11-03, docs/audits/20261103-r3-optimization-plan.md) 210 of 4,037
298
+ // injected PreToolUse rows named a different file of the same project. The clause itself stays as it is —
299
+ // it is byte-shared with lib/edge-attribution.mjs — and pre-tool-recall.js filters its rows with
300
+ // this predicate instead.
301
+ //
302
+ // Only what can be PLACED is judged. Both sides are normalised and a Claude Code worktree
303
+ // (`.claude/worktrees/<name>/`) is read as the project root, so a lesson recorded in an agent's
304
+ // worktree still reaches the main tree. An absolute edge is compared with the target; a relative
305
+ // one as a suffix of it (see edgesNameOtherFile). A path outside the project (a /tmp copy, another
306
+ // repository), a relative spelling with `..`, `~`, a drive letter or a scheme, and a missing project root
307
+ // cannot be placed, and such a row is kept, exactly as before. Nor can a path that names no file
308
+ // now: a file that moved inside the project left its lessons on the old path (v6.31.0 review r1).
309
+
310
+ const WORKTREE_RE = /^\.claude\/worktrees\/[^/]+\//;
311
+ const WORKTREE_IN_PATH_RE = /(^|\/)\.claude\/worktrees\/[^/]+\//;
312
+ // Spellings that cannot be placed without a filesystem or a host: a parent step, a home tilde, a
313
+ // drive letter (a Windows path read on POSIX, e.g. from import-jsonl), a URL. Pre-ship review M1.
314
+ const UNPLACEABLE_RE = /^~|^[A-Za-z]:|^[a-z][\w+.-]*:\/\/|(?:^|\/)\.\.(?:\/|$)/i;
315
+
316
+ /** `/`-separated; absolute paths through path.posix.normalize, relative ones cleaned of `.` and `//`. */
317
+ function normalisePath(p) {
318
+ const s = String(p ?? '').replace(/\\/g, '/');
319
+ if (s.startsWith('/')) return posix.normalize(s);
320
+ return s.replace(/\/{2,}/g, '/').replace(/(^|\/)(?:\.\/)+/g, '$1');
321
+ }
322
+
323
+ /** An absolute path inside the project as `<root>/…` with a worktree mapped to the root; null outside. */
324
+ function mapIntoProject(abs, root) {
325
+ if (!abs.startsWith(root + '/')) return null;
326
+ return (root + '/' + abs.slice(root.length + 1).replace(WORKTREE_RE, '')).toLowerCase();
327
+ }
328
+
329
+ /**
330
+ * True when every edge of one observation that carries the target's file name names a DIFFERENT
331
+ * file of the same project — the row matched fileMatchClause on its name alone. False whenever
332
+ * one such edge is the target, cannot be placed, or there is no such edge at all.
333
+ *
334
+ * An ABSOLUTE edge must equal the target once both are normalised and a worktree is mapped to the
335
+ * root — that is what tells `<root>/README.md` from `<root>/tasks/d614/README.md`. A RELATIVE edge
336
+ * names the target when the target's absolute path ends with it at a `/` boundary: it may have been
337
+ * recorded from any directory, including one ABOVE the session root (the monorepo case, pre-ship
338
+ * review M1), so it is not compared against the root-relative path alone.
339
+ *
340
+ * @param {string[]} storedPaths every observation_files.filename of the row
341
+ * @param {string} targetPath absolute path the tool reads or edits
342
+ * @param {string|null|undefined} projectDir the session's project root
343
+ * @param {{exists?: (p: string) => boolean}} [opts] the filesystem probe (a test or a replay passes its own)
344
+ * @returns {boolean}
345
+ */
346
+ export function edgesNameOtherFile(storedPaths, targetPath, projectDir, { exists = existsSync } = {}) {
347
+ if (typeof projectDir !== 'string' || !projectDir || !Array.isArray(storedPaths)) return false;
348
+ const root = normalisePath(projectDir).replace(/\/+$/, '');
349
+ const targetAbs = normalisePath(targetPath);
350
+ if (!root.startsWith('/') || !targetAbs.startsWith('/')) return false;
351
+ const target = mapIntoProject(targetAbs, root);
352
+ if (!target) return false;
353
+ const name = basenameAnySep(targetAbs).toLowerCase();
354
+ const sameName = storedPaths.filter(
355
+ (s) => typeof s === 'string' && basenameAnySep(s.replace(/\\/g, '/')).toLowerCase() === name,
356
+ );
357
+ if (sameName.length === 0) return false;
358
+ for (const raw of sameName) {
359
+ const s = normalisePath(raw);
360
+ if (s.startsWith('/')) {
361
+ const mapped = mapIntoProject(s, root);
362
+ if (mapped === null || mapped === target) return false;
363
+ // Probed on the main tree's spelling, so a worktree removed since does not count as gone.
364
+ if (!exists(root + '/' + s.slice(root.length + 1).replace(WORKTREE_RE, ''))) return false;
365
+ continue;
366
+ }
367
+ // Relative, bare names included: a bare name is a suffix of every same-named target, so it is
368
+ // always kept.
369
+ if (UNPLACEABLE_RE.test(raw.replace(/\\/g, '/'))) return false;
370
+ // A relative edge spelled through an agent worktree is the main tree's file (delta review F1).
371
+ const rel = s.replace(WORKTREE_IN_PATH_RE, '$1');
372
+ if (target.endsWith('/' + rel.toLowerCase())) return false;
373
+ if (!exists(root + '/' + rel)) return false;
374
+ }
375
+ return true;
376
+ }
@@ -61,6 +61,11 @@ export const LOCAL_MD = 'CLAUDE.local.md';
61
61
  /** The rules file used where CLAUDE.local.md would switch AGENTS.md off, relative to the top-level. */
62
62
  export const RULES_MD = '.claude/rules/claude-mem-lite.md';
63
63
 
64
+ /** Where ensureSteeringDetailDoc keeps the detail doc, without writing it (adopt --status reads). */
65
+ export function steeringDetailDocPath() {
66
+ return join(resolveDataDir(process.env.CLAUDE_MEM_DIR), 'plugin_claude_mem_lite.md');
67
+ }
68
+
64
69
  /**
65
70
  * The detail doc the block points at, kept in the plugin's data dir (never in the project:
66
71
  * both the injected and the CLAUDE.local.md block carry its absolute path). Rewritten only
@@ -69,7 +74,7 @@ export const RULES_MD = '.claude/rules/claude-mem-lite.md';
69
74
  * @returns {string} absolute path
70
75
  */
71
76
  export function ensureSteeringDetailDoc() {
72
- const p = join(resolveDataDir(process.env.CLAUDE_MEM_DIR), 'plugin_claude_mem_lite.md');
77
+ const p = steeringDetailDocPath();
73
78
  const doc = getDetailDoc();
74
79
  let current = null;
75
80
  try {
@@ -153,11 +153,23 @@ export function markCooldownCompacted(runtimeDir, sessionId) {
153
153
  /**
154
154
  * Error recall (PostToolUse / PostToolUseFailure) had no thread dedup, unlike PreToolUse and
155
155
  * UserPromptSubmit, so a red/green loop re-sent the identical "Related memories found for this
156
- * error" block on every failing run (E2E 2026-10-16). Ids shown to a thread are skipped for this
157
- * long, then may be shown again; compaction clears the marker (hook.mjs SessionStart), as it
158
- * does the recall header. The file is in this module's family, so the 24 h GC sweeps it.
156
+ * error" block on every failing run (E2E 2026-10-16). Ids shown to a thread are skipped from then
157
+ * on; compaction clears the marker (hook.mjs SessionStart), as it does the recall header, and the
158
+ * file is in this module's family, so the 24 h GC sweeps it.
159
+ *
160
+ * Whole thread, not 30 minutes (R3 O3, docs/audits/20261103-r3-optimization-plan.md): the
161
+ * 30-minute window this shipped with let the same memory back into the thread that still held it.
162
+ * PreToolUse shows a file's lessons once per thread for the same reason.
163
+ * CLAUDE_MEM_ERROR_RECALL_REPEAT_MIN=<minutes> restores a time window (30 = the old behaviour);
164
+ * anything that is not a positive number keeps the whole-thread default.
165
+ *
166
+ * @param {Record<string, string|undefined>} [env]
167
+ * @returns {number} milliseconds an id stays "shown"; Infinity = until the marker is cleared
159
168
  */
160
- const ERROR_RECALL_REPEAT_MS = 30 * 60 * 1000;
169
+ function errorRecallRepeatMs(env = process.env) {
170
+ const n = Number(env.CLAUDE_MEM_ERROR_RECALL_REPEAT_MIN);
171
+ return env.CLAUDE_MEM_ERROR_RECALL_REPEAT_MIN && Number.isFinite(n) && n > 0 ? n * 60 * 1000 : Infinity;
172
+ }
161
173
 
162
174
  /** @returns {string|null} the thread's error-recall marker, null without a thread */
163
175
  export function errorRecallShownPath(runtimeDir, thread) {
@@ -166,13 +178,14 @@ export function errorRecallShownPath(runtimeDir, thread) {
166
178
  }
167
179
 
168
180
  /** @returns {Map<string, number>} id → when it was shown, entries inside the window only */
169
- export function readErrorRecallShown(path, now = Date.now()) {
181
+ export function readErrorRecallShown(path, now = Date.now(), env = process.env) {
170
182
  const shown = new Map();
171
183
  if (!path) return shown;
184
+ const windowMs = errorRecallRepeatMs(env);
172
185
  try {
173
186
  const v = JSON.parse(readFileSync(path, 'utf8'));
174
187
  for (const [id, ts] of Object.entries(v?.ids || {})) {
175
- if (typeof ts === 'number' && now - ts < ERROR_RECALL_REPEAT_MS) shown.set(id, ts);
188
+ if (typeof ts === 'number' && now - ts < windowMs) shown.set(id, ts);
176
189
  }
177
190
  } catch {
178
191
  /* absent or torn: nothing shown */
@@ -30,8 +30,9 @@ export function formatTaskImperative(lesson, id) {
30
30
  return `${TASK_IMPERATIVE_PREFIX} You must: ${body}.${tag}`;
31
31
  }
32
32
 
33
- // Subagent-dispatch framing. Subagents are memory-blind (plugin hooks don't fire
34
- // inside them — #8848); the P0 dispatch hook (scripts/pre-agent-inject.js) APPENDS
33
+ // Subagent-dispatch framing. A subagent starts without the SessionStart context (plugin
34
+ // hooks do fire inside it, so recall arrives with its first tool call; #8848 no longer
35
+ // holds); the P0 dispatch hook (scripts/pre-agent-inject.js) APPENDS
35
36
  // this block to a spawned subagent's prompt via PreToolUse updatedInput. This is
36
37
  // deliberately NOT the "You must:" imperative above: Phase-0b measured live
37
38
  // (2026-07-03) that a raw imperative PREPEND trips the subagent's own
package/mem-cli.mjs CHANGED
@@ -3020,9 +3020,9 @@ function _reportSidechainCiteRecall({ days, json }) {
3020
3020
  );
3021
3021
  if (sidechain.files > 0 && sidechain.injected === 0) {
3022
3022
  out(' → subagent transcripts exist but none carried a detectable memory injection in');
3023
- out(' this window. claude-mem-lite hooks do NOT fire inside subagents; the dispatch-');
3024
- out(' time surface (pre-agent-inject.js, CLAUDE_MEM_SUBAGENT_INJECT) prompt-injects');
3025
- out(' a lesson when enabled — a 0 here means it was off or selected none for these.');
3023
+ out(' this window: neither PreToolUse recall inside the subagents nor the dispatch-');
3024
+ out(' time surface (pre-agent-inject.js, CLAUDE_MEM_SUBAGENT_INJECT, off by default)');
3025
+ out(' put a lesson in front of them.');
3026
3026
  } else if (sidechain.files === 0) {
3027
3027
  out(' → no subagent transcripts in window.');
3028
3028
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "6.30.15",
3
+ "version": "6.32.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "claude-mem-lite",
9
- "version": "6.30.15",
9
+ "version": "6.32.0",
10
10
  "os": [
11
11
  "darwin",
12
12
  "linux",
@@ -22,11 +22,11 @@
22
22
  },
23
23
  "devDependencies": {
24
24
  "@eslint/js": "^10.0.1",
25
- "@vitest/coverage-v8": "^5.0.5",
25
+ "@vitest/coverage-v8": "^5.1.0",
26
26
  "acorn": "8.19.0",
27
- "eslint": "^10.13.0",
27
+ "eslint": "^10.14.0",
28
28
  "fast-check": "^4.10.2",
29
- "knip": "^6.43.0",
29
+ "knip": "^6.44.1",
30
30
  "picomatch": "^4.0.4",
31
31
  "prettier": "3.9.10",
32
32
  "vitest": "^5.0.3"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-mem-lite",
3
- "version": "6.30.15",
3
+ "version": "6.32.0",
4
4
  "description": "Persistent long-term memory for Claude Code via MCP — captures coding decisions, bugfixes, and context across sessions. FTS5 BM25 keyword search with episode batching. Single SQLite DB, no external services. A lighter, lower-cost alternative to claude-mem (episode batching + a smaller model; cost savings are an internal estimate, not a measured benchmark).",
5
5
  "type": "module",
6
6
  "packageManager": "npm@10.9.2",
@@ -250,11 +250,11 @@
250
250
  },
251
251
  "devDependencies": {
252
252
  "@eslint/js": "^10.0.1",
253
- "@vitest/coverage-v8": "^5.0.5",
253
+ "@vitest/coverage-v8": "^5.1.0",
254
254
  "acorn": "8.19.0",
255
- "eslint": "^10.13.0",
255
+ "eslint": "^10.14.0",
256
256
  "fast-check": "^4.10.2",
257
- "knip": "^6.43.0",
257
+ "knip": "^6.44.1",
258
258
  "picomatch": "^4.0.4",
259
259
  "prettier": "3.9.10",
260
260
  "vitest": "^5.0.3"
@@ -1,11 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  // claude-mem-lite: PreToolUse:Agent|Task hook — subagent dispatch-time memory injection.
3
- // Subagents are memory-blind (plugin hooks do NOT fire inside them — #8848); this hook
3
+ // Plugin hooks do fire inside subagents now (#8848 no longer holds: subagent transcripts on one
4
+ // machine carry PreToolUse recall, 2026-11-10), but a subagent starts
5
+ // without the SessionStart context, so it sees no memory before its first tool call. This hook
4
6
  // injects ONE relevant project lesson into a dispatched subagent's prompt by mutating
5
7
  // tool_input.prompt via hookSpecificOutput.updatedInput. Verified live 2026-07-03
6
8
  // (Phase 0a: the mutation reaches the subagent's task-prompt position; Phase 0b: an
7
9
  // appended, attributed, reference-only block is adopted, whereas a raw imperative
8
- // prepend trips the subagent's own prompt-injection detector and is refused).
10
+ // prepend trips the subagent's own prompt-injection detector and is refused). It writes no
11
+ // cooldown or injected-id marker for the subagent's thread (its agent_id is not known at
12
+ // dispatch), so the subagent's own PreToolUse recall can show the same lesson again.
9
13
  //
10
14
  // DEFAULT OFF (CLAUDE_MEM_SUBAGENT_INJECT=on|1). The off path costs one env check and
11
15
  // returns — no stdin read, no DB, no heavy imports (schema/better-sqlite3 are dynamic,
@@ -25,6 +25,7 @@ import {
25
25
  fileMatchClause,
26
26
  fileMatchParams,
27
27
  basenameAnySep,
28
+ edgesNameOtherFile,
28
29
  jsonArrayLikeNeedle,
29
30
  toolEditPath,
30
31
  } from '../lib/file-edge-match.mjs';
@@ -261,6 +262,18 @@ const EDGE_DECAY_K = Math.max(1, Number.isNaN(EDGE_DECAY_K_RAW) ? 3 : EDGE_DECAY
261
262
  // environment and project pairs sit in the same bands, so the head-to-head is not
262
263
  // era-confounded. The `(null)` bucket and the face-overall figure ARE, being
263
264
  // dominated by legacy rows.
265
+ // R3 O1 (lib/file-edge-match.mjs edgesNameOtherFile): a row whose every same-named edge is ANOTHER
266
+ // file of this project is dropped after the SELECT. The SELECT is then PAGED until the slots are
267
+ // filled, because a filter downstream of a LIMIT shrinks the set instead of refilling it (the
268
+ // D#172 shape) — and the files this rule exists for are the ones with many same-named siblings:
269
+ // a fixed over-fetch of 3 left a Read of a Rust `mod.rs` silent in 8 of 122 probes on the
270
+ // maintainer's store (pre-ship review M2). Bounded at PATH_PRECISION_MAX_PAGES pages.
271
+ // CLAUDE_MEM_PRETOOL_PATH_PRECISION=off restores the name-only match and the single LIMIT.
272
+ const PATH_PRECISION_ON = !['0', 'off', 'false', 'no'].includes(
273
+ String(process.env.CLAUDE_MEM_PRETOOL_PATH_PRECISION ?? '').toLowerCase(),
274
+ );
275
+ const PATH_PRECISION_PAGE_EXTRA = 20;
276
+ const PATH_PRECISION_MAX_PAGES = 10;
264
277
  const SCOPE_FILTER_ON = ['1', 'on', 'true', 'yes'].includes(
265
278
  String(process.env.CLAUDE_MEM_SCOPE_FILTER || '').toLowerCase(),
266
279
  );
@@ -758,9 +771,9 @@ try {
758
771
  /* probe failure → unfiltered */
759
772
  }
760
773
  }
761
- const rows = db
762
- .prepare(
763
- `
774
+ // `LIMIT` stays a literal keyword: tests/order-by-created-at-guard.test.mjs reads the ORDER BY
775
+ // clause up to it, and the switch-off text must stay what it was.
776
+ const obsSelect = (limitArgs) => `
764
777
  SELECT DISTINCT o.id, o.type, o.title, o.lesson_learned
765
778
  FROM observations o
766
779
  JOIN observation_files of2 ON of2.obs_id = o.id
@@ -777,10 +790,54 @@ try {
777
790
  ${citeFactorClause('o')} DESC,
778
791
  o.created_at_epoch DESC,
779
792
  o.id DESC
780
- LIMIT ${obsLimit}
781
- `,
782
- )
783
- .all(project, cutoff, ...fileParams);
793
+ LIMIT ${limitArgs}
794
+ `;
795
+ let rows;
796
+ if (!PATH_PRECISION_ON) {
797
+ rows = db.prepare(obsSelect(`${obsLimit}`)).all(project, cutoff, ...fileParams);
798
+ } else {
799
+ const page = obsLimit + PATH_PRECISION_PAGE_EXTRA;
800
+ const select = db.prepare(obsSelect('? OFFSET ?'));
801
+ const projectRoot = inferProjectDir();
802
+ rows = [];
803
+ // Rows the old single LIMIT would have FETCHED and this rule removed (the metric's unit; the
804
+ // dedup and merge caps downstream may still have kept some of them out — delta review F4).
805
+ let displaced = 0;
806
+ let position = 0;
807
+ const pushed = new Set();
808
+ // One read transaction for every page, so a write landing between two pages cannot shift
809
+ // the OFFSET under them (a repeated or a skipped row — delta review F2).
810
+ db.transaction(() => {
811
+ for (let k = 0; k < PATH_PRECISION_MAX_PAGES && rows.length < obsLimit; k++) {
812
+ const batch = select.all(project, cutoff, ...fileParams, page, k * page);
813
+ if (batch.length === 0) break;
814
+ // The edges the match itself may use: with CLAUDE_MEM_EDGE_DECAY on, a decayed edge is not a
815
+ // match, so it must not keep the row here either (pre-ship review L1).
816
+ const ids = batch.map((r) => r.id);
817
+ const edges = new Map();
818
+ for (const e of db
819
+ .prepare(
820
+ `SELECT of2.obs_id, of2.filename FROM observation_files of2 WHERE of2.obs_id IN (${ids.map(() => '?').join(',')}) ${edgeDecayFilter}`,
821
+ )
822
+ .all(...ids)) {
823
+ if (!edges.has(e.obs_id)) edges.set(e.obs_id, []);
824
+ edges.get(e.obs_id).push(e.filename);
825
+ }
826
+ for (const r of batch) {
827
+ if (rows.length >= obsLimit) break;
828
+ if (edgesNameOtherFile(edges.get(r.id) || [], keyPath, projectRoot)) {
829
+ if (position < obsLimit) displaced++;
830
+ } else if (!pushed.has(r.id)) {
831
+ pushed.add(r.id);
832
+ rows.push(r);
833
+ }
834
+ position++;
835
+ }
836
+ if (batch.length < page) break;
837
+ }
838
+ })();
839
+ if (displaced > 0) recordMetric(DATA_DIR, { event: 'pretool_path_dropped', dropped: displaced });
840
+ }
784
841
 
785
842
  // T9: also query the `events` table — after T9, bugfix/lesson/decision/etc.
786
843
  // route here instead of observations, so we must read both sources to keep
@@ -51,6 +51,11 @@ const INSTRUCTIONS_BASE = [
51
51
  ` ${CLI_INVOKE} recent 5 — latest observations`,
52
52
  ` ${CLI_INVOKE} get 42,43 — full details by ID`,
53
53
  ` ${CLI_INVOKE} timeline --anchor 42 — chronological context`,
54
+ // R3 O6: the write verbs with their flags, so a CLI write does not start with a `help` call
55
+ // (the full help is 15.7 KB).
56
+ // tests/instructions-cli-write-lines.test.mjs runs both lines as written.
57
+ ` ${CLI_INVOKE} defer add "<title>" --priority 1|2|3 --detail "<why>" — cross-session TODO (3 = urgent)`,
58
+ ` ${CLI_INVOKE} save "<what happened>" --type bugfix --lesson "<root cause + fix>" --files <path> — save a lesson (--files ties it to file recall)`,
54
59
  '',
55
60
  'MCP tools: mem_search, mem_recent, mem_save, mem_get, mem_recall, mem_timeline (plus mem_defer/mem_defer_list/mem_defer_drop for cross-session TODOs). If already loaded, call directly (warm server, fastest path). In tool-heavy sessions these are deferred behind ToolSearch — if using one would cost a ToolSearch load first, run the Bash CLI above instead: one call, not two. Neither needs a PATH/CLI install.',
56
61
  'mem_save: Save non-obvious insights (bugfix lessons, architecture decisions).',