From 87aecc1212a798ee46fb5747f0ef88b3de7026df Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 15 Nov 2026 19:35:15 +0100 Subject: [PATCH 1/4] fix(memory): index fails closed on an unreadable registry memory_index skipped a non-regular blockers.md and dropped the awk rc, so the digest printed a false '- open: none'. With a kind it now returns 2; without, it skips the bad registry with a stderr line. The digest prints unknown on a malformed row. --- agents/handover-doc-writer.md | 2 + hooks/session-start.sh | 3 +- lib/memory.sh | 41 +++++++++++++++---- lib/tests/memory.test.sh | 70 +++++++++++++++++++++++++++++++- lib/tests/session-digest.test.sh | 41 +++++++++++++++++-- 5 files changed, 144 insertions(+), 13 deletions(-) diff --git a/agents/handover-doc-writer.md b/agents/handover-doc-writer.md index 26addd0..4e8b6c2 100644 --- a/agents/handover-doc-writer.md +++ b/agents/handover-doc-writer.md @@ -123,6 +123,8 @@ bash "$HOME/.claude/lib/memory.sh" -C "${ROOT:?}" index decision Only BDRs whose current word is `accepted`, `implemented` or `proposed` feed §6.1; `superseded` and `deprecated` ones are left out. A decision whose word is empty is counted as unreadable, not dropped silently. +If `index decision` exits non-zero, write `MEMORY: decisions reader +unavailable` instead of an empty §6.1. A `ROOT_UNSAFE` print (the first line of the root holds a control character) or a pre-paste refusal (see above) → `STATUS: BLOCKED` naming diff --git a/hooks/session-start.sh b/hooks/session-start.sh index dccc811..ab05151 100644 --- a/hooks/session-start.sh +++ b/hooks/session-start.sh @@ -336,7 +336,8 @@ _digest_blockers() { # [[ "$row" == "| BLK-"* ]] || continue line="${row#| }"; line="${line% |}" rest="${line#* | }"; rest="${rest#* | }" - [[ "$rest" == *" | "* ]] || continue + [[ "$rest" == *" | "* ]] || { + echo "- open: unknown (memory.sh index failed)"; return 0; } status="${rest##* | }"; title="${rest% | *}" case "$status" in open) open=$((open + 1)) diff --git a/lib/memory.sh b/lib/memory.sh index c80b98b..a12124a 100755 --- a/lib/memory.sh +++ b/lib/memory.sh @@ -9,7 +9,9 @@ # status append `- **Status ()**: ` to the entry; # starts with a status word ("open, reopened by …") # journal append `- ` under today's `## YYYY-MM-DD` -# index [] ID | Date | Title | Status, from headings and bodies +# index [] ID | Date | Title | Status, from headings and bodies; +# with a kind, an unreadable registry is rc 2; without, a +# bad registry is skipped with a stderr line, rc 0 # check [--staged] [] heading shape, unique IDs, no Index, # no open fence in a v2 file (v1 reported, never failed); # --staged: only NEW culprits vs HEAD, no line removed @@ -591,17 +593,42 @@ _mem_index_rows() { # → "| ID | date | title | word |" rows END { row() }' "$1" } +_mem_index_dir() { # → 1 (stderr) when .claude/memory cannot be searched + local d=.claude/memory + if [ -e "$d" ] || [ -L "$d" ]; then + { [ -d "$d" ] && [ -x "$d" ]; } && return 0 + else + [ ! -d .claude ] || [ -x .claude ] && return 0 + fi + echo "memory: $d: not a searchable directory" >&2 + return 1 +} + +_mem_index_one() { # → 0 read or absent, 1 bad (stderr) + local file=$1 rows + [ -e "$file" ] || [ -L "$file" ] || return 0 + if [ ! -f "$file" ] || ! rows=$(_mem_index_rows "$file" "$2"); then + echo "memory: $file: not a readable regular file" >&2 + return 1 + fi + printf '%s\n\n| ID | Date | Title | Status |\n|---|---|---|---|\n' "$file" + [ -n "$rows" ] && printf '%s\n' "$rows" + echo +} + memory_index() { # [] → one table per registry - local kinds k spec file + local kinds k spec strict=${1:+1} kinds=${1:-$(awk '{ print $1 }' <<< "$_MEM_TABLE")} + if ! _mem_index_dir; then + [ -n "$strict" ] && return 2 + return 0 + fi for k in $kinds; do spec=$(_mem_kind "$k") || return 2 - file=".claude/memory/${spec% *}" - [ -f "$file" ] || continue - printf '%s\n\n| ID | Date | Title | Status |\n|---|---|---|---|\n' "$file" - _mem_index_rows "$file" "${spec#* }" - echo + _mem_index_one ".claude/memory/${spec% *}" "${spec#* }" && continue + [ -n "$strict" ] && return 2 done + return 0 } _mem_index_table() { # → "IDdatelast column" per Index row diff --git a/lib/tests/memory.test.sh b/lib/tests/memory.test.sh index e9aeedf..d8cfc85 100755 --- a/lib/tests/memory.test.sh +++ b/lib/tests/memory.test.sh @@ -9,7 +9,8 @@ MEM="$ROOT/lib/memory.sh" pass=0; fail=0 check() { if [ "$2" = "$3" ]; then pass=$((pass+1)); else fail=$((fail+1)); printf 'FAIL %s: got[%s] want[%s]\n' "$1" "$2" "$3"; fi; } -FIX=$(mktemp -d) || exit 1; trap 'rm -rf "$FIX"' EXIT +FIX=$(mktemp -d) || exit 1 +trap 'chmod 700 "$FIX/ix20b/.claude/memory" 2>/dev/null; rm -rf "$FIX"' EXIT cd "$FIX" || exit 1 git init -q . && git config user.email t@t && git config user.name t export MEMORY_DATE=2026-10-27 @@ -37,6 +38,23 @@ check T1d-second-id "$(bash "$MEM" add blocker --title 'two' --body-file body.md check T1e-check-green "$(bash "$MEM" check; echo $?)" 0 check T1f-index-row "$(bash "$MEM" index blocker | grep -c '^| BLK-001 | 2026-10-27 | make red | open |$')" 1 +# T1g index healthy: rc 0 and a byte-identical full table (pre-fix capture) +want_ix=$(printf '%s\n' \ + '.claude/memory/decisions.md' '' '| ID | Date | Title | Status |' \ + '|---|---|---|---|' '' '.claude/memory/learnings.md' '' \ + '| ID | Date | Title | Status |' '|---|---|---|---|' '' \ + '.claude/memory/blockers.md' '' '| ID | Date | Title | Status |' \ + '|---|---|---|---|' \ + '| BLK-001 | 2026-10-27 | make red | open |' \ + '| BLK-002 | 2026-10-27 | two | |' '' \ + '.claude/memory/evals.md' '' '| ID | Date | Title | Status |' \ + '|---|---|---|---|' '') +check T1g-index-bytes "$(bash "$MEM" index)" "$want_ix" +bash "$MEM" index blocker >/dev/null 2>&1 +check T1h-index-kind-rc "$?" 0 +bash "$MEM" index >/dev/null 2>&1 +check T1i-index-all-rc "$?" 0 + # T2 add refuses, rc 2, registry unchanged sum=$(cksum < "$B") refused() { # → the add is rc 2 @@ -758,7 +776,9 @@ done # commit the stub. Installed here so earlier cases see the repo unceilinged. # shellcheck source=lib/tests/claude-stub.sh . "$ROOT/lib/tests/claude-stub.sh" || exit 1 -CSW=$(mktemp -d) || exit 1; trap 'rm -rf "$FIX" "$CSW"' EXIT +CSW=$(mktemp -d) || exit 1 +trap 'chmod 700 "$FIX/ix20b/.claude/memory" 2>/dev/null + rm -rf "$FIX" "$CSW"' EXIT claude_stub_install "$CSW" banner() { (cd "$1" && SESSION_START_OFFLINE=1 bash "$ROOT/hooks/session-start.sh" \ /dev/null) | grep -c "${2:-registry v1}"; } @@ -795,6 +815,52 @@ printf -- '---\nformat: 2\ntype: decisions_registry\nentry_prefix: BDR\n---\n\n# err=$(bash "$MEM" check 'a=b' 2>&1 >/dev/null + printf -- '---\nformat: 2\ntype: %s\nentry_prefix: %s\n---\n\n%s\n' \ + "$2" "$3" "$4" > "ix20/.claude/memory/$1"; } +reg20 learnings.md learnings_registry LRN '## LRN-001 — kept (2026-10-27)' +mkdir ix20/.claude/memory/blockers.md +err=$(bash "$MEM" -C ix20 index blocker 2>&1 >/dev/null); rc=$? +check T20-dir-strict-rc "$rc" 2 +check T20-dir-strict-names "$(printf '%s\n' "$err" | grep -c 'blockers.md')" 1 +out=$(bash "$MEM" -C ix20 index 2>ix20/err); rc=$? +check T20b-dir-lax-rc "$rc" 0 +check T20b-dir-lax-warns "$(grep -c 'blockers.md' ix20/err)" 1 +check T20b-dir-lax-keeps-lrn "$(printf '%s\n' "$out" | grep -c '^| LRN-001 |')" 1 +rmdir ix20/.claude/memory/blockers.md +mkfifo ix20/.claude/memory/blockers.md +timeout 5 bash "$MEM" -C ix20 index blocker >/dev/null 2>&1 /dev/null 2>&1 +check T20d-dangling-strict-rc "$?" 2 +rm ix20/.claude/memory/blockers.md +reg20 blockers.md blockers_registry BLK '## BLK-001 — mode (2026-10-27) [open]' +chmod 000 ix20/.claude/memory/blockers.md +if [ -r ix20/.claude/memory/blockers.md ]; then + echo "SKIP T20e-unreadable (chmod 000 ineffective for this user)" +else + out=$(bash "$MEM" -C ix20 index blocker 2>/dev/null); rc=$? + check T20e-unreadable-strict-rc "$rc" 2 + check T20e-no-partial-table "$(printf '%s' "$out" | grep -c .)" 0 +fi +chmod 600 ix20/.claude/memory/blockers.md +mkdir -p ix20b/.claude/memory +chmod 600 ix20b/.claude/memory +if [ -x ix20b/.claude/memory ]; then + echo "SKIP T20f-unsearchable (chmod 600 ineffective for this user)" +else + bash "$MEM" -C ix20b index blocker >/dev/null 2>&1 + check T20f-unsearchable-strict-rc "$?" 2 + bash "$MEM" -C ix20b index >/dev/null 2>&1 + check T20f-unsearchable-lax-rc "$?" 0 +fi +chmod 700 ix20b/.claude/memory + check no-claude-calls "$(claude_stub_calls)" 0 echo "PASS=$pass FAIL=$fail" [ "$fail" -eq 0 ] diff --git a/lib/tests/session-digest.test.sh b/lib/tests/session-digest.test.sh index e105d85..6af5519 100644 --- a/lib/tests/session-digest.test.sh +++ b/lib/tests/session-digest.test.sh @@ -4,7 +4,8 @@ set -u ROOT="$(cd "$(dirname "$0")/../.." && pwd)" SS="$ROOT/hooks/session-start.sh" -WORK="$(mktemp -d)" || exit 1; trap 'rm -rf "$WORK"' EXIT +WORK="$(mktemp -d)" || exit 1; SD9H_DIR= +trap '[ -z "$SD9H_DIR" ] || chmod 700 "$SD9H_DIR"; rm -rf "$WORK"' EXIT export SESSION_START_OFFLINE=1 pass=0; fail=0 check() { if [ "$2" = "$3" ]; then pass=$((pass+1)); else fail=$((fail+1)); @@ -205,12 +206,46 @@ printf '#!/usr/bin/env bash\nprintf "| BLK-1 |\\n| BLK-2 | x\\n| BLK-3 | d | t | out=$(run "$p" - "$S9"); rc=$? check SD9b-malformed-rc "$rc" 0 check SD9b-banner "$(printf '%s' "$out" | grep -c 'make doctor')" 1 -check SD9b-none "$(printf '%s\n' "$out" | grep -c -x -- '- open: none')" 1 +check SD9b-unknown "$(printf '%s\n' "$out" | grep -c -x -- '- open: unknown (memory.sh index failed)')" 1 +check SD9b-not-none "$(printf '%s\n' "$out" | grep -c -x -- '- open: none')" 0 p=$(mkproj sd9d); mkdir "$p/.claude/memory/blockers.md" out=$(run "$p" -); rc=$? check SD9c-dir-rc "$rc" 0 check SD9c-banner "$(printf '%s' "$out" | grep -c 'make doctor')" 1 -check SD9c-none "$(printf '%s\n' "$out" | grep -c -x -- '- open: none')" 1 +check SD9c-unknown "$(printf '%s\n' "$out" | grep -c -x -- '- open: unknown (memory.sh index failed)')" 1 +check SD9c-not-none "$(printf '%s\n' "$out" | grep -c -x -- '- open: none')" 0 + +# SD9f: a dangling-symlink blockers.md fails closed +p=$(mkproj sd9f); ln -s "$WORK/nowhere" "$p/.claude/memory/blockers.md" +out=$(run "$p" -); rc=$? +check SD9f-rc "$rc" 0 +check SD9f-unknown "$(printf '%s\n' "$out" | grep -c -x -- '- open: unknown (memory.sh index failed)')" 1 +check SD9f-not-none "$(printf '%s\n' "$out" | grep -c -x -- '- open: none')" 0 + +# SD9g: an unreadable (mode 000) blockers.md fails closed +p=$(mkproj sd9g); blk "$p" 1 open "Hidden" +chmod 000 "$p/.claude/memory/blockers.md" +if [ -r "$p/.claude/memory/blockers.md" ]; then + echo "SKIP SD9g-unreadable (chmod 000 ineffective for this user)" +else + out=$(run "$p" -) + check SD9g-unknown "$(printf '%s\n' "$out" | grep -c -x -- '- open: unknown (memory.sh index failed)')" 1 + check SD9g-not-none "$(printf '%s\n' "$out" | grep -c -x -- '- open: none')" 0 +fi + +# SD9h: a non-searchable .claude/memory fails closed, mode restored after +p=$(mkproj sd9h); blk "$p" 1 open "Hidden" +SD9H_DIR="$p/.claude/memory" +chmod 600 "$SD9H_DIR" +if [ -x "$SD9H_DIR" ]; then + echo "SKIP SD9h-unsearchable (chmod 600 ineffective for this user)" +else + out=$(run "$p" -) + chmod 700 "$SD9H_DIR" || true + check SD9h-unknown "$(printf '%s\n' "$out" | grep -c -x -- '- open: unknown (memory.sh index failed)')" 1 + check SD9h-not-none "$(printf '%s\n' "$out" | grep -c -x -- '- open: none')" 0 +fi +chmod 700 "$SD9H_DIR" || true # SD9d: a successful read with zero open rows says so p=$(mkproj sd9e); blk "$p" 1 resolved "Done" From 07f9a7feb7d3f67b491ab406e575897a4e6496a5 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 15 Nov 2026 19:35:34 +0100 Subject: [PATCH 2/4] chore(audits): mark memory_index fail-open fixed, log its residuals --- .claude/audits/BUGS-FOUND.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.claude/audits/BUGS-FOUND.md b/.claude/audits/BUGS-FOUND.md index 56fb8e6..5c3c795 100644 --- a/.claude/audits/BUGS-FOUND.md +++ b/.claude/audits/BUGS-FOUND.md @@ -84,7 +84,11 @@ - lib/profile.sh:68-72,85 — a root ABOVE a symlinked $HOME is caught by a string compare only (is_home covers exactly $HOME). Severity: low. Discovered while: /bugfix H6a security gate. Not fixed. -- lib/memory.sh:594-603 `memory_index` — skips a blockers.md that is not a regular file (`[ -f ] || continue`) and does not propagate the awk rc, so `index blocker` exits 0 on a registry it could not read and the session digest prints `- open: none` (SD9b/SD9c pin it). Fix direction: non-regular registry or unparsable `| BLK-` row → non-zero rc, the digest prints `unknown`. Severity: low. Discovered while: /bugfix bugs-found-scripts gates 1+2. Not fixed. +- lib/memory.sh:594-603 `memory_index` — skips a blockers.md that is not a regular file (`[ -f ] || continue`) and does not propagate the awk rc, so `index blocker` exits 0 on a registry it could not read and the session digest prints `- open: none` (SD9b/SD9c pin it). Fix direction: non-regular registry or unparsable `| BLK-` row → non-zero rc, the digest prints `unknown`. Severity: low. Discovered while: /bugfix bugs-found-scripts gates 1+2. FIXED 87aecc1 (BDR-125 gap A3). + + +- lib/memory.sh `memory_index` and the digest — what still reads as not-open or absent: an empty or unknown status word on a BLK row counts as not open (game holds 14 such v1 rows, config 3, so flagging them would fire every session); an unclosed ``` fence hides every later entry with no banner line; `index` reads without the lock while `status`/`_mem_restore` truncate then write in place (memory.sh:262,319), so a racing digest can read an empty file; `[ -e ] || [ -L ] || return 0` (:609) reads a stat failure (I/O, LSM denial) as absent. Severity: low. Discovered while: /bugfix index-fail-closed plan challenge and security gate. Not fixed. +- hooks/session-start.sh:358-377 `_digest_todo` / `_digest_journal` run awk on TODO.md and journal.md with no regular-file check and no timeout: a FIFO there hangs session start. agents/handover-doc-writer.md:105 reports a non-regular blockers.md as `no-file`. `_memory_digest` (:420) prints no digest at all when `.claude/memory` is not a directory. Severity: low. Discovered while: /bugfix index-fail-closed security gate and verifier. Not fixed. - lib/profile-state.jq `clean` strips LF/CR only: ESC and other control chars pass (no terminal sink today); human mode (:67-75) prints values unsanitized (pre-existing). Severity: low. Discovered while: /bugfix bugs-found-scripts security gate. Not fixed. - lib/tests/profile.test.sh:195 T28-nl-id-no-bare-on cannot fail (pre-fix tail is `=off`); the `clean` on pack keys has no biting assertion; lib/tests/session-digest.test.sh:245 comment still says "no digest". Severity: low. Discovered while: /bugfix bugs-found-scripts verifier. Not fixed. From 038670e4e8478c2757088eff17e652db3dc7768e Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 15 Nov 2026 20:40:28 +0100 Subject: [PATCH 3/4] docs: digest unknown line also covers an unparsable BLK row; changelog for index fail-closed --- CHANGELOG.md | 1 + README.md | 2 +- USAGE.md | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f4b8d71..f68073f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,7 @@ The BDR-125 context queue is delivered: phases 0, 0b, 4a, 1, 5, 2 and 4b-4d ship ### Fixed - `settings.json` denies a docker mount of the host root in 7 spellings: `/:/` after a space (`-v`, `--volume`) or after `=` (`-v=`, `--volume=`), the attached `-v/:/`, and `--mount` with `source=/` or `src=/` followed by a comma or a space. Each shape is denied under any subcommand and four prefixes (`docker`, `rtk docker`, `*/rtk docker`, `*/docker`): 28 rows. The 3.0.0 row `Bash(docker run * -v /:/*)` needed a token before `-v`, so a plain `docker run -v /:/x img` passed, and `Bash(docker run -v /:*)` (legacy prefix syntax) matched nothing. Both stay until the next removal window. The `autoMode.soft_deny` docker entry now names `docker create`, `docker container run` and `docker compose up` next to `docker run`. Left to the classifier: attached flag clusters (`-itv/:/x`), a host path from a variable or a substitution, root aliases (`//`, `/.`, `/..`), upper-case mount keys and compose-file volumes. Test: `lib/tests/push-guard.test.sh` T41 locks the 28 rows. +- `lib/memory.sh index ` exits 2 when the named registry exists but is not a readable regular file (directory, FIFO, dangling symlink, unreadable) or `.claude/memory` is not a searchable directory; `index` with no kind skips such a registry with a stderr line and exits 0. A non-regular `blockers.md` used to be skipped silently, so the session digest printed a false `- open: none`. The digest also prints `- open: unknown` on a `| BLK-` row it cannot parse. - `cc [profile]` (lib/cc.sh) raises the session's `oom_score_adj` to 500 before `exec claude` (raise-only, silent if the write fails). sshd's systemd override `OOMScoreAdjust=-1000` was inherited through tmux and dtach by every claude started with `cc`, so the OOM killer never picked a runaway session; `systemd-run --scope` rejects that property, hence the write inside the session (BLK-044). Test: `lib/tests/cc.test.sh` T7-oom. - `lib/project-rules.sh` (`extract`, `emit`): the out-path check resolves the rule file's first existing parent physically and refuses (rc 2, `must stay under the project`) a path a symlinked component sends outside the project; 3.0.0 checked `..` lexically only. `emit` goes through the same check and reports `cannot create` or `not written` (no partial file) with rc 2 where it printed `emitted`. An `extract` that wrote the rule but fails to rewrite CLAUDE.md keeps the rule file and the rewritten text in a temp file and names both on stderr with the command to complete or abort; it used to delete both. `/onboard` and `/init-project` keep an existing rule on an rc 2 ending in ` exists` and stop on any other rc 2. Tests: `lib/tests/project-rules.test.sh` T9h (re-asserted), T9z3 to T9z13. - `lib/memory.sh`: `memory_legacy_status` (the v1 status reader behind `memory.sh upgrade`, `/reconcile`, `/prune-memory`) ends an entry's range at the next heading of another entry of the same prefix, any level, outside a code fence, or at `## Index`: a `### BLK-` entry no longer lends its status to the `## BLK-` entry above, and a trailing `## Index` is no longer read. `memory.sh upgrade` on an entry with no strict status word writes the single word of its v1 `Status`/`Statut` label as the dated upgrade status line; when the `## Index` cell disagrees the body word wins and stderr says `kept body , dropped Index ` (the Index used to win); an Index `superseded`/`deprecated` still wins; a label without exactly one word is refused on a blocker and leaves the Index cell on a decision. Control characters from a v1 line or an Index cell print as `?`. `memory.sh journal` leaves exactly one blank line before a new date heading (a file ending with a blank line got two, one without a final newline got none). Tests: `lib/tests/memory.test.sh` T14l-gap, T15-statut-*, T15-bdr-*, T15-idx-*, T15-ctl-*, T15-trailing-index-not-read. diff --git a/README.md b/README.md index 4b0773e..79429f2 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,7 @@ Limits: a main-loop switch re-reads cold the part of the context the target mode - Tool: `mcp__memory__memory_pending` (deferred: a skill loads it once with `ToolSearch("select:mcp__memory__memory_pending")`). `/capitalize`, `/close` and the CAPITALIZE steps of `/feat`, `/bugfix`, `/hotfix`, `/ship-feature` and `/commit-change` call it first. It lists the milestones of this session and of the earlier ones kept in the store, then the failures as `NEW` or `known ` (word 4-grams matched against the backticked spans of BLK and LRN entries, superseded ones excluded through `lib/memory.sh index`; when that reader is unavailable every entry is matched and the `index:` line ends `status reader unavailable`), earlier sessions marked. Every text it returns is data. It never writes a registry; every call reads the statuses through `lib/memory.sh index`. - Recall: the mod hands registry entries back at the moment they matter. A prompt typed in the composer (never a slash command, at least 5 content words, stop words excluded) triggers it when it is the first of a context (start, `/clear`, `/compact`), comes after 30 minutes idle with at least 8 content words, or holds a design or analysis word (plan, architecture, design, why, explain, analyse, review, audit and their French forms). BM25 ranks the live BDR, LRN and BLK entries, one haiku call keeps at most 2, bounded to 5 seconds. The context block `memory recall:` carries one line per entry (ID, title, lesson), at most 1500 characters per turn, each entry once per context. Any failure or timeout injects nothing. - Known error: a Bash failure whose key matches a live BLK or LRN entry attaches `memory: known — <lesson>` to the tool answer, once per ID per context, from the same 1500-character budget. Sub-agents get this channel only. -- Digest: `hooks/session-start.sh` prints `memory digest:` on `startup`, `clear` and `compact` (never `resume`) in a project that has `.claude/memory/`: up to 3 open BLK from `memory.sh index blocker` (the rest counted, upstream ones counted; `- open: none` when none is open, `- open: unknown (memory.sh index failed)` when the read fails or times out), up to 3 unchecked TODO items (from a `## Actionable` or `### Actionable` section, else the file's first 3 unchecked top-level items; items inside HTML comments ignored), the last journal line, 800 characters at most. When the cap bites, TODO lines drop first and a `- todo: +N not shown, read .claude/tasks/TODO.md` line counts them; nothing else drops. Without `timeout` and `jq` it prints only from a terminal. +- Digest: `hooks/session-start.sh` prints `memory digest:` on `startup`, `clear` and `compact` (never `resume`) in a project that has `.claude/memory/`: up to 3 open BLK from `memory.sh index blocker` (the rest counted, upstream ones counted; `- open: none` when none is open, `- open: unknown (memory.sh index failed)` when the read fails, times out or returns a `| BLK-` row it cannot parse), up to 3 unchecked TODO items (from a `## Actionable` or `### Actionable` section, else the file's first 3 unchecked top-level items; items inside HTML comments ignored), the last journal line, 800 characters at most. When the cap bites, TODO lines drop first and a `- todo: +N not shown, read .claude/tasks/TODO.md` line counts them; nothing else drops. Without `timeout` and `jq` it prints only from a terminal. - Recall switch: `{"enabled": true, "recall": false}` in `~/.claude/memory.json` cuts the injections (recall and known-error line) and keeps capture. Every ask is logged under the `l:<root>` store key (last 200 records, 64 KiB), never shown: when, session, agent, channel, the IDs injected, the `trigger` (`fresh`, `idle`, `keyword`, `tool`) and the `outcome` (`injected`, `none`, `timeout`, `refused`, `paused`; an ask that injects nothing is logged with no IDs); a prompt ask also logs `cands` (BM25 candidates after the seen filter) and `ms` (rerank wall time, when a rerank ran). `/memory-feedback` reads it. - Recall residuals: measured on 14 days of this repo's transcripts, precision is 54 to 61 % against a 64 % bar, so recall ships on and switchable, and the log decides. The router's classifier label is not used. EVAL entries are not recalled. Each failing command that matches an entry spawns one `memory.sh index`. The haiku bound drops the recalls that answer slower than 5 seconds. - Feedback: `/memory-feedback` (phase 4d) labels each injected entry from its transcript, with a 5-label spot check by you, and reports precision, misses, noisy entries and promotion candidates against `lib/memory-feedback/thresholds.ts`. Two gates: prompt at 20 labelled asks or 35 days, tool at 10 injections (one 35-day extension, then closed). Precision, trigger precision and the miss share count only rows after the gate-1 fix; their actions wait for 20 post-fix asks (`Post-fix prompt asks: k/20` in FEEDBACK.md, pre-fix entries excluded). Data stays local in `~/.claude/memory-feedback/` (IDs, enums and repo tags only, never in git). The session banner prints `memory feedback: … → /memory-feedback` when a run is due, and goes silent once the prompt gate, the tool gate and the post-fix sample are recorded, or with `"recall": false`. diff --git a/USAGE.md b/USAGE.md index 0174745..61d77b8 100644 --- a/USAGE.md +++ b/USAGE.md @@ -217,7 +217,7 @@ Le mod `mods/memory/` note les échecs Bash et les jalons de la session pour que - L'outil : `mcp__memory__memory_pending` (différé : un skill le charge une fois avec `ToolSearch("select:mcp__memory__memory_pending")`). `/capitalize`, `/close` et les étapes CAPITALIZE de `/feat`, `/bugfix`, `/hotfix`, `/ship-feature` et `/commit-change` l'appellent en premier. Il liste les jalons de la session et ceux des sessions précédentes gardés dans le store, puis les échecs `NEW` ou `known <ID>` (4-grammes de mots comparés aux passages entre accents graves des entrées BLK et LRN, les remplacées exclues via `lib/memory.sh index` ; si ce lecteur est indisponible, toutes les entrées sont comparées et la ligne `index:` finit par `status reader unavailable`), les sessions précédentes signalées. Chaque texte est une donnée. Il n'écrit aucun registre ; chaque appel lit les statuts via `lib/memory.sh index`. - Rappel : le mod ramène les entrées des registres au bon moment. Un prompt tapé dans le composer (jamais une commande slash, au moins 5 mots de contenu, mots vides exclus) le déclenche s'il est le premier d'un contexte (démarrage, `/clear`, `/compact`), s'il suit 30 minutes d'inactivité avec au moins 8 mots de contenu, ou s'il contient un mot de conception ou d'analyse (plan, architecture, design, pourquoi, explique, analyse, review, audit et leurs équivalents anglais). BM25 classe les entrées BDR, LRN et BLK vivantes, un appel haiku en garde 2 au plus, borné à 5 secondes. Le bloc de contexte `memory recall:` porte une ligne par entrée (ID, titre, leçon), 1500 caractères par tour au plus, chaque entrée une fois par contexte. Un échec ou un dépassement n'injecte rien. - Erreur connue : un échec Bash dont la clé correspond à une entrée BLK ou LRN vivante ajoute `memory: known <ID> <titre> — <leçon>` à la réponse de l'outil, une fois par ID et par contexte, sur le même budget de 1500 caractères. Les sous-agents n'ont que ce canal. -- Digest : `hooks/session-start.sh` affiche `memory digest:` sur `startup`, `clear` et `compact` (jamais `resume`) dans un projet qui a `.claude/memory/` : jusqu'à 3 BLK ouverts issus de `memory.sh index blocker` (le reste compté, les « upstream » comptés ; `- open: none` quand aucun n'est ouvert, `- open: unknown (memory.sh index failed)` quand la lecture échoue ou dépasse son délai), jusqu'à 3 items non cochés du TODO (section `## Actionable` ou `### Actionable`, sinon les 3 premiers items de premier niveau du fichier ; items en commentaire HTML ignorés), la dernière ligne du journal, 800 caractères au plus. Quand le plafond mord, les lignes TODO tombent d'abord et une ligne `- todo: +N not shown, read .claude/tasks/TODO.md` les compte ; rien d'autre ne tombe. Sans `timeout` ni `jq`, il ne s'affiche que depuis un terminal. +- Digest : `hooks/session-start.sh` affiche `memory digest:` sur `startup`, `clear` et `compact` (jamais `resume`) dans un projet qui a `.claude/memory/` : jusqu'à 3 BLK ouverts issus de `memory.sh index blocker` (le reste compté, les « upstream » comptés ; `- open: none` quand aucun n'est ouvert, `- open: unknown (memory.sh index failed)` quand la lecture échoue, dépasse son délai ou renvoie une ligne `| BLK-` illisible), jusqu'à 3 items non cochés du TODO (section `## Actionable` ou `### Actionable`, sinon les 3 premiers items de premier niveau du fichier ; items en commentaire HTML ignorés), la dernière ligne du journal, 800 caractères au plus. Quand le plafond mord, les lignes TODO tombent d'abord et une ligne `- todo: +N not shown, read .claude/tasks/TODO.md` les compte ; rien d'autre ne tombe. Sans `timeout` ni `jq`, il ne s'affiche que depuis un terminal. - Interrupteur du rappel : `{"enabled": true, "recall": false}` dans `~/.claude/memory.json` coupe les injections (rappel et ligne d'erreur connue) et garde la capture. Chaque demande est journalisée sous la clé de store `l:<racine>` (200 enregistrements, 64 Kio), jamais affichée : date, session, agent, canal, IDs injectés, `trigger` (`fresh`, `idle`, `keyword`, `tool`) et `outcome` (`injected`, `none`, `timeout`, `refused`, `paused` ; une demande qui n'injecte rien est journalisée sans ID) ; une demande sur prompt note aussi `cands` (candidats BM25 après le filtre des entrées déjà vues) et `ms` (durée du rerank, quand il a tourné). `/memory-feedback` la lit. - Limites du rappel : mesurée sur 14 jours de transcripts de ce dépôt, la précision est de 54 à 61 % pour une barre à 64 %, donc le rappel est livré actif et coupable, et le journal tranchera. L'étiquette du classifieur du routeur n'est pas utilisée. Les entrées EVAL ne sont pas rappelées. Chaque commande en échec qui correspond à une entrée lance un `memory.sh index`. La borne haiku écarte les rappels qui répondent après 5 secondes. - Retour d'usage : `/memory-feedback` (phase 4d) étiquette chaque entrée injectée depuis son transcript, avec un contrôle de 5 étiquettes par toi, et donne la précision, les manqués, les entrées bruyantes et les candidates à promotion face aux seuils de `lib/memory-feedback/thresholds.ts`. Deux gates : prompt à 20 demandes étiquetées ou 35 jours, outil à 10 injections (une prolongation de 35 jours, puis fermé). La précision, la précision par trigger et la part de manqués ne comptent que les lignes postérieures au correctif du gate 1 ; leurs actions attendent 20 demandes post-correctif (`Post-fix prompt asks: k/20` dans FEEDBACK.md, entrées antérieures exclues). Les données restent locales dans `~/.claude/memory-feedback/` (IDs, enums et étiquettes de dépôt seulement, jamais dans git). La bannière de session affiche `memory feedback: … → /memory-feedback` quand un passage est dû, et se tait une fois le gate prompt, le gate outil et l'échantillon post-correctif enregistrés, ou avec `"recall": false`. From 1a4759d7520649b49d82782c2211fef970ea353b Mon Sep 17 00:00:00 2001 From: bchanot <chanot.bastien@gmail.com> Date: Sun, 15 Nov 2026 20:40:53 +0100 Subject: [PATCH 4/4] chore(memory): index fail-closed journal --- .claude/memory/journal.md | 1 + .../2026-11-15-index-fail-closed-1300.md | 27 ++++ .../plans/2026-11-14-bdr125-gap-audit-2330.md | 6 +- .../2026-11-15-index-fail-closed-1200.md | 148 ++++++++++++++++++ 4 files changed, 179 insertions(+), 3 deletions(-) create mode 100644 .claude/tasks/contracts/2026-11-15-index-fail-closed-1300.md create mode 100644 .claude/tasks/plans/2026-11-15-index-fail-closed-1200.md diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index ed9541b..65cbc26 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -761,3 +761,4 @@ rules: ## 2026-11-15 - Docker host-root mount deny shipped 0f73d7e: 28 rows (7 shapes x 4 prefixes), bench-proven echo analogue, verifier CONFORME, security PASS. Legacy rows dead, kept. Wrapper/podman residual added TODO:90. Docs committed. - A2 line width: 4 lines >80 cols re-wrapped (register.ts 591/683/3765, transcripts.ts 133; audit line numbers had drifted), no behavior change, make test green, security PASS. +- A3 index fail-closed: memory_index rc 2 on non-regular/unreadable registry with kind, lax skip+stderr without kind (register.ts recall keeps rc 0); digest unknown on unparsable BLK row; SD9b/c re-pinned, SD9f/g/h + T20* added (87aecc1). Residuals BUGS-FOUND 07f9a7f. Next A4. diff --git a/.claude/tasks/contracts/2026-11-15-index-fail-closed-1300.md b/.claude/tasks/contracts/2026-11-15-index-fail-closed-1300.md new file mode 100644 index 0000000..bca8d45 --- /dev/null +++ b/.claude/tasks/contracts/2026-11-15-index-fail-closed-1300.md @@ -0,0 +1,27 @@ +# CONTRACT — index-fail-closed (BDR-125 gap audit A3, BUGS-FOUND:87) +- date: 2026-11-15 | flow: bugfix | branch: bugfix/index-fail-closed (off develop) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +A3 (BDR-125 gap audit): memory_index on an unreadable or non-regular blockers.md (permission denied, a directory, a FIFO) must return non-zero so the session digest prints `- open: unknown (memory.sh index failed)` instead of `- open: none`. Today an unreadable blockers.md can yield `- open: none`, a false all-clear. Re-pin session-digest tests SD9b/SD9c to the new behavior. + +## CLARIFICATIONS +- [internal 2026-11-15, challenge r1-r3] plan .claude/tasks/plans/2026-11-15-index-fail-closed-1200.md: r2 + r3 win over the original FIX PLAN. Strict (kind named) → rc 2; lax (no kind, used live by mods/memory register.ts) → skip bad registry with stderr line, rc 0. Existing unknown line reused verbatim. Empty/unknown status words stay not-open (v1 rows in game/config). + +## ACCEPTANCE CRITERIA +1. session-digest suite green (SD9b/SD9c re-pinned to unknown, SD9f/g/h added). + CHECK: cd /home/bchanot/Documents/claude && PATH=$HOME/.bun/bin:$PATH make test suite=lib/tests/session-digest.test.sh </dev/null 2>&1 | tail -1 + EXPECT: all suites green + EVIDENCE: MET exit=0 marker-found :: all suites green +2. memory suite green (strict rc 2 on dir/FIFO, lax rc 0 with stderr, healthy rc 0 and byte-identical output). + CHECK: cd /home/bchanot/Documents/claude && PATH=$HOME/.bun/bin:$PATH make test suite=lib/tests/memory.test.sh </dev/null 2>&1 | tail -1 + EXPECT: all suites green + EVIDENCE: MET exit=0 marker-found :: all suites green +3. SD9b and SD9c assert the unknown line, not none. + CHECK: cd /home/bchanot/Documents/claude && grep -cE 'check SD9[bc]-unknown' lib/tests/session-digest.test.sh + EXPECT: 2 + EVIDENCE: MET exit=0 marker-found :: 2 +4. Full make test green; shellcheck clean on touched shell files; plan r3 items all implemented; regression tests fail on the pre-fix lib (manual). + +## FILE SCOPE +lib/memory.sh (memory_index, usage line :12), hooks/session-start.sh (_digest_blockers), lib/tests/session-digest.test.sh, lib/tests/memory.test.sh, agents/handover-doc-writer.md (:120 one sentence). diff --git a/.claude/tasks/plans/2026-11-14-bdr125-gap-audit-2330.md b/.claude/tasks/plans/2026-11-14-bdr125-gap-audit-2330.md index 49353b6..ae8b4d7 100644 --- a/.claude/tasks/plans/2026-11-14-bdr125-gap-audit-2330.md +++ b/.claude/tasks/plans/2026-11-14-bdr125-gap-audit-2330.md @@ -1,9 +1,9 @@ # BDR-125 gap audit 2026-11-14 (3 analyzers, all phases vs original asks) — consolidated ## Batch A — code (one skill each) -- A1 /bugfix docker host-root mount deny (phase 2, TODO:89): plan .claude/tasks/plans/2026-11-14-docker-mount-deny-1400.md r2 (confirmation pending). -- A2 /hotfix line width regressions: mods/memory/hooks/register.ts:976 (86 col, breaks 4b c10 / 4c c9 oracles), lib/memory-feedback/transcripts.ts:133 (follow-ups c7), register.test.ts:71 optional. -- A3 /bugfix memory_index rc 0 on unreadable/non-regular blockers.md → digest `- open: none` (4c digest defect, BUGS-FOUND:87): non-zero rc → `- open: unknown`; SD9b/SD9c re-pinned. +- [x] A1 DONE merged b03aced (0f73d7e). /bugfix docker host-root mount deny (phase 2, TODO:89): plan .claude/tasks/plans/2026-11-14-docker-mount-deny-1400.md r2. +- [x] A2 DONE merged 2315a0b (21ef47f). /hotfix line width regressions: mods/memory/hooks/register.ts:976 (86 col, breaks 4b c10 / 4c c9 oracles), lib/memory-feedback/transcripts.ts:133 (follow-ups c7), register.test.ts:71 optional. +- [x] A3 DONE 87aecc1 (docs 038670e, residuals BUGS-FOUND 07f9a7f). /bugfix memory_index rc 0 on unreadable/non-regular blockers.md → digest `- open: none` (4c digest defect, BUGS-FOUND:87): non-zero rc → `- open: unknown`; SD9b/SD9c re-pinned. - A4 memory.sh `check --staged`: new entry ID = max+1 (4a ask TODO:170; today comment "gap harmless" :162). - A5 memory.test.sh T18 hard-fails without bun on PATH → SKIP line like other bun-gated tests. - A6 (user choice) routing guard fail mode (phase 2 shared rule "guards fail closed"; today fail-open). diff --git a/.claude/tasks/plans/2026-11-15-index-fail-closed-1200.md b/.claude/tasks/plans/2026-11-15-index-fail-closed-1200.md new file mode 100644 index 0000000..26cf5ff --- /dev/null +++ b/.claude/tasks/plans/2026-11-15-index-fail-closed-1200.md @@ -0,0 +1,148 @@ +# PLAN — index-fail-closed (BDR-125 gap audit A3, BUGS-FOUND:87) + +## DIAGNOSIS +BUG: session digest prints `- open: none` when blockers.md is a directory, +a FIFO, unreadable, or when the index emits unparsable `| BLK-` rows: a +false all-clear. +ROOT CAUSE: +1. lib/memory.sh:594-603 `memory_index`: `[ -f "$file" ] || continue` + treats a present non-regular registry like an absent one; the awk rc of + `_mem_index_rows` is dropped (the function's rc is the trailing `echo`). + So `memory.sh index blocker` exits 0 with no rows. +2. hooks/session-start.sh:331-351 `_digest_blockers`: a `| BLK-` row whose + fields do not parse is skipped (`continue`), so malformed output with + rc 0 also ends as `- open: none`. +EVIDENCE: SD9b (stub prints malformed rows, rc 0) and SD9c (blockers.md is a +directory) both pin `- open: none` today (lib/tests/session-digest.test.sh: +206-213). BUGS-FOUND.md:87 states the same. +RELATED MEMORY: BDR-147/BDR-144 (digest is the start-of-session source: +a false none hides blockers, so fail closed honors them); CLAUDE.global.md +"`- open: unknown` → read blockers.md yourself" (the existing line is the +fail-closed output, reused verbatim, no new public string); LRN-274/LRN-233 +(pipefail callers, capture output). No BLK names this cause. + +## FIX PLAN +1. lib/memory.sh `memory_index`: + - `[ -e "$file" ] || continue` (absent stays silent, as today; a + dangling symlink counts as absent: `-e` false). + - present but not (`-f` and `-r`) → `echo "memory: $file: not a readable + regular file" >&2; return 1` (never opens it: a FIFO cannot block). + - `_mem_index_rows "$file" "${spec#* }" || return 1`. + Applies to every kind (`index` with no kind too): a bad registry fails + the whole call, the callers (digest, prune-memory, memory-feedback) then + say unknown instead of reading a partial table. +2. hooks/session-start.sh `_digest_blockers`: buffer the `- open: BLK…` + lines in a local variable instead of echoing inside the loop; a `| BLK-` + row that does not split into id | date | title | status (the existing + `[[ "$rest" == *" | "* ]] || continue` branch) → print the existing + `- open: unknown (memory.sh index failed)` line and `return 0`. Only on + a clean pass print the buffered lines, then the none/more lines as today. + Banner and exit code unchanged (rc 0). +3. Tests: + - lib/tests/session-digest.test.sh SD9b-none → SD9b-unknown (exact + unknown line, count 1, and `- open: none` count 0); SD9c-none → + SD9c-unknown likewise. New SD9f: blockers.md is a FIFO (mkfifo in the + test temp project) → unknown line, run returns (bounded by the + harness's existing timeout), rc 0. New SD9g: blockers.md mode 000 → + unknown, skipped with a SKIP line when `id -u` is 0. + - lib/tests/memory.test.sh: new T-index-dir: `index blocker` with + blockers.md a directory → rc 1 and stderr names the file; T-index-ok + unchanged rows still rc 0 (existing T1f covers it). + - Fix the stale comment at session-digest.test.sh:245 only if it is the + SD9 block (it is not: out of scope, C5 handles it). + +RISK: low. A caller that relied on rc 0 with a broken registry now gets +rc 1; grep shows the only runtime caller is the digest (already handles +non-zero). Skill callers run it interactively and print the error. + +## FILES +lib/memory.sh, hooks/session-start.sh, lib/tests/session-digest.test.sh, +lib/tests/memory.test.sh. + +## r2 (challenge r1: correctness CONCERNS(1), robustness CONCERNS(2), simplicity SOLID) — SUPERSEDES FIX PLAN 1-3 and RISK above +BLOCKERs landed: (a) `index` with no kind is a live runtime caller +(mods/memory/hooks/register.ts:671, stdout dropped on rc != 0 at :657 → +recall blackout); (b) `-e` false ≠ absent (dangling symlink, unsearchable +.claude/memory). Minors folded: rc 2 per lib convention (memory.sh:528,598), +`-f` guard only and awk rc propagation tested by mode 000, no buffer in the +digest, SD9f replaced by a timed memory.test.sh FIFO case, explicit rc 0 +asserts on healthy trees. + +1. lib/memory.sh `memory_index` (extract a per-registry helper if the + function passes 25 logic lines): + - strict = a kind was named (`index blocker`); lax = no kind. + - `.claude/memory` absent → every registry absent (silent, rc 0, as today). + - `.claude/memory` present but not searchable (`! -x`) → BAD. + - file absent = `! -e` AND `! -L` → silent skip (as today). + - present but `! -f` (dir, FIFO, dangling symlink, socket) → BAD, never + opened. + - rows captured first: `rows=$(_mem_index_rows …)`; awk rc != 0 (mode 000: + gawk exits 2) → BAD. Header and rows printed only after a clean read, + so no partial table reaches stdout. + - BAD → stderr `memory: <file>: not a readable regular file`; strict → + `return 2`; lax → skip this registry, continue, final rc 0 + (register.ts keeps the healthy registries; it already reports bad files + itself via tryRead). +2. hooks/session-start.sh `_digest_blockers`: the `[[ "$rest" == *" | "* ]] + || continue` branch → `{ echo "- open: unknown (memory.sh index + failed)"; return 0; }`. No buffering (real memory.sh never emits such a + row; this guards version skew/stubs; an earlier printed BLK line plus + unknown still fails closed). Empty or unknown status words stay "not + open" (game has 14, config 3 empty-status rows from v1: treating them as + unknown would flag every session) → residual in BUGS-FOUND. +3. Tests: + session-digest.test.sh: SD9b → exact unknown line count 1 and + `- open: none` count 0; SD9c (dir) → same; new SD9f dangling symlink + blockers.md → unknown; SD9g blockers.md mode 000 → unknown; SD9h + .claude/memory mode 600 (not searchable) → unknown, restore 700 after + the run; SD9g/SD9h print SKIP when `id -u` is 0. chmod only on literal + paths inside the test's own temp project, never -R. + memory.test.sh: healthy `index blocker` rc 0 and healthy `index` rc 0 + (explicit); blockers.md a directory → `index blocker` rc 2 + stderr names + blockers.md; same tree `index` (no kind) → rc 0, stderr warning, a + learnings row still printed; blockers.md a FIFO (mkfifo in the test's + mktemp dir) → `timeout 5 bash "$MEM" index blocker` rc 2 (not 124). +4. Out of the executor's scope, handled by the run's closing steps: README.md + :167 / USAGE.md:220 wording (doc sync), BUGS-FOUND:87 marked FIXED + a new + residual line (unknown/empty status words counted not-open; an unclosed + ``` fence hides later entries with no banner warning). + +RISK (corrected): runtime callers are the digest (`index blocker`, strict) +and register.ts (`index`, lax: unchanged rc 0, bad registry now skipped with +a stderr line instead of silently). Skill/agent callers (prune-memory with +a kind, memory-feedback without) get rc 2 / a stderr line on a broken +registry, which they print. + +## r3 (re-challenge: correctness SOLID, robustness SOLID; minors folded) — amends r2 +- Dir rule: `.claude/memory` present (`-e` or `-L`) but `! -d` or `! -x` → + BAD with its own stderr line `memory: .claude/memory: not a searchable + directory`; absent only when neither `-e` nor `-L` holds AND `.claude` + (if present) is searchable, else BAD. +- Healthy output byte-identical: print a registry's table only after the + read; rows printed only when non-empty (`[ -n "$rows" ] && printf + '%s\n' "$rows"`), then the trailing blank line as today. Test: full + `index` output on the shared healthy $FIX equals a capture taken with the + pre-fix logic (store the expected text literally in the test). +- Usage line lib/memory.sh:12: name the contract `index [<kind>]` → with a + kind rc 2 on an unreadable registry; without, bad registries skipped + with a stderr line, rc 0. +- agents/handover-doc-writer.md:120: one sentence: `index decision` rc != 0 + → write `MEMORY: decisions reader unavailable` instead of an empty §6.1. + (5th file in scope.) +- Test placement: SD9f/g/h each on its own `mkproj`, run with `run "$p" -` + (real lib, as SD9c), never `"$S9"` (still the malformed stub). The + memory.test.sh dir/FIFO/no-kind cases use their own `-C` subtree (pattern + v1h, memory.test.sh:320) seeded with one BLK and one LRN entry; the shared + $FIX blockers.md is never touched. +- Skip idiom: after chmod, SKIP when the read still works (`[ -r + blockers.md ]` for SD9g, `[ -x .claude/memory ]` for SD9h), as + push-guard.test.sh:220-222. SD9h restores 700 right after the run + (`chmod 700 … || true`) AND in the EXIT trap before `rm -rf`. +- Residuals (BUGS-FOUND, closing step): empty/unknown status words counted + not-open; unclosed ``` fence hides later entries without a banner line; + `index` reads without the lock while `status`/`_mem_restore` rewrite in + place (truncate then write, memory.sh:262,319): a racing digest can read + an empty file. +FILES (final): lib/memory.sh, hooks/session-start.sh, +lib/tests/session-digest.test.sh, lib/tests/memory.test.sh, +agents/handover-doc-writer.md.