chore: purge transient planning artifacts (BDR-065)

This commit is contained in:
bchanot committed 2026-10-28 19:20:37 +01:00
1 parent 776a417c5c
commit a19b46735e
6 files changed
-1837

No files matched your search

@@ -1,546 +0,0 @@
# Memory v2 write side (phase 4a) Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** `lib/memory.sh` becomes the only writer of `.claude/memory` registries, one status parser and one classifier serve memory.sh and reconcile on v2 registries, this repo's registries move to v2 (no `## Index`), every citer writes through the lib.
**Architecture:** One sourceable bash lib on the `lib/project-rules.sh` skeleton (`-C <dir>`, verbs, rc 2 + named reason). The awk parser lives once in `_MEM_AWK` and is shared by `index`, `upgrade` and `lib/reconcile.sh` (v2 files). Writers serialize through a noclobber lock file in the git common dir. `memory-commit.sh` runs `check --staged` as the chokepoint. Revision r2 (2026-10-28) after a 3-lens challenge: FATAL(2) simplicity, CONCERNS(5) robustness, FATAL(6) correctness, every BLOCKER and MAJOR closed. Revision r3 (2026-10-28) after the confirmation round (CONCERNS(1) / CONCERNS(3) / CONCERNS(3), no BLOCKER): any-level ID allocation, open fence always refused, v1 status as a body line, one verified backup + trap for every writer, token lock with a serialized steal, exact journal key, staged-dir guard.
**Tech Stack:** bash 5, POSIX awk (no gawk-only features, no `{n}` intervals, no byte-count slicing around `—`), git. Tests via `make test`.
**Spec:** `docs/superpowers/specs/2026-10-27-memory-v2-write-design.md` (user-approved 2026-10-27). Contract: `.claude/tasks/contracts/2026-10-27-memory-v2-write-2030.md`.
**Reference implementation (proven r3):** `docs/superpowers/plans/memory-v2-write/` holds `memory.sh`, `memory.test.sh`, `blockers-v2-status.md`, `blockers-v1-dialects.md`. Proven on a `git clone --shared` of this repo through `make test`: suite `PASS=112 FAIL=0` five runs in a row and under `LC_ALL=C` (the 15 r3 checks T14* are red against the r2 lib, 12 of them), 12 concurrent writers starting from a stale lock: 0 overlaps, 12 distinct IDs, no lock left (3 rounds), shellcheck clean, no `# shellcheck disable`, no line over 80 chars. `upgrade` on a copy of this repo's live registries: oracle-green, `check`-green, idempotent, its diff `--staged`-green, 26 statuses and 129 dates materialized, one Index status dropped and named (BDR-012). Task 2, 3 and 4 code below was applied to that clone and run through `make test` (run-reconcile 28 GREEN / 1 RED where the red is T6c, the gitignored `skills/darwin-skill` absent from a clone; run-deterministic 18/18; memory suite with T13 122/122). `_mem_next_id` equals max heading ID + 1 on all 59 registries of the 15 repos on this machine (r2 gave BDR-001 / LRN-001 / BLK-001 on trucks_at_work's `###` registries: duplicates). Task 1 copies the files; do not rewrite them.
## Global Constraints
- Branch `feature/memory-v2-write` (already started, spec at cdc0a47). Never switch, never merge, never push by hand (hooks push).
- Our code: functions ≤ 25 logic lines (see Deviations for awk programs), ≤ 5 locals, ≤ 5 params, lines ≤ 80 chars in `lib/memory.sh`.
- No `# shellcheck disable` anywhere in the diff (floor guard, LRN-234). `# shellcheck source=/dev/null` directives are allowed.
- `/usr/bin/grep` pinned in libs (`MEM_GREP`, LRN-074); no `grep -q` reading a pipe under pipefail (LRN-189); no `sed -i`, `stat -c`, `realpath -m`, `grep -P` (portability census, BDR-110).
- No recursive delete through a variable except the existing `trap 'rm -rf "$FIX"' EXIT` mktemp pattern.
- Hermetic tests run through `make test [suite=…]` only.
- Census-cited strings stay byte-identical: every `CLAUDE.md "Memory registries" (Always English, always caveman)` citation, the CLAUDE.global.md heading `## Memory registries (\`.claude/memory/\`)` and the bold label `**Always English, always caveman**` (doctrine-citers, LRN-166). Do not rewrap a line that holds one.
- CLAUDE.global.md line count must not exceed 333 after the edit.
- Worked examples use fictional 9xx IDs (LRN-073).
- Entry text written to registries is English caveman (BDR-009).
## Deviations from the spec (named for the human gate)
1. **Lock and backup**: the lock is a file created under bash noclobber (`open(O_EXCL)`), not a `mkdir` dir: uutils `mkdir` 0.10 on this host is not atomic (5 concurrent adds lost 2-4 entries). It holds `<epoch> <pid>.<RANDOM>` and is removed only by its owner's token. A lock older than 30 s, or seen empty on 10 consecutive tries (holder died between create and write), is stolen by one waiter at a time (`memory.lock.steal`, itself noclobber, age re-read under it). Every writer (`add`, `status`, `journal`, `upgrade`) runs on a backup of its file verified by `cmp` (rc 2 before any write if the copy is short), restored on failure or on INT/TERM/HUP; the caller's own traps are saved and put back. No EXIT trap: a sourced lib must not own the caller's EXIT. **Residuals for the gate:** (a) a holder alive but slower than 30 s loses the lock to a stealer and both write (its token no longer matches, so it never removes the new lock); (b) a stealer that dies holding `memory.lock.steal` makes the next waiter clear it once older than 30 s; two waiters doing that at the same moment can both enter the steal section. Both need a crash or a 30 s stall; a write lost that way shows as a `check` culprit (duplicate ID) or a missing entry, never silently in v2.
2. **`journal` takes no `--date`**: `MEMORY_DATE` already pins the date for tests.
3. **`upgrade` body wins**: an Index status reaches the body only when the body has none, or when the Index says superseded/deprecated and the body does not. Every other conflicting Index status is dropped and named on stderr (`memory: BDR-012: kept body shipped, dropped Index accepted`, the only one on this repo).
4. **Status word**: a lib-written `**Status (YYYY-MM-DD…)**:` line reads its leading word (`status` requires the text to start with one: "open, reopened by abc"); other labelled lines rank words in `_MEM_WORDS` order, `open` last ("accepted. check OPEN" = accepted). A heading candidate is its `[tag]` only, never the title.
5. **One classifier on v2, the lexical reader kept on v1**: on a v2 registry reconcile classifies by word (`memory_closed`: resolved | superseded | deprecated); `accepted` on a blocker stays open. On a v1 registry reconcile keeps today's lexical reader verbatim: the strict parser, measured on copies of all 13 other projects' blockers, changed the open set of 4 (config `— RESOLVED` title suffix, game `date: … · status:`, zenquality and angelscar356 `**Statut** :`); with the v1 branch the 13 sets are identical to today.
6. **Heading dialects**: `mem_key` accepts `## ID` followed by any non-alphanumeric char (` — `, ` - `, ` | `), so `status` and `--supersedes` work on v1 hyphen and pipe files. ID allocation reads every heading level, fenced or not (`### BDR-001` in trucks_at_work, a stray fence elsewhere), and a v1 add whose ID already sits in any heading is refused. `status` on a `###` registry stays rc 2 "no entry" (loud, not silent). A v1 `add --status s` writes `- **Status**: s` as the first body line instead of a heading tag: the v1 reconcile reader never reads the entry's own heading. The em-dash shape check is v2-only. `upgrade` migrates the measured dialects (Task 8): only headings that fail the v2 shape are rewritten (` - ` and ` | date | ` separators, `###`), a file without frontmatter gets the template's, every blocker verdict is proven against reconcile's v1 reader (a v1-closed entry the strict reader would open gets a `Status (<date>, upgrade)` line; the reverse, the BLK-032..034 false-open fix, is kept and named). It still refuses what the oracle cannot prove (duplicate IDs, `## ID ADDENDUM` headings: game); the banner says `memory.sh check`, never promises an upgrade.
7. **Journal template** carries no `format: 2`: journal.md is not a registry (`check` excludes it). Contract criterion 8 says "every `templates/memory/*.md`": the four registry templates.
8. **awk programs**: an embedded awk program counts as one statement toward the 25-logic-line limit (`_mem_upgrade_text`, `_mem_upgrade_oracle`, `_mem_index_rows` hold 20-30 awk lines). Splitting them would scatter one parser across files.
9. **`--staged` removal rule**: a removed line counts only from the first entry heading down (the spec said any `-` line). The Index sits above the first entry, so Task 7's upgrade commit goes through memory-commit like any memory commit; the diff runs with `-c diff.interHunkContext=0 --no-color --no-ext-diff --no-textconv` so user git config cannot fold or hide hunks. An open code fence always counts as a culprit, even when it predates the commit (it hides headings from allocation).
## Review Focus
1. **Concurrent writers.** The noclobber lock is proven by T6e/T6f (red with the mkdir lock on this host) and T14i (12 writers from a stale lock). Unlock by token (T14g), empty-lock steal (T14h). Every writer restores its verified backup on failure or signal and frees the lock. Residuals named in Deviation 1.
2. **Status words in prose and titles.** "fail-open", "`data:` OPEN", a title saying "DNS resolved", "open again, not resolved by abc": T10b/c/h/i and run-reconcile T8a/b.
3. **Index-only facts at upgrade.** 13 BDR statuses, BDR-038 + BLK-019/020 + 12 LRN supersessions, 129 dates; a stale Index (BDR-012) never overwrites the body and is named. BLK-019/020 must read closed after Task 7 (superseded).
4. **v1 projects keep working.** 13 other repos run this lib through `~/.claude/lib`: v1 writes are lenient, `check` never fails on v1, `--staged` ignores v1, reconcile on v1 is byte-for-byte today's reader (Deviation 5), `status` works on hyphen and pipe headings (T10m-o).
5. **The chokepoint never blocks a legitimate commit.** Only NEW culprits count (a duplicate a merge left behind blocks neither `add` nor a staged append: T7i-k), except an open code fence, which always blocks until fixed (T14e/f); the upgrade commit passes (Index lines sit above the first entry); a refused commit leaves nothing staged.
---
### Task 1: lib/memory.sh, its suite and the parser fixtures
**Files:**
- Create: `lib/memory.sh` (copy of `docs/superpowers/plans/memory-v2-write/memory.sh`)
- Create: `lib/tests/memory.test.sh` (copy of `…/memory.test.sh`)
- Create: `lib/tests/fixtures/blockers-v2-status.md` (copy of `…/blockers-v2-status.md`)
- Create: `lib/tests/fixtures/blockers-v1-dialects.md` (copy of `…/blockers-v1-dialects.md`; used by Task 2)
**Interfaces (produced, used by Tasks 2-7):** `memory_entry_status <file> <ID>` (winning candidate: `[tag]` or the labelled line; rc 1 if none), `memory_status_word <line>` (status word or first 40 chars), `memory_closed <word>` (rc 0 for resolved | superseded | deprecated), `memory_is_v2 <file>`, `memory_check [--staged] [<dir>]` (prints `memory: v1: <file>` per v1 registry on stderr, the banner's input), `memory_add`, `memory_status`, `memory_journal`, `memory_index`, `memory_upgrade`. CLI: `bash lib/memory.sh [-C dir] add|status|journal|index|check|upgrade …`. Env: `MEMORY_DATE`, `MEM_GREP`, `MEM_LOCK_TRIES`.
- [ ] **Step 1: Copy the four files**
```bash
cp docs/superpowers/plans/memory-v2-write/memory.sh lib/memory.sh
cp docs/superpowers/plans/memory-v2-write/memory.test.sh lib/tests/memory.test.sh
cp docs/superpowers/plans/memory-v2-write/blockers-v2-status.md lib/tests/fixtures/blockers-v2-status.md
cp docs/superpowers/plans/memory-v2-write/blockers-v1-dialects.md lib/tests/fixtures/blockers-v1-dialects.md
chmod +x lib/memory.sh lib/tests/memory.test.sh
```
- [ ] **Step 2: Run the suite and the static checks**
Run: `make test suite=lib/tests/memory.test.sh` three times → each ends `PASS=112 FAIL=0` and `all suites green` (T6e and T14i races must be stable).
Run: `shellcheck lib/memory.sh lib/tests/memory.test.sh && awk 'length > 80' lib/memory.sh` → no output after shellcheck.
Run: `make test suite=lib/tests/portability-census.test.sh` → green.
- [ ] **Step 3: Commit**
```bash
git add lib/memory.sh lib/tests/memory.test.sh lib/tests/fixtures/blockers-v2-status.md lib/tests/fixtures/blockers-v1-dialects.md
git commit -m "feat(memory): lib/memory.sh single registry writer — add/status/journal/index/check/upgrade, shared status parser, noclobber lock"
```
---
### Task 2: reconcile reads v2 status through the shared parser and classifier
**Files:**
- Modify: `lib/reconcile.sh` (source line after `RECONCILE_GREP=`; `reconcile_blk_current_status` and `reconcile_blk_open` with their comments)
- Modify: `lib/tests/run-reconcile.sh` (T8 block before the final summary line)
- Modify: `skills/reconcile/SKILL.md:25` and `:54`
**Interfaces:** consumes `memory_is_v2`, `memory_entry_status`, `memory_status_word`, `memory_closed`. `reconcile_blk_current_status` and `reconcile_blk_open` keep their signatures.
- [ ] **Step 1: Write the failing test** — insert before the `echo; echo "================ $pass GREEN` line of `lib/tests/run-reconcile.sh`:
```bash
echo; echo "=== T8 shared parser — header [tag] + labelled lines, prose never (BLK-032..034) ==="
v2="$FIX/blockers-v2-status.md"
open_v2=$(reconcile_blk_open "$v2" | cut -f1 | sort | tr '\n' ' ')
if [ "$open_v2" = "BLK-040 BLK-041 BLK-042 BLK-043 BLK-044 " ]; then ok "T8a open = {040..044}: 032..034 and 008 closed, accepted stays open"; else no "T8a open = [$open_v2], expected {040,041,042,043,044}"; fi
case "$(reconcile_blk_current_status "$v2" BLK-034)" in
'[resolved]') ok "T8b BLK-034 status = its own header tag, title never read";;
*) no "T8b BLK-034 read from prose (fail-open), not the header tag";;
esac
v1d="$FIX/blockers-v1-dialects.md"
open_v1=$(reconcile_blk_open "$v1d" | cut -f1 | tr '\n' ' ')
if [ "$open_v1" = "BLK-002 " ]; then ok "T8c v1 hyphen and pipe headings still parsed"; else no "T8c v1 dialects open = [$open_v1], expected {002}"; fi
v1w=$(mktemp -d)
mkdir "$v1w/.claude" "$v1w/.claude/memory"
printf '# Blockers\n' > "$v1w/.claude/memory/blockers.md"
printf -- '- **Cause**: `x`\n' > "$v1w/b.md"
bash "$REPO/memory.sh" -C "$v1w" add blocker --title fixed \
--body-file "$v1w/b.md" --status resolved >/dev/null 2>&1
open_v1w=$(reconcile_blk_open "$v1w/.claude/memory/blockers.md" | cut -f1)
if [ -z "$open_v1w" ]; then ok "T8d lib-written v1 blocker --status resolved reads closed"; else no "T8d lib-written v1 blocker reads open [$open_v1w]"; fi
rm -f "$v1w/.claude/memory/blockers.md" "$v1w/b.md"
rmdir "$v1w/.claude/memory" "$v1w/.claude" "$v1w"
```
- [ ] **Step 2: Run, expect red** — `make test suite=lib/tests/run-reconcile.sh` → T8a and T8b red (today: 032..034 open, BLK-034 read from prose).
- [ ] **Step 3: Implement** — in `lib/reconcile.sh`, right after the `RECONCILE_GREP=…` line add:
```bash
# the status parser and classifier are shared with lib/memory.sh (BDR-125 4a)
# shellcheck source=/dev/null
. "$(dirname "${BASH_SOURCE[0]}")/memory.sh"
```
Replace everything from the comment `# --- registry status: LAST status-bearing line wins …` through the closing `}` of `reconcile_blk_open` by:
```bash
# --- registry status: LAST candidate wins (the BLK-008 trap A fell into) ---
# $1 blockers file, $2 id. A v2 registry (lib/memory.sh): the entry's own
# header `[tag]` or a labelled body line, never a status word in prose or in
# the title (the BLK-032..034 false-open). A v1 registry keeps the lexical
# reader below: its dialects (title suffix `— RESOLVED`, `date: … · status:`,
# `**Statut** :`) carry status where the strict parser cannot see it.
reconcile_blk_current_status() {
if memory_is_v2 "$1"; then memory_entry_status "$1" "$2"; return; fi
# v1: drop ALL `## BLK-` header lines first: the range is inclusive of the
# NEXT entry's header, and a sibling header may carry a status word.
sed -n "/^## ${2} /,/^## BLK-/p" "$1" \
| "$RECONCILE_GREP" -v '^## BLK-' \
| "$RECONCILE_GREP" -iE 'status|RESOLVED|REVERTED|upstream|resolved|[^a-z]open' \
| tail -1
}
# blockers whose CURRENT status does not close them → "id<TAB>status".
# v2: memory_closed (resolved | superseded | deprecated); v1: the substring.
reconcile_blk_open() {
local id st v2=""
memory_is_v2 "$1" && v2=1
for id in $(reconcile_enumerate_ids "$1" BLK); do
st=$(reconcile_blk_current_status "$1" "$id")
if [ -n "$v2" ]; then
memory_closed "$(memory_status_word "$st")" && continue
else
case "$st" in *RESOLVED*|*resolved*) continue ;; esac
fi
printf '%s\t%s\n' "$id" "$st"
done
}
```
Header comment: insert one line right after line 12 (`# preaches — the recursive-coherence test (run-reconcile.sh T1) reds if this is broken.`): `# v2 registries carry no Index at all (lib/memory.sh); v1 ones still may.`
- [ ] **Step 4: Run, expect green** — `make test suite=lib/tests/run-reconcile.sh` → `29 GREEN / 0 RED` (T1-T7 unchanged, T8a/b/c/d green; T8d is red against the r2 lib, which put the status in the heading tag the v1 reader drops). `make test suite=lib/tests/run-review-guards.sh` → green (G4: T8 reads fixtures only).
- [ ] **Step 5: Skill lines** — `skills/reconcile/SKILL.md:54`: `→ 25/25,` → `→ 29/29,`. `skills/reconcile/SKILL.md:25`: replace `` (`reconcile_oracle_*`, `reconcile_blk_current_status` = last block wins) `` by `` (`reconcile_oracle_*`, `reconcile_blk_current_status` = last candidate wins: header `[tag]` or a labelled status line on a v2 registry via `lib/memory.sh`, today's lexical reader on v1) ``.
- [ ] **Step 6: Commit**
```bash
git add lib/reconcile.sh lib/tests/run-reconcile.sh skills/reconcile/SKILL.md
git commit -m "fix(reconcile): v2 blocker status through the shared memory.sh parser and classifier — BLK-032..034 no longer false-open; v1 reader unchanged"
```
---
### Task 3: memory-commit.sh refuses a staged in-place edit or new culprit (rc 6)
**Files:**
- Modify: `lib/memory-commit.sh` (usage comment, `MC_MEMORY_SH`, `commit_memory` right after `git add`)
- Modify: `lib/tests/run-deterministic.sh` (block before the final `echo` + `printf 'RESULT: …'`)
- Modify: `lib/capitalize-commit.md` (rc table)
- [ ] **Step 1: Write the failing tests** — insert right before the final `echo` / `printf 'RESULT: %d passed, %d failed\n' "$PASS" "$FAIL"` lines of `lib/tests/run-deterministic.sh`:
```bash
echo "== check --staged chokepoint (v2 registry, phase 4a)"
d="$(new_repo)"
printf -- '---\nformat: 2\ntype: decisions_registry\nentry_prefix: BDR\n---\n\n## BDR-001 — kept (2026-10-27)\n- **Status**: accepted\n' \
> "$d/.claude/memory/decisions.md"
git -C "$d" add -A && git -C "$d" commit -qm v2
head_before=$(git -C "$d" rev-parse HEAD)
sed 's/kept/rewritten/' "$d/.claude/memory/decisions.md" > "$d/x.tmp" \
&& cat "$d/x.tmp" > "$d/.claude/memory/decisions.md"
out="$(cd "$d" && bash "$HELPER" commit "chore(memory): bad" 2>/dev/null)"; rc=$?
staged="$(git -C "$d" diff --cached --name-only)"
if [ "$rc" -eq 6 ] && [ -z "$out" ] && [ -z "$staged" ] && [ "$(git -C "$d" rev-parse HEAD)" = "$head_before" ]; then ok "in-place edit of a v2 entry → rc 6, nothing committed, nothing staged"; else ko "rc=$rc out=[$out] staged=[$staged] — in-place edit committed or left staged"; fi
git -C "$d" checkout -q HEAD -- .claude/memory/decisions.md
printf '\n## BDR-002 — added (2026-10-27)\nbody\n' >> "$d/.claude/memory/decisions.md"
out="$(cd "$d" && bash "$HELPER" commit "chore(memory): BDR-002" 2>/dev/null)"; rc=$?
if [ "$rc" -eq 0 ] && [ -n "$out" ]; then ok "append to a v2 registry → committed"; else ko "append refused rc=$rc"; fi
```
(Existing tests write `baseline` registries with no frontmatter: v1, skipped by the check, unchanged and green.)
- [ ] **Step 2: Run, expect red** — `make test suite=lib/tests/run-deterministic.sh` → the rc 6 test fails (today rc 0, the edit is committed).
- [ ] **Step 3: Implement** — in `lib/memory-commit.sh`:
- after `MC_PATHS=(".claude/memory" ".claude/tasks")` add `MC_MEMORY_SH="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)/memory.sh"`;
- in `commit_memory`, right after `git add -- "${changed[@]}"`, insert:
```bash
# Chokepoint (BDR-125 phase 4a): a staged v2 registry may only grow and
# never gains a new culprit (duplicate ID, bad heading, open fence). v1
# registries are skipped. Unstage on refusal so no later plain commit
# sweeps the refused change in.
if [ -d .claude/memory ] \
&& ! bash "$MC_MEMORY_SH" check --staged .claude/memory; then
git reset -q -- "${changed[@]}"
echo "memory-commit: REFUSED — memory.sh check --staged failed (above);" \
"NOTHING committed, nothing left staged." >&2
return 6
fi
```
- usage comment line becomes two lines: `# memory-commit.sh commit "<message>" # surgical commit; exit 0 ok/no-op, 3 unsafe` / `# # state, 5 commit rejected, 6 check refused`.
- [ ] **Step 4: Run, expect green** — `make test suite=lib/tests/run-deterministic.sh` → `RESULT: 18 passed, 0 failed`.
- [ ] **Step 5: Document rc 5 and rc 6** — `lib/capitalize-commit.md` step 3 "Report by (rc, mem_hash)", after the `rc 3` bullet:
```
- rc 5 → `git commit` rejected (hook, protected branch,
signing); nothing committed, surface stderr.
- rc 6 → `memory.sh check --staged` refused, nothing
committed, nothing left staged. Two causes,
named on stderr: a line removed inside an
existing v2 entry (only appends pass), or a NEW
culprit (duplicate ID, heading shape); an open
code fence counts even when it predates the
commit. Fix the file, then commit the fix with
/commit-change; never bypass the helper.
```
- [ ] **Step 6: Commit**
```bash
git add lib/memory-commit.sh lib/tests/run-deterministic.sh lib/capitalize-commit.md
git commit -m "feat(memory): memory-commit refuses a staged in-place edit or new culprit in a v2 registry (rc 6, unstaged); rc 5/6 documented"
```
---
### Task 4: v2 templates and the registry v1 banner line
**Files:**
- Modify: `templates/memory/{decisions,learnings,blockers,evals}.md` (journal.md unchanged, Deviation 7)
- Modify: `hooks/session-start.sh` (before `# Version check: compare local vs remote (non-blocking)`)
- Modify: `lib/tests/memory.test.sh` (T13, before the final `echo "PASS=…"`)
- Modify: `agents/onboarder.md:126`
- [ ] **Step 1: Write the failing test** — insert before `echo "PASS=$pass FAIL=$fail"` in `lib/tests/memory.test.sh`:
```bash
# T13 templates are born v2; the session banner names a v1 project only
for t in decisions learnings blockers evals; do
check "T13-template-$t-v2" "$(sed -n 2p "$ROOT/templates/memory/$t.md")" 'format: 2'
check "T13b-template-$t-no-index" "$(grep -c '^## Index$' "$ROOT/templates/memory/$t.md")" 0
done
banner() { (cd "$1" && SESSION_START_OFFLINE=1 bash "$ROOT/hooks/session-start.sh" \
</dev/null 2>/dev/null) | grep -c "${2:-registry v1}"; }
check T13c-banner-v1-v2 "$(banner "$FIX/v1h" 'registry v1: 1 file(s) (memory.sh check)')/$(banner "$FIX")" 1/0
cp "$FIX/v1h/.claude/memory/blockers.md" v1h.bak
printf -- '---\nformat: 2\n---\n' > "$FIX/v1h/.claude/memory/blockers.md"
check T13d-banner-flips-off "$(banner "$FIX/v1h")" 0
cat v1h.bak > "$FIX/v1h/.claude/memory/blockers.md"
```
(`$FIX/v1h` is the v1 pipe/hyphen project T10 built; `$FIX/.claude/memory` is v2. T13c reads both projects in one check (`1/0`), red until the banner exists; T13d turns the same v1 project v2 and expects the line gone. The hook resolves `memory.sh` next to itself, so the test exercises `$ROOT/lib/memory.sh`, never the installed copy.)
- [ ] **Step 2: Run, expect red** — `make test suite=lib/tests/memory.test.sh` → 9 checks red (the eight template checks and T13c); T13d is green before and after, it guards the flip-off once T13c is green.
- [ ] **Step 3: Templates** — in each of the four registry templates: insert `format: 2` as line 2 (right after the opening `---`); delete `## Index`, the blank line after it, the two table lines and the blank line after them; replace the `<!-- Append entries below. Template: … -->` comment by (shown for blockers; the heading line is indented two spaces so no line starts with `## `):
```
<!-- Written only by `bash ~/.claude/lib/memory.sh add blocker --title "<friction>"
--body-file <file> [--status open]` (it allocates the ID). Entry shape:
## BLK-NNN — <friction> [open] (YYYY-MM-DD)
- **Friction**: <what was blocked>
- **Real cause**: <root cause>
- **Solution**: <workaround or fix>
Later status: `bash ~/.claude/lib/memory.sh status BLK-NNN "resolved <hash>"`.
-->
```
decisions → `decision`, `<title>`, `[accepted]`, labels Decision / Why / Rejected alternatives / Reference, later status `superseded by BDR-NNN`; learnings → `learning`, `<abstract pattern>`, no tag, labels Pattern / Context / Future application, no "Later status" line; evals → `eval`, `<output>`, `[keep]`, labels Output / Method / Anomalies / Action.
- [ ] **Step 4: Banner** — in `hooks/session-start.sh`, right before `# Version check: compare local vs remote (non-blocking)`:
```bash
# Registry v1 (BDR-125 phase 4a): a project registry without `format: 2`.
# The lib names each v1 registry on stderr (`memory: v1: <file>`).
_mem_lib="$(dirname "${BASH_SOURCE[0]}")/../lib/memory.sh"
if [ -f "$_mem_lib" ] && [ -d .claude/memory ]; then
_v1=$(bash "$_mem_lib" check .claude/memory 2>&1 >/dev/null \
| grep -c '^memory: v1:' || true)
if [ "${_v1:-0}" -gt 0 ]; then
printf "│ ⚠️ %-44s│\n" "registry v1: ${_v1} file(s) (memory.sh check)"
fi
unset _v1
fi
unset _mem_lib
```
- [ ] **Step 5: Onboarder line** — `agents/onboarder.md:126`: `(YAML schema + empty index + inline template comment)` → `(YAML schema with \`format: 2\` + inline template comment; no Index, entries go through \`lib/memory.sh\`)`.
- [ ] **Step 6: Run, expect green** — `make test suite=lib/tests/memory.test.sh` → `PASS=122 FAIL=0`. `make test suite=lib/tests/push-guard.test.sh` → green: its banner checks grep specific strings. From this task until Task 7 this repo's own banner shows `registry v1: 4 file(s) (memory.sh check)` (its registries are still v1); that is expected.
- [ ] **Step 7: Commit**
```bash
git add templates/memory hooks/session-start.sh lib/tests/memory.test.sh agents/onboarder.md
git commit -m "feat(memory): templates born v2 (format: 2, no Index); session banner names a v1 registry"
```
---
### Task 5: flows write through the lib (one WRITE section, cited everywhere)
**Files:** `lib/capitalize-commit.md` (new WRITE section), `skills/capitalize/SKILL.md` (STEP 2 `:143`, STEP 4 items 1-4, STEP 5 bullets, STEP 5B rc list), `skills/feat/SKILL.md:248`, `skills/bugfix/SKILL.md:275`, `skills/hotfix/SKILL.md:234`, `skills/ship-feature/SKILL.md:273-274`, `skills/init-project/SKILL.md:301-303`, `agents/commit-changer.md:220-223`, `skills/onboard/SKILL.md` S7, `lib/analyze-before-plan.md:42-43` and `:100-102`, `agents/analyzer.md:98-99`, `CLAUDE.global.md`.
- [ ] **Step 1: The one WRITE section** — in `lib/capitalize-commit.md`, first the intro: `Inline snippet. Include at the END of any dev flow's CAPITALIZE step, AFTER the` / `approved registry / journal / TODO entries are written. It commits ONLY the` → `Inline snippet for any dev flow's CAPITALIZE step: § WRITE says how the approved` / `registry and journal entries are written, then the rest commits ONLY the` (the two lines after it unchanged), and `decide WHAT to write are unchanged and run before this snippet. Only the COMMIT` / `of the already-approved entries is automated here.` → `decide WHAT to write are unchanged and run before this snippet; § WRITE then` / `writes them through lib/memory.sh and the COMMIT is automated here.`. Then insert before `## DO`:
```
## WRITE (before the commit)
Registry entries and journal lines are written only by `lib/memory.sh`,
never by Edit or append; there is no `## Index` to update.
- Entry: caveman body to a scratch file, then
`bash "$HOME/.claude/lib/memory.sh" [-C <project root>] add
<decision|learning|blocker|eval> --title "<title>" --body-file <file>
[--status <status>] [--supersedes <ID>]`. One call per entry; it
allocates the ID under a lock and prints it. A blocker body quotes ≥1
error in backticks. `-C` when the cwd is not the project root.
- Status change on an existing entry:
`bash "$HOME/.claude/lib/memory.sh" status <ID> "<word> …"`, the text
starting with a status word (`resolved abc1234`, `open, reopened by …`,
`superseded by BDR-NNN`).
- Journal: `bash "$HOME/.claude/lib/memory.sh" journal "<line>"`.
- rc 2 names its reason (title chars, empty body, a status not starting
with a status word, an open code fence in the body or the registry,
unknown ID, lock busy): fix the input and re-run.
```
- [ ] **Step 2: capitalize**
- `:143` `(Index + bodies)` → `(headings + bodies)`.
- STEP 4 items 1-4 (from `1. Read the target registry file.` through `match that file's header row).`) → one item: `1. Write each approved entry per \`lib/capitalize-commit.md\` § WRITE (\`memory.sh add\`, one call each; a resolved blocker: \`memory.sh status <ID> "resolved <hash>"\`).` Old item 5 (caveman) stays, renumbered 2.
- STEP 5: the two bullets `- Heading exists → append a bullet.` / `- Missing → create …` → `- \`bash "$HOME/.claude/lib/memory.sh" journal "<line>"\` per bullet (it creates today's heading when missing).`
- STEP 5B step 3: after the `**rc 3**` bullet add `- **rc 5 / rc 6** → nothing committed; surface the helper's stderr; meaning and recovery in \`lib/capitalize-commit.md\` (rc 6: fix the registry, then /commit-change). STEP 6 says NOT committed.`
- [ ] **Step 3: flow citations** (each a one-line replacement; the **Language rule** lines untouched):
- feat `:248` (`Always append a 1-line entry to today's heading in \`.claude/memory/journal.md\`.`) → `Approved entries and the always-written 1-line journal entry: per \`lib/capitalize-commit.md\` § WRITE (\`memory.sh add\` / \`memory.sh journal\`).`
- bugfix `:275` → `4. Write approved entries per \`lib/capitalize-commit.md\` § WRITE: a new blocker \`add blocker … --status resolved\`, an existing one now fixed \`status <BLK-ID> "resolved <hash>"\`, an LRN \`add learning …\` (no status); the journal line \`memory.sh journal\`.`
- hotfix `:234` → `Always append a 1-line journal entry (even trivial hotfix — journal is timeline, not signal) and any approved BLK/LRN per \`lib/capitalize-commit.md\` § WRITE.`
- ship-feature `:273-274` → `4. Write approved entries per \`lib/capitalize-commit.md\` § WRITE (\`memory.sh add\`, one call each; no Index to update).` / `5. Journal line: \`memory.sh journal\` (same section).`
- init-project `:301-303` → `3. Write approved entries to the registries bootstrapped at STEP 5 (in the root commit), and the journal line, per \`lib/capitalize-commit.md\` § WRITE.`
- commit-changer `:220-223` (Phase 4 item 2) → `2. Write each resolved entry and one journal line for the batch per \`$HOME/.claude/lib/capitalize-commit.md\` § WRITE (\`memory.sh -C <repo root> add …\`, \`memory.sh -C <repo root> journal …\`; no Index to update).`
- onboard S7: the source text spans a line break, `append to that` (end of the line starting `S7 — AFTER.`) + newline + `project's \`.claude/memory/journal.md\` under today's date:`. Replace the tail `append to that` / `project's \`.claude/memory/journal.md\` under today's date:` by `append to that` / `project's journal (\`bash "$HOME/.claude/lib/memory.sh" -C <ROOT> journal\`):` — same two-line wrap, the quoted line text after it unchanged.
- [ ] **Step 4: analyze-before-plan + analyzer**
- `lib/analyze-before-plan.md:42-43`: `Do NOT read the \`## Index\` table: it drifts (entries land in the body, the manual Index update lapses — measured 32-40% missing on a mature repo); headings cannot.` → `Do NOT read a \`## Index\` table (v1 registries may still carry one; it drifted 32-40% on a mature repo; v2 has none); headings cannot drift.`
- `:100-102`: `No write, no Index update, no memory mutation.` → `No write, no memory mutation.`; `Index backfill, if ever wanted, is \`/prune-memory\` passe D — never this snippet.` → `Registry writes go through \`lib/memory.sh\`, never this snippet.`
- `agents/analyzer.md:98-99`: `Index backfill or new entries are never your job` → `new entries or status lines are never your job (writes go through lib/memory.sh)`.
- [ ] **Step 5: CLAUDE.global.md** (line-neutral):
- `Append-only: never rewrite past entries; curation (merge, supersede,` / `compress) only via \`/prune-memory\`.` → `Append-only, written only through \`bash ~/.claude/lib/memory.sh\` (add,` / `status, journal), never by Edit; curation only via \`/prune-memory\`.`
- `exact. Pattern \`[thing] [action] [reason]. [next step].\` Registries load` / `every session; caveman cuts ~40% of the tokens with no substance lost.` → `exact. Pattern \`[thing] [action] [reason]. [next step].\` Planning flows` / `read the registries; caveman cuts ~40% of every read, no substance lost.`
- [ ] **Step 6: Verify** — `grep -rn 'Index' skills/capitalize/SKILL.md skills/feat/SKILL.md skills/bugfix/SKILL.md skills/hotfix/SKILL.md skills/ship-feature/SKILL.md skills/init-project/SKILL.md agents/commit-changer.md` → no line telling a writer to update an Index. `wc -l < CLAUDE.global.md` → ≤ 333. `make test suite=lib/tests/doctrine-citers.test.sh` and `make test suite=lib/tests/effort-routing.test.sh` → green.
- [ ] **Step 7: Commit**
```bash
git add lib/capitalize-commit.md skills/capitalize/SKILL.md skills/feat/SKILL.md skills/bugfix/SKILL.md skills/hotfix/SKILL.md skills/ship-feature/SKILL.md skills/init-project/SKILL.md agents/commit-changer.md skills/onboard/SKILL.md lib/analyze-before-plan.md agents/analyzer.md CLAUDE.global.md
git commit -m "docs(memory): one WRITE section in capitalize-commit.md, every flow cites it; Index steps removed; doctrine names the single writer"
```
---
### Task 6: /prune-memory on v2 (no § D, status through the lib, check as verify)
**Files:** `skills/prune-memory/SKILL.md` (§ A `:83-85`, § D `:111-115`, STEP 2 example, STEP 3 list, `:177`, STEP 4 block, report sample, failure row, `:322-323`), `skills/prune-memory/tests/run-deterministic.sh` (RED-6), new `skills/prune-memory/tests/fixtures/red6-check/.claude/memory/decisions.md`, `git rm` of `skills/prune-memory/tests/fixtures/red6-orphan/.claude/memory/decisions.md`, `skills/prune-memory/test-prompts.json` (id 1).
- [ ] **Step 1: Write the failing test** — replace the whole RED-6 block (from `# ---- RED-6:` through its closing `fi`) by:
```bash
# ---- RED-6: STEP 4 verify runs memory.sh check (duplicate ID caught) --------
# v2 registries carry no Index; the structural verify is `memory.sh check`
# (heading shape, unique IDs). HOME is pinned to a sandbox whose .claude/lib
# is this repo's lib, so the run never depends on the machine's ~/.claude.
S6="$SANDBOX/red6"; mkdir -p "$S6/.claude/memory" "$S6/home/.claude"
ln -s "$HERE/../../../lib" "$S6/home/.claude/lib"
cp "$HERE/fixtures/red6-check/.claude/memory/decisions.md" \
"$S6/.claude/memory/decisions.md"
extract_block "STEP 4" > "$S6/step4.sh"
out="$( cd "$S6" && HOME="$S6/home" bash step4.sh 2>&1 )"
if printf '%s\n' "$out" | grep -qE 'duplicate BDR-009'; then
green 6 "verify runs memory.sh check and names the duplicate BDR-009"
else
red 6 "verify misses the duplicate BDR-009 (no memory.sh check in STEP 4)"
fi
```
Fixture `skills/prune-memory/tests/fixtures/red6-check/.claude/memory/decisions.md`:
```
---
format: 2
type: decisions_registry
entry_prefix: BDR
---
# Decisions registry (BDR)
## BDR-009 — first (2026-06-01)
- **Status**: accepted
## BDR-009 — duplicate, the trap (2026-06-02)
- **Status**: accepted
```
`git rm -q skills/prune-memory/tests/fixtures/red6-orphan/.claude/memory/decisions.md`.
- [ ] **Step 2: Run, expect red** — `make test suite=skills/prune-memory/tests/run-deterministic.sh` → `RED-6: RED`.
- [ ] **Step 3: SKILL.md edits**
- § A `:83-85` → `Decisions whose body names a successor ("superseded by <ID>", "Supersedes [[<ID>]]" on the newer one) but whose current status (\`bash "$HOME/.claude/lib/memory.sh" index decision\`) still reads \`accepted\` → propose \`memory.sh status <ID> "superseded by <that-ID>"\`.`
- Delete § D (`### D. Index drift` and its two bullets).
- STEP 2 example: `→ fix Index: status = "superseded by BDR-903"` → `→ memory.sh status BDR-902 "superseded by BDR-903"`; delete `[D. Index drift]` + `(none)`; `(all / a / b / c / d / edit <ID> / skip)` → `(all / a / b / c / edit <ID> / skip)`.
- STEP 3 list (replacing items 1-3; old item 4 becomes 3, unchanged):
```
1. **Status flag updates** — `bash "$HOME/.claude/lib/memory.sh" status <ID>
"<word> …"` appends a dated status line (text starts with a status word:
`deprecated, no follow-up after 90 days`); the body above stays verbatim.
2. **Merges** — write the merged body to a scratch file, then
`bash "$HOME/.claude/lib/memory.sh" add <kind> --title "<title>"
--body-file <file> --supersedes <first source>` (next-free ID, forward
link, the first source marked superseded); each other source:
`memory.sh status <ID> "superseded by <new-ID>"`. Source bodies stay
verbatim for history. Merged body:
```
followed by the existing merged-body sub-bullets. Delete `After each write, regenerate Index from body when rows changed.`
- STEP 4 block: delete the `PREFIX_MAP` declaration, its comment and the `# All body entries have Index rows; no orphans` loop through its `done`; in their place:
```bash
# Structure: heading shape + unique IDs + no open fence (v2 registries; a
# v1 one is named and skipped). Same verify the writer runs after every add.
bash "$HOME/.claude/lib/memory.sh" check .claude/memory \
|| echo "CHECK FAILED: fix the lines above before certifying"
```
- Report sample `INDEX SANITY: OK` → `CHECK: OK`; `NEXT: review \`git diff .claude/memory/\`, then \`/commit-change\`` unchanged (curation edits are removals: they never go through memory-commit's chokepoint).
- Failure row `| Index sanity FAILED at STEP 4 | …` → `| \`memory.sh check\` FAILED at STEP 4 | Print its culprit lines. Do NOT auto-fix — user re-runs or hand-edits. |`.
- `:322-323` fixtures list `red6-orphan` → `red6-check`.
- [ ] **Step 4: test-prompts.json** id 1 `expected` → `"Skill runs PRECHECK (refuses if working tree dirty on .claude/memory/), audits all 5 registries for A) obsolete/superseded entries B) similar merge candidates C) bloated prose, presents the per-registry PRUNE PLAN with category-level approval gate, applies only approved changes (status lines and merges through lib/memory.sh, never hard-delete), then runs memory.sh check and the fidelity census at STEP 4."`
- [ ] **Step 5: Run, expect green** — `make test suite=skills/prune-memory/tests/run-deterministic.sh` → RED-1..7 GREEN (RED-5's journal-only sandbox has no registry, `check` prints nothing). `grep -n 'Index' skills/prune-memory/SKILL.md` → no writer step mentions an Index.
- [ ] **Step 6: Commit**
```bash
git add skills/prune-memory
git commit -m "feat(prune-memory): v2 registries — § D dropped, status and merges through memory.sh, STEP 4 verify = memory.sh check"
```
---
### Task 7: upgrade this repo's registries (the one curation)
**Files:** `.claude/memory/{decisions,learnings,blockers,evals}.md` (by the lib only). `upgrade` already transforms on a temp copy and runs its oracle before replacing any file; the registries are tracked, so no dry run.
- [ ] **Step 0: Clean memory precondition** — `git diff --quiet HEAD -- .claude/memory .claude/tasks || { echo "STOP: uncommitted memory or tasks; commit them first"; exit 1; }`. The rollback below and the memory-commit sweep both rely on it.
- [ ] **Step 1: Upgrade in place and commit through the chokepoint**
```bash
bash lib/memory.sh upgrade
bash lib/memory.sh check && echo CHECK-OK
bash "$HOME/.claude/lib/memory-commit.sh" commit "chore(memory): registries v2 — Index removed, Index-only dates and statuses materialized (memory.sh upgrade)"
```
Expected: four `memory: upgraded …` lines and one stderr line `memory: BDR-012: kept body shipped, dropped Index accepted`; `CHECK-OK`; memory-commit prints a hash (Index lines sit above the first entry, every other change is an insertion). If `upgrade` returns rc 2: each file is already restored from its verified backup; `git checkout -- .claude/memory` (safe only after Step 0) puts any upgraded sibling back, report the stderr, stop.
- [ ] **Step 2: Verify the live facts**
Run: `bash -c '. lib/reconcile.sh; reconcile_blk_open .claude/memory/blockers.md | cut -f1 | tr "\n" " "'` → exactly `BLK-001 BLK-003 BLK-017 BLK-018 BLK-021 BLK-022 BLK-029 ` (measured on an upgraded copy 2026-10-28: 032..034 resolved, 019/020 superseded = closed).
Run: `bash lib/memory.sh index blocker | grep -E 'BLK-0(19|20|32|33|34)'` → dates `2026-09-01 2026-09-02 2026-10-19 2026-10-21 2026-10-22`, statuses superseded, superseded, resolved ×3.
Run: `grep -c '^## Index' .claude/memory/*.md` → 0 everywhere; `make test suite=lib/tests/memory.test.sh` → T12 green; the session banner no longer shows `registry v1`.
---
## Final verification (main loop, after Task 7)
`make test` all suites green; `shellcheck lib/memory.sh lib/reconcile.sh lib/memory-commit.sh hooks/session-start.sh`; `bash lib/memory.sh check`; `git status --short` clean except the user-owned `settings.json`. No other project changed: `git -C <dir> status --short .claude/memory` empty, and `bash -c '. lib/reconcile.sh; reconcile_blk_open <dir>/.claude/memory/blockers.md'` equal to the pre-branch reader, for each of:
```
/home/bchanot/Documents/config
/home/bchanot/Documents/faunosteo
/home/bchanot/Documents/game
/home/bchanot/Documents/game-deploy
/home/bchanot/Documents/integration_alphalink
/home/bchanot/Documents/robin_petier
/home/bchanot/Documents/zenquality
/home/bchanot/repos/bchanot/angelscar356
/home/bchanot/repos/bchanot/bchanot-cv
/home/bchanot/repos/bchanot/for_you
/home/bchanot/repos/bchanot/game-deploy
/home/bchanot/repos/bchanot/gitea-deploy
/home/bchanot/repos/bchanot/nuit-folle
/home/bchanot/repos/bchanot/trucks_at_work
```
(pre-branch reader: `git show develop:lib/reconcile.sh > <tmp>` then source `<tmp>`; measured 2026-10-28 on copies: 13 of 13 distinct files identical.)
---
### Task 8: `upgrade` migrates every v1 dialect (user ask at the gate, 2026-10-28)
User at STEP 3: "Il faudrait un système de migration pour que les fichiers v1 deviennent des fichiers v2 pour tout harmoniser". Same files, same `.claude/memory/` place, versioned and pushed with the code; v2 = `format: 2` + no Index.
**Files:** `lib/memory.sh` (`upgrade` path only), `lib/tests/memory.test.sh` (new T15 block), `lib/tests/fixtures/blockers-v1-dialects.md` (extend if needed).
**Behaviour** (replaces the dialect refusal of Deviation 6 for `upgrade` only):
1. No frontmatter → prepend the matching `templates/memory/<name>.md` frontmatter (with `format: 2`) and keep the file's own body verbatim below it.
2. Heading normalization, entry headings only (`^#+ *PREFIX-[0-9]+`): `## ID - t`, `## ID | date | t`, `### ID — t`, `## ID — t — date` → `## ID — t (date)`; the date comes from the heading, else the Index row, else the first `Date`/`date:` body line, else none. The title text is kept verbatim (only separators change). IDs never change.
3. Status preservation: before rewriting, compute every entry's open/closed verdict with the v1 lexical reader (reconcile's legacy path, blockers) and the status word (all registries); after rewriting, if the strict v2 parser would read a different verdict or no status where the legacy reader had one, append `- **Status (<today>, upgrade)**: <word>` to that entry.
4. Oracle (file untouched on any failure, rc 2, culprit named): same ID set and order; every entry's verdict before == after (blockers via the legacy reader vs `memory_closed`, others by status word when one existed); `check` green; idempotent second run.
5. `upgrade` no longer refuses any of the measured dialects; it refuses only what the oracle cannot prove.
**Tests (T15):** one fixture per dialect (hyphen, pipe, `###`, title-suffix `— RESOLVED`, `date: … · status:`, `**Statut** :`, no frontmatter) → upgraded, `check` green, verdicts preserved, idempotent; a tampered case where the oracle refuses and the file stays byte-identical. Proof on copies (read-only on the real repos): `upgrade` on a copy of each of the 13 other projects' registries is oracle-green; report the per-repo line counts.
**Out of this branch:** applying it to the 13 other repos happens after the merge, one `chore/memory-v2` branch per repo, user approval per repo (phase 0b pattern), committed through `/commit-change` (a heading rename is an in-place edit, memory-commit refuses it by design).
@@ -1,10 +0,0 @@
# Blockers
## BLK-001 - hyphen dialect, resolved
- **Status**: resolved
## BLK-002 | 2026-05-18 | pipe dialect, open
Status: open
## BLK-003 | 2026-05-19 | pipe dialect, resolved
Status: resolved.
@@ -1,56 +0,0 @@
---
format: 2
type: blockers_registry
entry_prefix: BLK
---
# Status parser fixture: BLK-032..034 as written 2026-10-27 (false-open
# before phase 4a), BLK-008 compound (frozen snapshot), BLK-040..042 shapes.
## BLK-008 — gstack ./setup fails on Ubuntu 26.04 — Playwright chromium unsupported
- **Date**: 2026-06-23
- **Friction**: fresh Ubuntu 26.04, `make install` / `make plugin` → "Failed to install browsers / ERROR: Playwright does not support chromium on ubuntu26.04-x64" → "GStack ./setup failed". Non-fatal in our wrapper (warn only) but gstack's browser (`/browse`, `/qa`, design screenshots) is silently dead once gstack is enabled.
- **Real cause**: Playwright 1.58.2 (pinned in the gstack submodule) registry lists `ubuntu20.04/22.04/24.04` only; 26.04 released later → not in list → `getHostPlatform` errors. Pure OS-newness, not an install bug.
- **Solution**: gated `export PLAYWRIGHT_HOST_PLATFORM_OVERRIDE=ubuntu24.04-x64` (ubuntu >24.04 only) before gstack setup + persisted to `.bashrc` for runtime. Playwright then pulls a Chrome-for-Testing fallback build for ubuntu24.04. Verified on 26.04: `ldd` resolves all libs + real headless render OK.
- **Status**: resolved (commit 211c7d4). Residual: exact rev 1208 launch not in-session-tested (sandbox download hung at extraction); proved via sibling rev 1228 same-platform CfT build. Confirm on next real `make plugin`. Proper upstream fix = gstack bumps Playwright to a version that lists ubuntu26.04. See [[LRN-038]].
- **2026-06-23 UPDATE — Solution REVERTED, status downgraded to UPSTREAM/open** (commit b9c3937): the `PLAYWRIGHT_HOST_PLATFORM_OVERRIDE` solution above does NOT work on 26.04. The fallback build downloads to 100% then HANGS at extraction (chrome binary never appears, no headless-shell download starts; reproduced on real machine + sandbox) → turned a 0.5s fast-fail into an install-blocking hang (user Ctrl+C). Reverted to the fast-fail (non-fatal; gstack OFF by default, browser only for /browse,/qa,screenshots). The earlier "verified ldd + headless render" was an isolated test on a sibling already-extracted build (rev 1228) — it masked the rev-1208 install-path hang. **Real fix = upstream**: gstack bumps Playwright to a version that lists ubuntu26.04. Until then gstack's browser is unavailable on 26.04, install completes cleanly. See [[LRN-038]] correction.
- **2026-06-23 FINAL — RESOLVED** (commit 3b8ffb1): gstack browser now works on Ubuntu 26.04. Two layers fixed: (1) bumped gstack's pinned Playwright 1.58.2 → 1.61 (`bun add playwright@latest` in the submodule; 1.61 ships a native ubuntu26.04 build — chromium rev 1228), automated in the installer (`gstack_bump_playwright_if_unsupported`, idempotent, OS-gated); (2) `GSTACK_CHROMIUM_NO_SANDBOX=1` to work around the AppArmor userns restriction (`sysctl kernel.apparmor_restrict_unprivileged_userns=1`), persisted to `.bashrc` + installer Step 9 (sysctl-gated). Verified end-to-end: `browse goto https://example.com` → "Navigated (200)". Caveat: the Playwright bump is a local submodule edit, reset by `git submodule update`, re-applied by the next install. See [[BDR-029]], [[LRN-040]].
---
## BLK-032 — Main loop pinned on Fable in long sessions: session model Fable 1M + downgrade cap 120k + prompt rule `plan` → inline code on Fable xhigh [resolved]
- **Cause**: `~/.claude/settings.json` `"model": "claude-fable-5-1[1m]"` (every session starts on Fable); model-router never moves main above the session model, moves DOWN only under `downgradeMaxTokens` 120000 (LRN-204 cold read) → a long session (faunosteo R4.x, context > 120k) never reaches `implement`/sonnet; prompt rule `(plan|design|architecture…)` → phase plan = best/xhigh each turn ("plan §B.1.7"). No doctrine ceiling: CLAUDE.md allows inline work "doable in a few tool calls", BDR-115 "pin = default, never ceiling".
- **User policy 2026-10-19**: session model Opus 5.5; sonnet writes, opus decides what to write; Fable only for orchestrator reflection/plans and the important audits (security, functional), other judges opus. → next `/feat`: settings model, `judge` split, ceiling rule in CLAUDE.md, BDR superseding part of BDR-066 / BDR-115. Links [[BDR-066]], [[BDR-107]], [[BDR-115]], [[LRN-204]].
- **Solution (2026-10-23)**: feat A+B (BDR-123) + feat C 786ee13 (feature/router-keyword-cap): keyword prompt rules, `ultrathink` floor, derived `orchestrate` dispatch write effort-only routes (`effortRoute`, `belowRun` pattern) → never lift main above session model; held best-tier run keeps its model (per-axis fall-through); `mainModelSlot` drops `turnFloor`. Fable on main only via skill row, `route` tool, `/route`. Docs d2d590f. Links [[LRN-226]], [[EVAL-048]].
## BLK-033 — Guardrails residuals: probe trusted plan `supabase.url`, redirects free of budget, unread bodies read CLOSED; rules 5 FP / 7 misses [resolved]
- **Friction**: GATE 2 of the a11y split (f586304) left a MEDIUM + 3 LOW on probe.py, opus review left Minors on the rules. Parked in TODO, fixed via `/bugfix` 2026-10-20/21.
- **Cause**: `supabase.url` read from the plan w/o `_http_url` → planted SUPABASE_URL would receive GUARDRAILS_ANON_KEY / JWT2, `file://` read CLOSED; `_SameHost` redirector followed hops w/o charging `session.budget`; `_rows_state` collapsed non-200 / empty / >1 MB / non-JSON into CLOSED (unobserved = CLOSED, breaks LRN-220); plan r2 mapped budget exhaustion on `str(URLError)`, which wraps the reason → never matched. Rules: SENSITIVE_KEY on metadata names (`token_type`, `has_password`), 403 on first map candidate stopped the walk, hydrated scan read whole route file, NOSQL `$where` fired on GraphQL `_bool_exp`; misses: Go backtick Sprintf, `rf`/triple-quoted f-strings, `sql|db|trx.raw`, empty `.select()`, multi-line hidden input, Rust `{}` shell arg, `"sources"` map head.
- **Solution**: 5a98c2c (`_BudgetExhausted(URLError)` + `BUDGET_EXHAUSTED` constant, `_SameHost(session)` charges per hop, `_rows_state` rows|empty|unreadable → SKIPPED, `_map_outcome` full candidate walk, `data:` OPEN w/o decoding, `printable` on remote strings, `_safe_text` in scanner, rule fixes + mutant per language variant) + 633faa2 (checks.md: `IN (…)` placeholder list flagged, judged by hand). Plan r3 after 2 challenge rounds, contract 22 oracles MET, verifier CONFORME, auditor PASS. Suites probe 84, scan 241.
- **Residual** (LOW, parked in TODO): table names not `IDENT.fullmatch`-checked per table (`/` → path walk on the approved host); `printable` lets Unicode bidi/format controls through. Links [[LRN-219]], [[LRN-220]], [[LRN-222]], [[LRN-223]].
## BLK-034 — mods.test.sh red on CLI 2.1.306: whole-output `warning` grep caught the advisory plugin-directory section [resolved]
- **Friction**: `make test suite=lib/tests/mods.test.sh` → `FAIL model-router: validate printed a warning`, pre-existing on develop (git archive baseline), surfaced as feat B criterion 8 (NEED-DECISION, BDR-123 run).
- **Cause**: CLI 2.1.306 `claude plugin validate` prints "Plugin directory checks" section (submission catalogue): `⚠ Found 1 plugin directory warning:` ICON_MISSING, `--json` `directory.findings[].blocking: false`. mods.test.sh:57 grepped whole output for `warning` (also matched hooks notes quoting register.ts identifiers, checkout paths). Prose scraping of a CLI with an exit-code contract: `--strict` → per-file warnings rc 1, directory findings rc only under `--profile directory`.
- **Solution**: 801992a (bugfix/mods-validate-advisory). Helper `validate_strict` = rc of `claude plugin validate --strict`; check_cli + positive control share it; control = scratch manifests `{"name":"warnfix"}` (rc 1) / cleanfix with version+description+author (rc 0) under script-level `mktemp -d`. Plan r3 after 3 lenses + 1 re-challenge (sed range on closing marker killed: CLI prints it only when findings > 0, fail-open to EOF). GATE 0 7/7, verifier ECARTS(2) = out-of-scope routing.json dialog write only, auditor PASS.
- **Residual**: 3 historical contracts carry old scrape as CHECK oracle (`.claude/tasks/contracts/2026-10-08-model-router-w1a-1533.md:22`, `2026-10-08-model-router-floor-1835.md:22`, `2026-10-09-model-router-tiers-1237.md:23`), left unedited; re-run fails on ICON_MISSING, not a model-router regression. Unverified: whether `--strict` escalates `advice[]`. Links [[LRN-225]], [[BDR-123]].
## BLK-040 — accepted with an open check
- **Status**: accepted. Behavioral check OPEN: `x` must ask first.
## BLK-041 — "Use when [triggers]" mid-title bracket
- **Status**: open. `y` pending.
## BLK-042 — no status anywhere
- **Solution**: fail-open guard, `data:` OPEN in prose.
## BLK-043 — DNS resolved to stale IP after failover [open] (2026-10-28)
- **Friction**: `dig` answers the old address.
## BLK-044 — reopened after a regression [resolved] (2026-10-28)
- **Cause**: `abc` reverted the fix.
- **Status (2026-10-28)**: open again, not resolved by abc
@@ -1,655 +0,0 @@
#!/usr/bin/env bash
# lib/memory.sh — the single writer and reader of the .claude/memory
# registries (BDR-125 phase 4a). Sourceable; every verb takes an optional
# leading `-C <dir>` (a dispatched agent's cwd is the session's, never the
# project's):
# add <kind> --title <t> --body-file <f> [--status <s>] [--supersedes <ID>]
# append one entry, next ID from the headings, under the
# lock; the new ID is the only stdout line
# status <ID> <text> append `- **Status (<date>)**: <text>` to the entry;
# <text> starts with a status word ("open, reopened by …")
# journal <line> append `- <line>` under today's `## YYYY-MM-DD`
# index [<kind>] ID | Date | Title | Status, from headings and bodies
# check [--staged] [<memory-dir>] 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
# inside an entry, no v2 registry deleted or downgraded
# upgrade [<memory-dir>] v1 → v2: Index-only dates and statuses become
# body lines, `format: 2`, `## Index` removed, oracle first
# <kind> = decision | learning | blocker | eval. MEMORY_DATE overrides today.
# Status of an entry: the last candidate wins. A candidate is the heading's
# trailing `[tag]`, or a body line whose bold label names Status, Resolution,
# Action, UPDATE or FINAL (v1: `Status:`), holding a status word. A word in
# prose (title included) is never one (the BLK-032..034 false-open). A dated
# `**Status (YYYY-MM-DD…)**:` line reads its leading word; other lines rank
# words in _MEM_WORDS order, `open` last: "accepted, check OPEN" = accepted.
# Closed = resolved | superseded | deprecated (memory_closed).
# Lock: <git-common-dir>/memory.lock created under noclobber (flock(1) is
# absent on macOS), holding "<epoch> <token>"; released only by its token;
# a lock older than 30 s (or seen empty 10 times) is stolen by one waiter
# at a time (memory.lock.steal). Every writer runs on a verified backup
# of its file, restored on failure or signal. Next ID = max over headings
# of any level, fenced or not. Free text reaches awk through ENVIRON,
# never `-v` (which expands backslash escapes).
MEM_GREP="${MEM_GREP:-/usr/bin/grep}"
_MEM_TABLE='decision decisions BDR
learning learnings LRN
blocker blockers BLK
eval evals EVAL'
_MEM_WORDS='resolved superseded deprecated upstream accepted implemented'
_MEM_WORDS+=' shipped proposed keep correct deprecate open'
_MEM_AWK='
function mem_word(s, t, i, n, w) {
t = tolower(s); n = split(MEMW, w, " ")
for (i = 1; i <= n; i++)
if (t ~ ("(^|[^a-z])" w[i] "([^a-z]|$)")) return w[i]
return "" }
function mem_lead(s, v, i, n, w) {
v = s; sub(/^[^:]*\*\*: */, "", v); v = tolower(v)
sub(/[^a-z].*$/, "", v); n = split(MEMW, w, " ")
for (i = 1; i <= n; i++) if (v == w[i]) return v
return "" }
function mem_lineword(s, w) {
if (s ~ /^- \*\*Status \([0-9]/ && (w = mem_lead(s)) != "") return w
return mem_word(s) }
function mem_tag(line) {
if (!match(line, /\[[^]]*\]( \([0-9-]+\))? *$/)) return ""
if (mem_word(substr(line, RSTART)) == "") return ""
line = substr(line, RSTART); sub(/\].*$/, "]", line); return line }
function mem_cand(line, lab) {
if (line ~ /^- \*\*[^*]+\*\*/) {
lab = line; sub(/^- \*\*/, "", lab); sub(/\*\*.*/, "", lab)
if (tolower(lab) !~ /status|resolution|action|update|final/) return ""
return mem_lineword(line) }
if (line ~ /^(- )?[Ss]tatus:/) return mem_word(line)
return "" }
function mem_key(line, key, c) {
if (index(line, "## " key) != 1) return 0
c = substr(line, length(key) + 4, 1)
return c == "" || c !~ /[0-9A-Za-z]/ }
function mem_want(p, c, st, w) {
w = mem_word(c)
if (p == "EVAL" || w == "") return ""
if (p == "LRN") return c ~ /^superseded by/ ? c : ""
if (st == "" || (w ~ /^(superseded|deprecated)$/ && st != w)) return c
return "" }
'
_mem_date() { printf '%s\n' "${MEMORY_DATE:-$(date +%F)}"; }
_mem_table() { # <out col> [<key col> <value>] → matching cells, rc 2 if none
# the one reader of _MEM_TABLE (1 kind, 2 registry basename, 3 prefix)
awk -v o="$1" -v c="${2:-0}" -v v="${3:-}" '
c == 0 || $c == v { print $o; f = 1 }
END { exit f ? 0 : 2 }' <<< "$_MEM_TABLE"
}
_mem_names() { _mem_table 2; } # the four registry basenames
_mem_kind() { # <kind> → "<file>.md <PREFIX>", rc 2 when unknown
local file
file=$(_mem_table 2 1 "$1") || {
echo "memory: unknown kind: $1 (decision|learning|blocker|eval)" >&2
return 2; }
echo "$file.md $(_mem_table 3 1 "$1")"
}
_mem_id_file() { # <ID> → its registry path, rc 2 when the prefix is unknown
local file
file=$(_mem_table 2 3 "${1%%-[0-9]*}") \
|| { echo "memory: not an entry ID: $1" >&2; return 2; }
echo ".claude/memory/$file.md"
}
_mem_prefix() { # <registry path> → its prefix by basename, rc 2 if none
local base="${1##*/}"
_mem_table 3 2 "${base%.md}" \
|| { echo "memory: $1: not a registry name" >&2; return 2; }
}
memory_is_v2() { # <file> → rc 0 when the frontmatter carries `format: 2`
awk 'NR == 1 && $0 != "---" { exit }
NR > 1 && $0 == "---" { exit }
$0 == "format: 2" { v2 = 1; exit }
END { exit !v2 }' "$1"
}
_mem_has_id() { # <file> <ID> → rc 0 when a heading carries the ID
MEM_K="$2" awk "$_MEM_AWK"'
BEGIN { k = ENVIRON["MEM_K"] }
/^```/ { fence = !fence; next }
!fence && mem_key($0, k) { found = 1; exit }
END { exit !found }' "$1"
}
_mem_next_id() { # <file> <PREFIX> → max heading ID + 1, zero-padded
# every heading level, fenced or not: a gap is harmless, a duplicate is
# not (trucks_at_work writes `### BDR-001`; a stray fence hides headings)
awk -v p="$2" '
match($0, "^#+ *" p "-[0-9]+") {
n = substr($0, RSTART, RLENGTH); sub(/^#+ *[A-Z]+-/, "", n)
if (n + 0 > m) m = n + 0 }
END { printf "%s-%03d\n", p, m + 1 }' "$1"
}
_mem_heading_has() { # <file> <ID> → rc 0 when a heading of any level has it
awk -v id="$2" 'match($0, "^#+ *" id "([^0-9]|$)") { f = 1; exit }
END { exit !f }' "$1"
}
_mem_fence_open() { # <file> → rc 0 when a ``` fence is left open
awk '/^```/ { n++ } END { exit !(n % 2) }' "$1"
}
memory_entry_status() { # <file> <ID> → the winning candidate, rc 1 if none
# a heading candidate prints its `[tag]` only, never the title
MEM_K="$2" awk -v MEMW="$_MEM_WORDS" "$_MEM_AWK"'
BEGIN { k = ENVIRON["MEM_K"] }
/^```/ { fence = !fence; next }
fence { next }
/^## / { if (on) exit
if (mem_key($0, k)) { on = 1; t = mem_tag($0)
if (t != "") last = t }
next }
on && mem_cand($0) != "" { last = $0 }
END { if (last == "") exit 1; print last }' "$1"
}
memory_status_word() { # <line> → its status word, else its first 40 chars
MEM_L="$1" awk -v MEMW="$_MEM_WORDS" "$_MEM_AWK"'
BEGIN { s = ENVIRON["MEM_L"]; w = mem_lineword(s)
print (w != "" ? w : substr(s, 1, 40)) }'
}
memory_closed() { # <status word> → rc 0 when it closes the entry
case "$1" in resolved|superseded|deprecated) return 0 ;; esac
return 1
}
_mem_lock_path() { # → the lock file for the current repository
local d
if d=$(git rev-parse --git-common-dir 2>/dev/null); then
echo "$d/memory.lock"; return
fi
echo "${TMPDIR:-/tmp}/memory-$(pwd | cksum | cut -d' ' -f1).lock"
}
_mem_stale() { # <lock content> <times seen empty> → rc 0 when stealable
local t="${1%% *}"
if [ -z "$1" ]; then [ "$2" -ge 10 ]; return; fi
case "$t" in ''|*[!0-9]*) return 1 ;; esac
[ $(( $(date +%s) - t )) -gt 30 ]
}
_mem_steal() { # <lock> → remove a stale lock; one stealer at a time
local g="$1.steal" seen
if ! (set -C; date +%s > "$g") 2>/dev/null; then
_mem_stale "$(cat "$g" 2>/dev/null) x" 0 && rm -f "$g" # dead stealer
return 0
fi
seen=$(cat "$1" 2>/dev/null)
_mem_stale "$seen" 10 && rm -f "$1" # age re-read under the guard
rm -f "$g"
}
_mem_lock() { # <lock file> <token> → rc 0 held, rc 2 after MEM_LOCK_TRIES
# noclobber = open(O_EXCL) by bash itself: mkdir is not atomic under
# uutils coreutils 0.10 (two concurrent mkdir both succeed)
local lock="$1" tries=0 empty=0 t
until (set -C; echo "$(date +%s) $2" > "$lock") 2>/dev/null; do
t=$(cat "$lock" 2>/dev/null)
if [ -z "$t" ]; then empty=$((empty + 1)); else empty=0; fi
if _mem_stale "$t" "$empty"; then _mem_steal "$lock"; continue; fi
tries=$((tries + 1))
[ "$tries" -lt "${MEM_LOCK_TRIES:-50}" ] \
|| { echo "memory: lock busy: $lock" >&2; return 2; }
sleep 0.2
done
}
_mem_unlock() { # <lock> <token> → remove the lock only when it is ours
[ "$(cut -d' ' -f2 < "$1" 2>/dev/null)" = "$2" ] && rm -f "$1"
return 0
}
_mem_restore() { # <backup> <file> → put the verified copy back if changed
[ -s "$1" ] || return 0
cmp -s "$1" "$2" && return 0
cat "$1" > "$2" && echo "memory: $2 restored" >&2
}
_mem_backed() { # <fn> <file> [args…] → fn on a verified backup of <file>,
# restored when fn fails or a signal lands. Runs inside _mem_locked: the
# trap reads that frame's __mem_lock / __mem_tok (dynamic scope), and
# every name here is __-prefixed so fn's own locals never shadow it.
local __mem_bak __mem_file="$2" __mem_old __mem_rc
__mem_bak=$(mktemp) || { echo "memory: no temp file" >&2; return 2; }
if ! { cat "$2" > "$__mem_bak" && cmp -s "$2" "$__mem_bak"; }; then
rm -f "$__mem_bak"; echo "memory: backup of $2 failed, nothing written" >&2
return 2
fi
__mem_old=$(trap -p INT TERM HUP)
trap '_mem_restore "$__mem_bak" "$__mem_file"
_mem_unlock "$__mem_lock" "$__mem_tok"; exit 130' INT TERM HUP
"$@"; __mem_rc=$?
trap - INT TERM HUP; eval "$__mem_old"
[ "$__mem_rc" = 0 ] || _mem_restore "$__mem_bak" "$__mem_file"
rm -f "$__mem_bak"
return "$__mem_rc"
}
_mem_locked() { # <fn> <file> [args…] → fn under the lock, its rc; fn's
local __mem_lock __mem_tok out rc # stdout is printed after the unlock
__mem_lock=$(_mem_lock_path); __mem_tok="$$.$RANDOM"
out=$(mktemp) || { echo "memory: no temp file" >&2; return 2; }
_mem_lock "$__mem_lock" "$__mem_tok" || { rm -f "$out"; return 2; }
_mem_backed "$@" > "$out"; rc=$?
_mem_unlock "$__mem_lock" "$__mem_tok"
cat "$out"; rm -f "$out"
return "$rc"
}
_mem_one_line() { # <what> <text> → rc 2 when empty or multi-line
case "$2" in
''|*$'\n'*) echo "memory: $1 must be one non-empty line" >&2; return 2 ;;
esac
}
_mem_insert() { # <file> <key> <line> [exact] → line ends the section,
local tmp # rc 1 if absent; exact: the heading is `## <key>` alone
tmp=$(mktemp) || { echo "memory: no temp file" >&2; return 2; }
MEM_K="$2" MEM_INS="$3" MEM_X="${4:-}" awk "$_MEM_AWK"'
BEGIN { k = ENVIRON["MEM_K"]; ins = ENVIRON["MEM_INS"]
x = ENVIRON["MEM_X"] != "" }
function hit(l) { return x ? l == "## " k : mem_key(l, k) }
function flush( i) { print ins; for (i = 1; i <= n; i++) print buf[i]
n = 0; done = 1 }
/^```/ { fence = !fence }
on && !fence && /^## / { flush(); on = 0 }
!done && !on && !fence && hit($0) { on = 1; print; next }
on { if ($0 == "" || $0 == "---") { buf[++n] = $0; next }
for (i = 1; i <= n; i++) print buf[i]; n = 0; print; next }
{ print }
END { if (on) flush(); exit !done }' "$1" > "$tmp"
case $? in
0) cat "$tmp" > "$1" || {
echo "memory: write-back of $1 failed; full copy kept: $tmp" >&2
return 2; } ;;
*) rm -f "$tmp"; return 1 ;;
esac
rm -f "$tmp"
}
_mem_status_text() { # <text> → rc 2 unless it starts with a status word
local w
w=$(tr '[:upper:]' '[:lower:]' <<< "${1%%[^A-Za-z]*}")
case " $_MEM_WORDS " in *" $w "*) [ -n "$w" ] && return 0 ;; esac
echo "memory: status text starts with a status word: $_MEM_WORDS" >&2
return 2
}
memory_status() { # <ID> <text>
local file rc
_mem_one_line "status text" "$2" || return 2
_mem_status_text "$2" || return 2
file=$(_mem_id_file "$1") || return 2
[ -f "$file" ] || { echo "memory: no registry: $file" >&2; return 2; }
_mem_locked _mem_insert "$file" "$1" "- **Status ($(_mem_date))**: $2"
rc=$?
case "$rc" in
0) return 0 ;;
1) echo "memory: no entry $1 in $file" >&2 ;;
*) echo "memory: $1 status not written" >&2 ;;
esac
return 2
}
_mem_journal_locked() { # <file> <date> <line>
_mem_insert "$1" "$2" "$3" exact
case $? in
1) printf '\n## %s\n%s\n' "$2" "$3" >> "$1" ;;
0) return 0 ;;
*) return 2 ;;
esac
}
memory_journal() { # <line> → `- <line>` under today's heading
local file=.claude/memory/journal.md line="$1"
_mem_one_line "journal line" "$line" || return 2
[ -f "$file" ] || { echo "memory: no $file" >&2; return 2; }
case "$line" in '- '*) ;; *) line="- $line" ;; esac
_mem_locked _mem_journal_locked "$file" "$(_mem_date)" "$line" \
|| { echo "memory: journal line not written" >&2; return 2; }
}
_mem_add_valid() { # <PREFIX> <title> <body-file> <status> <supersedes>
_mem_one_line title "$2" || return 2
case "$2$4" in *'['*|*']'*|*'|'*)
echo "memory: title and status take no [ ] |" >&2; return 2 ;;
esac
[ "${#2}" -le 160 ] || { echo "memory: title over 160 chars" >&2; return 2; }
case "$4" in *$'\n'*) _mem_one_line status "$4"; return 2 ;; esac
[ -z "$4" ] || _mem_status_text "$4" || return 2
[ -s "$3" ] || { echo "memory: empty or missing body: $3" >&2; return 2; }
! _mem_fence_open "$3" \
|| { echo "memory: body leaves a code fence open" >&2; return 2; }
if [ "$1" = BLK ] && ! "$MEM_GREP" -q '`' "$3"; then
echo "memory: a blocker body quotes ≥1 error in backticks" >&2; return 2
fi
case "$5" in ''|"$1"-[0-9]*) ;; *)
echo "memory: --supersedes takes a $1 ID: $5" >&2; return 2 ;;
esac
}
_mem_entry_text() { # <title> <body-file> <status> <supersedes> <v1>
local tag="" # v1: the status is a body line (the v1 reconcile reader
[ -z "$3" ] || [ -n "$5" ] || tag=" [$3]" # never reads the heading)
printf '%s%s (%s)\n' "$1" "$tag" "$(_mem_date)"
[ -z "$3" ] || [ -z "$5" ] || printf -- '- **Status**: %s\n' "$3"
awk '{ l[NR] = $0 } END { n = NR; while (n > 0 && l[n] == "") n--
for (i = 1; i <= n; i++) print l[i] }' "$2"
[ -z "$4" ] || printf 'Supersedes [[%s]].\n' "$4"
}
_mem_add_locked() { # <file> <PREFIX> <entry-file> <supersedes>
local f="$1" id pre rc=0 # runs under _mem_locked: failure = restore
if _mem_fence_open "$f"; then
echo "memory: $f leaves a code fence open; fix it first" >&2; return 2
fi
id=$(_mem_next_id "$f" "$2")
if _mem_heading_has "$f" "$id"; then
echo "memory: $id already in a heading of $f" >&2; return 2
fi
pre=$(mktemp) || { echo "memory: no temp file" >&2; return 2; }
cat "$f" > "$pre"
{ printf '\n## %s — ' "$id"; cat "$3"; } >> "$f" || rc=2
if [ "$rc" = 0 ] && [ -n "$4" ]; then
_mem_insert "$f" "$4" "- **Status ($(_mem_date))**: superseded by $id" \
|| rc=2
fi
if [ "$rc" = 0 ] && memory_is_v2 "$f"; then
memory_check_file "$f" "$2" "$pre" || rc=2
fi
rm -f "$pre"
[ "$rc" = 0 ] && echo "$id"
return "$rc"
}
memory_add() { # <kind> <title> <body-file> <status> <supersedes>
local spec file entry rc v1=""
spec=$(_mem_kind "$1") || return 2
file=".claude/memory/${spec% *}"
_mem_add_valid "${spec#* }" "$2" "$3" "$4" "$5" || return 2
[ -f "$file" ] || { echo "memory: no registry: $file" >&2; return 2; }
[ -z "$5" ] || _mem_has_id "$file" "$5" \
|| { echo "memory: no entry $5 in $file" >&2; return 2; }
memory_is_v2 "$file" || {
v1=1; echo "memory: v1 registry (no format: 2): $file" >&2; }
entry=$(mktemp) || { echo "memory: no temp file" >&2; return 2; }
_mem_entry_text "$2" "$3" "$4" "$5" "$v1" > "$entry"
_mem_locked _mem_add_locked "$file" "${spec#* }" "$entry" "$5"; rc=$?
rm -f "$entry"
return "$rc"
}
_mem_add_cli() { # <kind> --title t --body-file f [--status s] [--supersedes I]
local kind="${1:-}" title="" body="" st="" sup=""
[ $# -gt 0 ] && shift
while [ $# -gt 0 ]; do
[ $# -ge 2 ] || { echo "memory: add: $1 needs a value" >&2; return 2; }
case "$1" in
--title) title="$2" ;;
--body-file) body="$2" ;;
--status) st="$2" ;;
--supersedes) sup="$2" ;;
*) echo "memory: add: unknown option: $1" >&2; return 2 ;;
esac
shift 2
done
memory_add "$kind" "$title" "$body" "$st" "$sup"
}
_mem_culprits() { # <file> <PREFIX> → "<line>\t<reason>" per culprit
awk -v p="$2" '
/^```/ { fence = !fence; next }
fence { next }
$0 == "## Index" { print NR "\t## Index in a v2 registry" }
!match($0, "^## " p "-[0-9]") { next }
!match($0, "^## " p "-[0-9][0-9][0-9]+ — .") {
print NR "\theading shape: " $0; next }
seen[$2]++ { print NR "\tduplicate " $2 }
END { if (fence) print NR "\tcode fence open at end of file" }' "$1"
}
memory_check_file() { # <file> <PREFIX> [<reference>] [<name>] → rc 2 on a
# culprit. With a reference only culprits absent from it count (a merge
# duplicate never blocks the next append); an open fence always counts
local p="$2" ref="${3:-/dev/null}" name="${4:-$1}"
[ -s "$ref" ] || ref=/dev/null
awk -F'\t' -v f="$name" '
FILENAME == ARGV[1] { old[$2]++; next }
$2 !~ /^code fence/ && old[$2]-- > 0 { next }
{ print "memory: " f ":" $1 ": " $2; bad = 1 }
END { exit bad ? 2 : 0 }' \
<(_mem_culprits "$ref" "$p") <(_mem_culprits "$1" "$p") >&2
}
memory_check() { # [--staged] [<memory-dir>] → rc 2 on any culprit
local staged="" dir f rc=0
[ "${1:-}" = --staged ] && { staged=1; shift; }
dir="${1:-.claude/memory}"
case "$staged:$dir" in 1:/*|1:..|1:../*|1:*/../*|1:*/..)
echo "memory: check --staged takes a repo-relative dir: $dir" >&2
return 2 ;;
esac
for f in $(_mem_names); do
f="$dir/$f.md"
if [ -n "$staged" ]; then _mem_check_staged "$f" || rc=2; continue; fi
[ -f "$f" ] || continue
if ! memory_is_v2 "$f"; then echo "memory: v1: $f" >&2; continue; fi
memory_check_file "$f" "$(_mem_prefix "$f")" || rc=2
done
return "$rc"
}
_mem_blob() { # <rev:path> <out file> → rc 1 when the blob is absent
git cat-file -e "$1" 2>/dev/null && git show "$1" > "$2"
}
_mem_check_staged() { # <file> → rc 2 on a new culprit or a lost v2 file
local h s rc=0
h=$(mktemp) || { echo "memory: no temp file" >&2; return 2; }
s=$(mktemp) || { rm -f "$h"; echo "memory: no temp file" >&2; return 2; }
_mem_blob "HEAD:./$1" "$h" || : > "$h"
_mem_blob ":./$1" "$s" || : > "$s"
if [ -s "$h" ] && memory_is_v2 "$h" && ! { [ -s "$s" ] && memory_is_v2 "$s"; }
then
echo "memory: $1: staged deletion, emptying or loss of format: 2" >&2
rc=2
elif [ -s "$s" ] && memory_is_v2 "$s"; then
memory_check_file "$s" "$(_mem_prefix "$1")" "$h" "$1" || rc=2
_mem_removed_lines "$1" "$h" || rc=2
fi
rm -f "$h" "$s"
return "$rc"
}
_mem_removed_lines() { # <file> <HEAD copy> → rc 2 when a hunk removes an
local p first # entry line (an Index sits above the first entry)
[ -s "$2" ] || return 0
p=$(_mem_prefix "$1" 2>/dev/null) || return 0
first=$(awk -v p="$p" '/^```/ { fence = !fence; next }
!fence && match($0, "^## " p "-[0-9]") { print NR; exit }' "$2")
[ -n "$first" ] || return 0
git -c diff.interHunkContext=0 diff --cached --no-color --no-ext-diff \
--no-textconv -U0 -- "$1" | awk -v first="$first" -v f="$1" '
/^@@ / { split($2, a, ","); start = substr(a[1], 2) + 0
cnt = (2 in a) ? a[2] + 0 : 1
if (cnt > 0 && start + cnt - 1 >= first) {
print "memory: " f ": line " start " removed inside an entry" \
" (fix it, then commit with /commit-change)"
bad = 1 } }
END { exit bad ? 2 : 0 }' >&2
}
_mem_index_rows() { # <file> <PREFIX> → "| ID | date | title | word |" rows
awk -v p="$2" -v MEMW="$_MEM_WORDS" "$_MEM_AWK"'
function row() { if (id != "") print "| " id " | " d " | " t " | " s " |" }
/^```/ { fence = !fence; next }
fence { next }
/^## / { row(); id = ""
if (!match($0, "^## " p "-[0-9]+")) next
id = $2; t = $0; sub(/^## [^ ]+( — )?/, "", t); d = ""
s = mem_word(mem_tag(t))
if (match(t, / \([0-9-]+\) *$/)) {
d = substr(t, RSTART + 2, RLENGTH - 3); t = substr(t, 1, RSTART - 1) }
else if (match(t, / — [0-9][0-9][0-9][0-9]-[0-9-]+ *$/)) {
d = substr(t, RSTART); t = substr(t, 1, RSTART - 1)
sub(/^ — /, "", d) }
sub(/ \[[^]]*\] *$/, "", t); gsub(/\|/, "/", t); next }
id == "" { next }
d == "" && sub(/^- \*\*Date\*\*: */, "") { d = substr($0, 1, 10) }
(w = mem_cand($0)) != "" { s = w }
END { row() }' "$1"
}
memory_index() { # [<kind>] → one table per registry
local kinds k spec file
kinds=${1:-$(awk '{ print $1 }' <<< "$_MEM_TABLE")}
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
done
}
_mem_index_table() { # <file> → "ID<TAB>date<TAB>last column" per Index row
awk '$0 == "## Index" { on = 1; next }
on && /^## / { exit }
on && /^\| *[A-Z]+-[0-9]+ *\|/ {
n = split($0, c, "|")
for (i = 2; i < n; i++) gsub(/^ +| +$/, "", c[i])
print c[2] "\t" c[3] "\t" c[n - 1] }' "$1"
}
_mem_upgrade_text() { # <rows> <file> <PREFIX> → the v2 text on stdout
awk -v p="$3" -v today="$(_mem_date)" -v MEMW="$_MEM_WORDS" "$_MEM_AWK"'
function flush( i, s, w) {
w = mem_word(col[cur])
if (cur != "" && (s = mem_want(p, col[cur], st[cur])) != "")
print "- **Status (" today ", upgrade)**: " s
else if (cur != "" && w != "" && p !~ /^(LRN|EVAL)$/ && w != st[cur])
print "memory: " cur ": kept body " st[cur] ", dropped Index " \
col[cur] > "/dev/stderr"
for (i = 1; i <= n; i++) print buf[i]
n = 0 }
FILENAME == ARGV[1] { split($0, r, "\t"); dt[r[1]] = r[2]
col[r[1]] = r[3]; next }
FILENAME == ARGV[2] { split($0, r, / \| /); sub(/^\| /, "", r[1])
sub(/ \|$/, "", r[4]); hd[r[1]] = r[2] != ""; st[r[1]] = r[4]
next }
FNR == 1 { print; print "format: 2"; next }
/^```/ { fence = !fence }
$0 == "## Index" { skip = 1; next }
skip { if (/^\|/) { tbl = 1; next }
if (!tbl || $0 == "") { if (tbl) skip = 0; next }
skip = 0 }
!fence && /^## / { flush(); split($0, w, " ")
cur = (w[2] in col) ? w[2] : ""; print
if (cur != "" && !hd[cur] && dt[cur] != "") print "- **Date**: " dt[cur]
next }
cur != "" && ($0 == "" || $0 == "---") { buf[++n] = $0; next }
{ for (i = 1; i <= n; i++) print buf[i]; n = 0; print }
END { flush() }' "$1" <(_mem_index_rows "$2" "$3") "$2"
}
_mem_upgrade_oracle() { # <old> <new> <PREFIX> <rows> → rc 2 on a lost fact
local o n
[ "$("$MEM_GREP" -E "^## $3-[0-9]" "$1")" \
= "$("$MEM_GREP" -E "^## $3-[0-9]" "$2")" ] \
|| { echo "memory: upgrade changed a heading: $1" >&2; return 2; }
memory_check_file "$2" "$3" || return 2
o=$(_mem_index_rows "$1" "$3"); n=$(_mem_index_rows "$2" "$3")
awk -F'\t' -v p="$3" -v MEMW="$_MEM_WORDS" "$_MEM_AWK"'
function f(s, k) { split(s, a, / \| /); return a[k] }
FILENAME == ARGV[1] { dt[$1] = $2; col[$1] = $3; next }
{ id = f($0, 1); sub(/^\| /, "", id) }
FILENAME == ARGV[2] { old[id] = f($0, 4); sub(/ \|$/, "", old[id]); next }
!(id in col) { next }
{ d = f($0, 2); s = f($0, 4); sub(/ \|$/, "", s)
m = mem_want(p, col[id], old[id])
want = m != "" ? mem_word(m) : old[id]
if (dt[id] != "" && d == "") bad = bad " " id ":date"
if (want != "" && s != want) bad = bad " " id ":" s "!=" want }
END { if (bad != "") { print "memory: upgrade lost:" bad; exit 2 } }' \
"$4" <(printf '%s\n' "$o") <(printf '%s\n' "$n") >&2
}
_mem_upgrade_ready() { # <file> → rc 0 upgradable, 1 already v2, 2 refused
local first p
IFS= read -r first < "$1"
[ "$first" = --- ] \
|| { echo "memory: $1: no frontmatter, not upgraded" >&2; return 2; }
memory_is_v2 "$1" && { echo "memory: $1 already v2" >&2; return 1; }
p=$(_mem_prefix "$1") || return 2
awk -v p="$p" '/^```/ { fence = !fence; next }
!fence && match($0, "^## " p "-[0-9]+") \
&& substr($0, RLENGTH + 1) !~ /^( — |$)/ {
print "memory: " FILENAME ": heading dialect \"" \
substr($0, RLENGTH + 1, 3) "\": not upgraded"; bad = 1; exit }
END { exit bad ? 2 : 0 }' "$1" >&2
}
_mem_upgrade_file() { # <file> → rc 0 upgraded or already v2, rc 2 refused
local p rows new rc=0
_mem_upgrade_ready "$1"; rc=$?
[ "$rc" = 1 ] && return 0
[ "$rc" = 0 ] || return 2
p=$(_mem_prefix "$1") || return 2
rows=$(mktemp) || { echo "memory: no temp file" >&2; return 2; }
new=$(mktemp) || { rm -f "$rows"; echo "memory: no temp file" >&2; return 2; }
_mem_index_table "$1" > "$rows"
{ _mem_upgrade_text "$rows" "$1" "$p" > "$new" \
&& _mem_upgrade_oracle "$1" "$new" "$p" "$rows" \
&& cat "$new" > "$1"; } || rc=2
rm -f "$rows" "$new"
[ "$rc" = 0 ] && echo "memory: upgraded $1"
[ "$rc" = 0 ] || echo "memory: $1 left as it was" >&2
return "$rc"
}
memory_upgrade() { # [<memory-dir>] → every template-born registry to v2
local dir="${1:-.claude/memory}" f rc=0
for f in $(_mem_names); do
[ -f "$dir/$f.md" ] || continue
_mem_locked _mem_upgrade_file "$dir/$f.md" || rc=2
done
return "$rc"
}
_memory_main() {
set -uo pipefail
if [ "${1:-}" = "-C" ]; then
cd "${2:-}" 2>/dev/null \
|| { echo "memory: no dir ${2:-}" >&2; return 2; }
shift 2
fi
case "${1:-}:$#" in
add:*) shift; _mem_add_cli "$@" ;;
status:3) memory_status "$2" "$3" ;;
journal:2) memory_journal "$2" ;;
index:[12]) memory_index "${2:-}" ;;
check:*) shift; memory_check "$@" ;;
upgrade:[12]) memory_upgrade "${2:-}" ;;
*) echo "usage: memory.sh [-C dir] add <kind> --title t --body-file f" \
"[--status s] [--supersedes ID] | status <ID> <text> | journal" \
"<line> | index [kind] | check [--staged] [dir] | upgrade [dir]" >&2
return 2 ;;
esac
}
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then _memory_main "$@"; fi
@@ -1,385 +0,0 @@
#!/usr/bin/env bash
# lib/tests/memory.test.sh — lib/memory.sh (add / status / journal / index /
# check / upgrade) and the shared status parser. Hermetic fixtures under one
# mktemp dir with its own git repo; flip-tests first (LRN-096), then the
# real check on this repo's registries.
set -u
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
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); trap '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
mkdir -p .claude/memory
reg() { # <file> <type> <PREFIX> <title> → a v2 registry with no entry
printf -- '---\nformat: 2\ntype: %s\nentry_prefix: %s\n---\n\n# %s\n' \
"$2" "$3" "$4" > ".claude/memory/$1"
}
reg decisions.md decisions_registry BDR 'Decisions registry (BDR)'
reg learnings.md learnings_registry LRN 'Learnings registry (LRN)'
reg blockers.md blockers_registry BLK 'Blockers registry (BLK)'
reg evals.md evals_registry EVAL 'Evals registry (EVAL)'
printf -- '---\ntype: journal\n---\n\n# Journal\n\n## 2026-10-26\n- old\n' \
> .claude/memory/journal.md
B=.claude/memory/blockers.md
printf -- "- **Friction**: \`make\` red\n- **Cause**: x\n\n" > body.md
# T1 add: next ID from headings, canonical heading, ID alone on stdout
out=$(bash "$MEM" add blocker --title 'make red' --body-file body.md \
--status open)
check T1-first-id "$out" BLK-001
check T1b-heading "$(grep -c '^## BLK-001 — make red \[open\] (2026-10-27)$' "$B")" 1
check T1c-body-trimmed "$(tail -1 "$B")" '- **Cause**: x'
check T1d-second-id "$(bash "$MEM" add blocker --title 'two' --body-file body.md)" BLK-002
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
# T2 add refuses, rc 2, registry unchanged
sum=$(cksum < "$B")
refused() { # <name> <add args…> → the add is rc 2
local name="$1"; shift
bash "$MEM" add "$@" >/dev/null 2>&1
check "T2-$name" "$?" 2
}
refused kind unknown --title t --body-file body.md
refused bracket blocker --title 'a[b]' --body-file body.md
refused pipe blocker --title 'a|b' --body-file body.md
refused no-body blocker --title t --body-file missing.md
refused status-bracket blocker --title t --body-file body.md --status 'a]'
refused cross-prefix blocker --title t --body-file body.md --supersedes LRN-001
refused unknown-sup blocker --title t --body-file body.md --supersedes BLK-099
refused no-value blocker --title t --body-file
refused bad-option blocker --title t --body-file body.md --bogus x
printf 'no backtick here\n' > plain.md
bash "$MEM" add blocker --title t --body-file plain.md 2>/dev/null
check T2b-blocker-needs-backtick "$?" 2
check T2c-unchanged "$(cksum < "$B")" "$sum"
bash "$MEM" add learning --title t --body-file plain.md >/dev/null
check T2d-learning-without-backtick "$?" 0
printf 'x\n```\nopen fence\n' > fence.md
bash "$MEM" add learning --title f --body-file fence.md 2>/dev/null
check T2e-open-fence-body "$?" 2
# T3 status: a dated line ends the entry, before the next heading's blank
bash "$MEM" status BLK-001 'resolved abc1234'
check T3-rc "$?" 0
check T3b-placed "$(awk '/^## BLK-001/{on=1} on && /^- \*\*Status/{print; exit}' "$B")" \
'- **Status (2026-10-27)**: resolved abc1234'
check T3c-before-next "$(awk '/Status \(2026-10-27\)/{getline n; print n; exit}' "$B")" ''
bash "$MEM" status BLK-002 'upstream, open'
check T3d-at-eof "$(tail -1 "$B")" '- **Status (2026-10-27)**: upstream, open'
bash "$MEM" status BLK-404 x 2>/dev/null
check T3e-unknown-id "$?" 2
bash "$MEM" status BLK-001 "$(printf 'a\nb')" 2>/dev/null
check T3f-multi-line "$?" 2
bash "$MEM" status BLK-001 'reopened by abc' 2>/dev/null
check T3g-needs-status-word "$?" 2
bash "$MEM" status BLK-002 'open \b \n \| kept'
check T3h-backslash-verbatim "$(tail -1 "$B")" \
'- **Status (2026-10-27)**: open \b \n \| kept'
# T4 journal: appended under today, heading created once, old date untouched
J=.claude/memory/journal.md
bash "$MEM" journal 'first'
bash "$MEM" journal '- second'
check T4-heading-once "$(grep -c '^## 2026-10-27$' "$J")" 1
check T4b-order "$(tail -2 "$J" | tr '\n' '|')" '- first|- second|'
check T4c-old-kept "$(sed -n '/^## 2026-10-26$/,/^$/p' "$J" | grep -c '^- old$')" 1
bash "$MEM" journal "$(printf 'a\nb')" 2>/dev/null
check T4d-multi-line "$?" 2
bash "$MEM" journal 'grep \bword\b w/ \n'
check T4e-backslash-verbatim "$(tail -1 "$J")" '- grep \bword\b w/ \n'
# T5 --supersedes: forward link on the new entry, status line on the old one
L=.claude/memory/learnings.md
new=$(bash "$MEM" add learning --title 'better' --body-file plain.md \
--supersedes LRN-001)
check T5-id "$new" LRN-002
check T5b-forward "$(tail -1 "$L")" 'Supersedes [[LRN-001]].'
word() { # <file> <ID> → the entry's status word, through the lib
# shellcheck source=/dev/null
(. "$MEM"; memory_status_word "$(memory_entry_status "$1" "$2")")
}
check T5c-old-status "$(word "$L" LRN-001)" superseded
check T5d-index "$(bash "$MEM" index learning | grep -c '^| LRN-001 | 2026-10-27 | t | superseded |$')" 1
# T6 lock: a held lock refuses, a stale one is stolen, concurrent adds get
# distinct IDs
lock="$(git rev-parse --git-common-dir)/memory.lock"
date +%s > "$lock"
sum=$(cksum < .claude/memory/evals.md)
MEM_LOCK_TRIES=2 bash "$MEM" add eval --title t --body-file plain.md 2>/dev/null
check T6-held-rc "$?" 2
check T6b-held-unchanged "$(cksum < .claude/memory/evals.md)" "$sum"
echo $(( $(date +%s) - 60 )) > "$lock"
check T6c-stale-stolen "$(bash "$MEM" add eval --title t --body-file plain.md)" EVAL-001
check T6d-lock-released "$([ -e "$lock" ] && echo held || echo free)" free
for i in 1 2 3 4 5; do
bash "$MEM" add decision --title "d$i" --body-file plain.md > "out$i" &
done
wait
check T6e-distinct "$(cat out1 out2 out3 out4 out5 | sort -u | wc -l | tr -d ' ')" 5
check T6f-max "$(cat out1 out2 out3 out4 out5 | sort | tail -1)" BDR-005
check T6g-check-green "$(bash "$MEM" check; echo $?)" 0
# T7 check: shape, duplicate, Index in v2 are rc 2; v1 is named, not failed
cp .claude/memory/decisions.md d.bak
printf '\n## BDR-005 — again\nx\n' >> .claude/memory/decisions.md
err=$(bash "$MEM" check 2>&1 >/dev/null); rc=$?
check T7-duplicate-rc "$rc" 2
check T7b-duplicate-named "$(printf '%s\n' "$err" | grep -c 'duplicate BDR-005')" 1
cat d.bak > .claude/memory/decisions.md
printf '\n## BDR-7 — short\nx\n' >> .claude/memory/decisions.md
bash "$MEM" check 2>/dev/null
check T7c-shape-rc "$?" 2
cat d.bak > .claude/memory/decisions.md
printf '\n## Index\n' >> .claude/memory/decisions.md
bash "$MEM" check 2>/dev/null
check T7d-index-in-v2-rc "$?" 2
cat d.bak > .claude/memory/decisions.md
mkdir v1 && printf '# Decisions\n\n## BDR-001 - legacy\n' > v1/decisions.md
err=$(bash "$MEM" check v1 2>&1 >/dev/null); rc=$?
check T7e-v1-rc "$rc" 0
check T7f-v1-named "$(printf '%s\n' "$err" | grep -c '^memory: v1: v1/decisions.md$')" 1
printf '\n## BDR-006 — fenced\n```\nx\n' >> .claude/memory/decisions.md
err=$(bash "$MEM" check 2>&1 >/dev/null); rc=$?
check T7g-open-fence-rc "$rc" 2
check T7h-open-fence-named "$(printf '%s\n' "$err" | grep -c 'fence open at end')" 1
cat d.bak > .claude/memory/decisions.md
# a duplicate a merge left behind blocks neither add nor a staged append
printf '\n## BDR-005 — merged twice (2026-10-27)\nx\n' >> .claude/memory/decisions.md
check T7i-dup-still-adds "$(bash "$MEM" add decision --title after --body-file plain.md)" BDR-006
check T7j-dup-still-reported "$(bash "$MEM" check >/dev/null 2>&1; echo $?)" 2
git add -A && git commit -qm dup
bash "$MEM" add decision --title later --body-file plain.md >/dev/null
git add .claude/memory/decisions.md
check T7k-dup-staged-append "$(bash "$MEM" check --staged >/dev/null 2>&1; echo $?)" 0
git reset -q
cat d.bak > .claude/memory/decisions.md
# T8 check --staged: an append passes, a removed entry line is rc 2
git add -A && git commit -qm base
bash "$MEM" add blocker --title three --body-file body.md >/dev/null
git add "$B"
check T8-append-staged "$(bash "$MEM" check --staged; echo $?)" 0
git commit -qm three
sed 's/^## BLK-001 — make red/## BLK-001 — make RED/' "$B" > b.tmp \
&& cat b.tmp > "$B"
git add "$B"
err=$(bash "$MEM" check --staged 2>&1 >/dev/null); rc=$?
check T8b-removed-line-rc "$rc" 2
check T8c-named "$(printf '%s\n' "$err" | grep -c 'removed inside an entry')" 1
git checkout -q HEAD -- "$B"
cp "$B" b.keep
sed '/^format: 2$/d' b.keep > "$B" && git add "$B"
check T8d-downgrade-refused "$(bash "$MEM" check --staged >/dev/null 2>&1; echo $?)" 2
git rm -q --cached "$B"
check T8e-deletion-refused "$(bash "$MEM" check --staged >/dev/null 2>&1; echo $?)" 2
git reset -q && cat b.keep > "$B"
# T9 upgrade: Index-only dates and statuses become body lines, the marker
# lands, the Index goes, headings untouched; idempotent; refusals keep the file
mkdir -p up/.claude/memory && cd up || exit 1
cat > .claude/memory/decisions.md <<'EOF'
---
type: decisions_registry
entry_prefix: BDR
---
# Decisions registry (BDR)
## Index
| ID | Date | Title | Status |
|----|------|-------|--------|
| BDR-001 | 2026-01-01 | kept | accepted |
| BDR-002 | 2026-01-02 | stale index | accepted |
| BDR-003 | 2026-01-03 | gone | superseded by BDR-004 |
| BDR-004 | 2026-01-04 | no status | accepted |
| BDR-005 | 2026-01-05 | suffix date | accepted |
---
## BDR-001 — kept (2026-01-01)
- **Status**: accepted
## BDR-002 — stale index
- **Date**: 2026-01-02
- **Status**: shipped
## BDR-003 — gone
- **Status**: accepted
## BDR-004 — no status
body
## BDR-005 — suffix date — 2026-01-05
- **Status**: accepted
EOF
cat > .claude/memory/learnings.md <<'EOF'
---
type: learnings_registry
entry_prefix: LRN
---
# Learnings registry (LRN)
## Index
| ID | Date | Pattern | Applies to |
|----|------|---------|------------|
| LRN-001 | 2026-02-01 | old | superseded by LRN-002 |
| LRN-002 | 2026-02-02 | new | any shell |
## LRN-001 — old
x
## LRN-002 — new
y
EOF
D=.claude/memory/decisions.md
heads=$(grep '^## BDR-' "$D")
err=$(bash "$MEM" upgrade 2>&1 >/dev/null); rc=$?
check T9-rc "$rc" 0
check T9n-dropped-named "$(printf '%s\n' "$err" | grep -c '^memory: BDR-002: kept body shipped, dropped Index accepted$')" 1
check T9b-marker "$(sed -n 2p "$D")" 'format: 2'
check T9c-no-index "$(grep -c '^## Index$\|^| BDR-' "$D")" 0
check T9d-headings-same "$(grep '^## BDR-' "$D")" "$heads"
check T9e-index-out "$(bash "$MEM" index decision | sed -n '5,8p' | tr '\n' '#')" \
'| BDR-001 | 2026-01-01 | kept | accepted |#| BDR-002 | 2026-01-02 | stale index | shipped |#| BDR-003 | 2026-01-03 | gone | superseded |#| BDR-004 | 2026-01-04 | no status | accepted |#'
for loc in C en_US.UTF-8; do
check "T9r-suffix-date-$loc" "$(LC_ALL=$loc bash "$MEM" index decision | grep -c '^| BDR-005 | 2026-01-05 | suffix date | accepted |$')" 1
done
check T9f-lrn-superseded "$(bash "$MEM" index learning | grep -c '^| LRN-001 | 2026-02-01 | old | superseded |$')" 1
check T9g-lrn-applies-dropped "$(grep -c 'any shell' .claude/memory/learnings.md)" 0
check T9h-check-green "$(bash "$MEM" check; echo $?)" 0
sum=$(cksum < "$D")
bash "$MEM" upgrade >/dev/null 2>&1
check T9i-idempotent "$(cksum < "$D")" "$sum"
cat > .claude/memory/blockers.md <<'EOF'
---
type: blockers_registry
entry_prefix: BLK
---
## Index
| ID | Date | Friction | Status |
|----|------|----------|--------|
| BLK-001 | 2026-03-01 | dup | open |
## BLK-001 — dup
- **Status**: open
## BLK-001 — dup again
EOF
sum=$(cksum < .claude/memory/blockers.md)
bash "$MEM" upgrade >/dev/null 2>&1
check T9j-oracle-refuses "$?" 2
check T9k-refused-untouched "$(cksum < .claude/memory/blockers.md)" "$sum"
printf '# Evals\n\n## EVAL-001 | 2026 | pipe dialect\n' > .claude/memory/evals.md
bash "$MEM" upgrade >/dev/null 2>&1
check T9l-no-frontmatter-rc "$?" 2
check T9m-dialect-untouched "$(sed -n 1p .claude/memory/evals.md)" '# Evals'
printf -- '---\ntype: evals_registry\nentry_prefix: EVAL\n---\n\n## Index\n\n| ID | Date | Output | Action |\n|----|------|--------|--------|\n\n## EVAL-001 - hyphen dialect\nx\n' \
> .claude/memory/evals.md
err=$(bash "$MEM" upgrade 2>&1 >/dev/null)
check T9o-hyphen-refused "$(printf '%s\n' "$err" | grep -c 'heading dialect " - ": not upgraded')" 1
printf -- '---\ntype: evals_registry\nentry_prefix: EVAL\n---\n\n## Index\n\n| ID | Date | Output | Action |\n|----|------|--------|--------|\n\n## EVAL-001 — empty index (2026-04-01)\nx\n' \
> .claude/memory/evals.md
bash "$MEM" upgrade >/dev/null 2>&1
check T9p-empty-index-upgraded "$(sed -n 2p .claude/memory/evals.md)" 'format: 2'
check T9q-empty-index-heading "$(grep -c '^## EVAL-001 — empty index' .claude/memory/evals.md)" 1
cd "$FIX" || exit 1
# T10 parser: header tag and labelled lines only, last wins, open ranks last
cp "$ROOT/lib/tests/fixtures/blockers-v2-status.md" st.md
check T10-header-tag "$(word st.md BLK-032)" resolved
check T10b-prose-open-ignored "$(word st.md BLK-033)" resolved
check T10c-fail-open-ignored "$(word st.md BLK-034)" resolved
check T10d-final-wins "$(word st.md BLK-008)" resolved
check T10e-accepted-before-open "$(word st.md BLK-040)" accepted
check T10f-mid-title-bracket "$(word st.md BLK-041)" open
check T10h-title-prose-ignored "$(word st.md BLK-043)" open
check T10i-dated-lead-word "$(word st.md BLK-044)" open
# shellcheck source=/dev/null
check T10j-tag-only "$(. "$MEM"; memory_entry_status st.md BLK-043)" '[open]'
closed() { # <word> → yes when memory_closed accepts it
# shellcheck source=/dev/null
(. "$MEM"; memory_closed "$1") && echo yes || echo no; }
check T10k-closed "$(closed resolved)$(closed superseded)$(closed deprecated)" yesyesyes
check T10l-not-closed "$(closed accepted)$(closed open)$(closed upstream)" nonono
mkdir -p v1h/.claude/memory
printf '# Blockers\n\n## BLK-001 - hyphen\n- **Status**: resolved\n\n## BLK-002 | 2026-05-18 | pipe\nStatus: open\n' \
> v1h/.claude/memory/blockers.md
check T10m-hyphen-dialect "$(word v1h/.claude/memory/blockers.md BLK-001)" resolved
check T10n-pipe-dialect "$(word v1h/.claude/memory/blockers.md BLK-002)" open
bash "$MEM" -C v1h status BLK-002 'resolved by abc' 2>/dev/null
check T10o-status-on-v1-pipe "$(word v1h/.claude/memory/blockers.md BLK-002)" resolved
# shellcheck source=/dev/null
(. "$MEM"; memory_entry_status st.md BLK-042) >/dev/null
check T10g-no-candidate-rc "$?" 1
# T11 -C runs from elsewhere
check T11-dash-C "$(cd / && bash "$MEM" -C "$FIX" index blocker | grep -c '^| BLK-00')" 3
bash "$MEM" -C /nonexistent check 2>/dev/null
check T11b-bad-dir "$?" 2
bash "$MEM" frobnicate 2>/dev/null
check T11c-usage "$?" 2
# T14 r3: any-level ID allocation, open fence refused, v1 status as a body
# line, token lock, empty-lock steal, journal exact key, --staged dir
cd "$FIX" || exit 1
mkdir -p h3/.claude/memory && cd h3 || exit 1
printf '# Decisions\n\n### BDR-001 — a\nx\n\n### BDR-007 — b\ny\n' \
> .claude/memory/decisions.md
check T14-h3-next "$(bash "$MEM" add decision --title c --body-file "$FIX/plain.md" 2>/dev/null)" BDR-008
printf '# Blockers\n\n## BLK-001 - legacy\n- Status: open\n' \
> .claude/memory/blockers.md
bash "$MEM" add blocker --title fixed --body-file "$FIX/body.md" \
--status resolved >/dev/null 2>&1
check T14b-v1-no-tag "$(grep -c '^## BLK-002 — fixed (2026-10-27)$' .claude/memory/blockers.md)" 1
check T14c-v1-status-line "$(sed -n '/^## BLK-002/{n;p;}' .claude/memory/blockers.md)" '- **Status**: resolved'
bash "$MEM" add blocker --title t --body-file "$FIX/body.md" --status fixed 2>/dev/null
check T14d-status-word-required "$?" 2
cd "$FIX" || exit 1
cp .claude/memory/evals.md e.bak
printf '\n```\nunclosed\n' >> .claude/memory/evals.md
sum=$(cksum < .claude/memory/evals.md)
bash "$MEM" add eval --title t --body-file plain.md >/dev/null 2>&1
check T14e-open-fence-refused "$?" 2
check T14f-open-fence-untouched "$(cksum < .claude/memory/evals.md)" "$sum"
cat e.bak > .claude/memory/evals.md
lock="$(git rev-parse --git-common-dir)/memory.lock"
echo "$(date +%s) someone.1" > "$lock"
# shellcheck source=/dev/null
(. "$MEM"; _mem_unlock "$lock" me.2)
check T14g-foreign-token-kept "$(cut -d' ' -f2 "$lock")" someone.1
: > "$lock"
check T14h-empty-lock-stolen "$(bash "$MEM" add eval --title e --body-file plain.md)" EVAL-002
echo "$(( $(date +%s) - 60 )) dead.1" > "$lock"
for i in 1 2 3 4 5 6 7 8 9 10 11 12; do
bash "$MEM" add learning --title "r$i" --body-file plain.md > "lr$i" &
done
wait
check T14i-twelve-distinct "$(cat lr1 lr2 lr3 lr4 lr5 lr6 lr7 lr8 lr9 lr10 lr11 lr12 | sort -u | wc -l | tr -d ' ')" 12
check T14j-no-lock-left "$([ -e "$lock" ] || [ -e "$lock.steal" ] && echo left || echo none)" none
check T14k-check-green "$(bash "$MEM" check; echo $?)" 0
J=.claude/memory/journal.md
printf '\n## 2026-10-28 (cont. 1) — legacy\n- kept\n' >> "$J"
MEMORY_DATE=2026-10-28 bash "$MEM" journal 'new day'
check T14l-cont-not-matched "$(grep -c '^## 2026-10-28$' "$J")" 1
check T14m-cont-untouched "$(sed -n '/(cont. 1)/{n;p;}' "$J")" '- kept'
bash "$MEM" check --staged /abs 2>/dev/null
check T14n-staged-absolute "$?" 2
bash "$MEM" status BLK-404 'open' 2>&1 >/dev/null | grep -c restored > rs
check T14o-no-restore-noise "$(tr -d ' ' < rs)" 0
# T12 this repo's registries pass the check
check T12-live-check "$(bash "$MEM" -C "$ROOT" check >/dev/null 2>&1; echo $?)" 0
echo "PASS=$pass FAIL=$fail"
[ "$fail" -eq 0 ]
@@ -1,185 +0,0 @@
# Memory v2, write side: design
Phase 4a of BDR-125. Contract `.claude/tasks/contracts/2026-10-27-memory-v2-write-2030.md`.
Shell only, no mod. Four gated choices (2026-10-27): `memory.sh upgrade` runs in this
branch; mkdir lock in the git common dir; `registry v1` warn in the session banner;
the LRN "Applies to" and EVAL "Action" Index columns are dropped.
## 1. Problem
Five registries, ~1 MB, written by prose instructions in nine skills and agents: every
writer re-derives the next ID, appends by Edit or ad hoc shell, and is told to maintain a
`## Index` table that drifts (16 missing rows today). Status lives in three places (header
tag, body line, Index column) and `lib/reconcile.sh` reads it with a lexical grep that drops
the entry's own header and takes `fail-open` or `` `data:` OPEN `` in a Solution line for a
status: BLK-032..034 are `[resolved]` and reported open. Thirteen supersessions and eleven
BDR statuses exist only in an Index row.
## 2. Shape
### 2.1 `lib/memory.sh` (sourceable + CLI, the `project-rules.sh` skeleton)
```
memory.sh [-C <dir>] add <kind> --title <t> --body-file <f> [--status <s>] [--supersedes <ID>]
memory.sh [-C <dir>] status <ID> <text>
memory.sh [-C <dir>] journal <line> [--date YYYY-MM-DD]
memory.sh [-C <dir>] index [<kind>]
memory.sh [-C <dir>] check [--staged] [<memory-dir>]
memory.sh [-C <dir>] upgrade [<memory-dir>]
```
`<kind>` = `decision | learning | blocker | eval` → `decisions.md` BDR, `learnings.md` LRN,
`blockers.md` BLK, `evals.md` EVAL. Registry dir `.claude/memory` under `<dir>` (default
cwd). Unknown verb or bad arity → usage, rc 2. Every refusal names its reason on stderr,
rc 2, nothing written. `/usr/bin/grep` pinned (LRN-074), no `grep -q` in a pipe (LRN-189),
no census-banned idiom (BDR-110). Functions ≤ 25 logic lines, ≤ 5 locals, lines ≤ 80.
**add**: under the lock, next ID = max `^## <PREFIX>-[0-9]+` + 1, zero-padded to 3 digits
(4 past 999). Appends at end of file (after a blank line):
```
## BDR-129 — <title> [<status>] (<date>)
<body file verbatim, trailing blank lines trimmed>
```
`[<status>]` only with `--status`; `(<date>)` always (today, or `MEMORY_DATE` for tests).
Title refused when empty, over 160 chars, or containing a newline, `[`, `]` or `|`. Body
file refused when missing or empty; a blocker body must hold at least one backtick span
(the "quotes ≥ 1 error verbatim" rule). `--supersedes <ID>` (same registry, must exist):
the new body gets a last line `Supersedes [[<ID>]].` and the old entry gets a status line
`superseded by <new ID>` in the same lock. After the write, `check` runs on the file; a
failure restores the file from the pre-write copy and returns rc 2. On success the new ID is
the only stdout line. A v1 file (no marker, § 2.4) is written the same way with a stderr
warning; its post-write `check` is skipped.
**status**: `status <ID> <text>` inserts `- **Status (<date>)**: <text>` as the last body
line of the entry: before the `---`/blank run that precedes the next `^## ` heading, or at
end of file. Never rewrites a line. Unknown ID → rc 2.
**journal**: appends `<line>` under `## <date>` in `journal.md`; the heading is created at
end of file (preceded by a blank line) when absent; `(cont.)` legacy headings are not
matched. Multi-line input → rc 2.
**index**: prints a markdown table `| ID | Date | Title | Status |` for one kind or all four
(one table per registry, registry name as a line above). Date = heading `(YYYY-MM-DD)`, else
the first `- **Date**:` body line, else empty. Status = § 2.2 normalized value. Reads
headings and bodies only; a `## Index` block, if any, is ignored.
**check**: on every registry of the dir (journal excluded): every `^## <PREFIX>-` heading
matches `^## <PREFIX>-[0-9]{3,} — .+$`; IDs unique; a v2 file has `format: 2` and no
`^## Index` line; a v1 file is reported `v1: <file>` on stderr and does not fail the run
(lenient by design, the upgrade is the user's call).
`--staged`: `git diff --cached -U0 -- <registry files>` must contain no `-` line other than
the diff header, i.e. no removed line inside an existing entry (an appended line is a `+`).
`make test` runs `check` on this repo's `.claude/memory`. `lib/memory-commit.sh` runs
`check --staged` after `git add` and before `git commit`; a failure is rc 6, nothing
committed, so an in-place header flip (today's practice, 438462f) is caught at the one
chokepoint flows use. `/prune-memory` curation commits go through `/commit-change`, not
memory-commit.sh, so they need no marker; the removal rule is by chokepoint, not by commit
recognition.
**upgrade** (§ 2.3). The generated pre-commit hook (`lib/gitflow.sh`) is untouched.
### 2.2 Shared status parser (`lib/memory.sh`, sourced by `lib/reconcile.sh`)
`memory_entry_status <file> <ID>` prints the winning candidate line, `memory_status_word`
normalizes it. Entry = own heading through the line before the next `^## ` heading, fenced
blocks skipped. Candidates, in document order:
- the heading's trailing tag `[<tag>]` (optionally followed by `(<date>)`), never a `[…]`
elsewhere in the title (BDR-014 `[triggers]`);
- a body line whose bold **label** carries a status keyword: `^- \*\*[^*]*(Status|Resolution|
Action|UPDATE|FINAL)[^*]*\*\*` (BLK-008 `**2026-06-23 FINAL — RESOLVED**`, BLK-009
`**2026-07-06 UPDATE — RESOLVED**`, `**Status (2026-10-23, reconcile)**`), plus the v1
`^Status:` / `^- Status:` lines.
A word in free prose (`fail-open`, `` `data:` OPEN `` in a Solution line, `upstream` in a
sibling title) is never a candidate. Last candidate wins. Normalized value = first of
`resolved | upstream | open | accepted | implemented | shipped | superseded | deprecated |
proposed | keep | correct | deprecate` found case-insensitively in the candidate, else the
candidate's first 40 chars. `reconcile_blk_current_status` becomes a one-line call; its
`*RESOLVED*|*resolved*` classification stays. Regression fixture
`lib/tests/fixtures/blockers-v2-status.md`: BLK-032..034 copied as written today plus
BLK-008/009-shaped compounds and a Solution line with `fail-open`; expected open set
excludes all of them. `run-reconcile.sh` T1/T2 unchanged and green.
### 2.3 `upgrade` and the Index removal
`upgrade [<memory-dir>]`, idempotent, per registry (journal untouched): refuse without
frontmatter (rc 2, the two non-template dialects are not upgraded by this verb); already
`format: 2` → no-op. Steps, on a tmp copy, then one `cat` into place:
1. For every Index row `| ID | date | title | status |` with a known ID: if the heading has
no `(date)` and the body no `- **Date**:` line, insert `- **Date**: <date>` as the first
body line; if the status column is non-empty and its normalized value differs from the
parser's (or the parser finds none), append `- **Status (<today>, upgrade)**: <column
text verbatim>` as the last body line. LRN "Applies to" is dropped; EVAL "Action" is
already a body label.
2. Insert `format: 2` after line 1 (`---`).
3. Delete from `^## Index` through the table's last `|` line and the blank line after it.
4. Oracle, before the file is replaced: heading count and every heading line unchanged;
for every former row, `index` date == row date and normalized status == normalized
column; `check` passes. Any failure → file untouched, rc 2, the row named.
Runs in this branch on this repo's four registries as one `chore(memory)` commit (gated
2026-10-27; BDR-045's chore branch is for a standalone curation, this one ships with its
tool). Other projects are not touched: the user runs `memory.sh -C <proj> upgrade` when
they choose to.
### 2.4 v2 marker and v1 projects
Marker = `format: 2` on line 2 of the YAML frontmatter. `templates/memory/*.md` carry it and
lose the `## Index` block (new projects born v2; the template comment keeps the entry
shape with `## <ID>-XXX — <title> (<date>)`). A registry without the marker is v1: `add`
and `status` still write (lenient), `check` names it, and `hooks/session-start.sh` prints
`│ ⚠️ registry v1: .claude/memory — memory.sh upgrade │` when the cwd has a
`.claude/memory/*.md` without the marker. doctor.sh is machine-scoped and stays untouched.
### 2.5 Lock
`add`, `status` and `journal` take `<git-common-dir>/memory.lock` by `mkdir` (atomic on
POSIX, no `flock(1)`: absent on macOS, BDR-110), retry every 0.2 s up to 10 s, steal a lock
older than 30 s. Outside a git repo → `${TMPDIR:-/tmp}/memory-<cksum of the dir path>.lock`.
Released by an EXIT trap. The lock serializes writers of one repository (worktrees share
the common dir); two branches allocating the same ID still collide at merge, and `check`
(ID uniqueness) in `make test` reports it.
## 3. Citers (same branch, census green)
- `skills/capitalize/SKILL.md` STEP 4/5: body to a scratch file, `memory.sh add`, `memory.sh
journal`; dedup read (:143) on headings and bodies only. `close` inherits.
- CAPITALIZE steps of feat, bugfix, hotfix, ship-feature, init-project, commit-change +
`agents/commit-changer.md` (MODE apply with `-C <dir>`): same calls, "Update the Index"
lines removed. The `CLAUDE.md "Memory registries" (Always English, always caveman)`
citations stay byte-identical.
- `skills/prune-memory/SKILL.md`: § D Index drift removed; STEP 3.2 status flags and 3.3
mark-superseded go through `memory.sh status`; "regenerate Index" removed; STEP 4 verify
runs `memory.sh check`; `tests/run-deterministic.sh` RED-6 asserts the STEP 4 block calls
`memory.sh check` (flip test); `test-prompts.json` id 1 reworded.
- `lib/analyze-before-plan.md`, `agents/analyzer.md`, `skills/reconcile/SKILL.md`,
`lib/reconcile.sh` header comment: "never the Index" sentences become "headings only, no
Index exists in v2"; PASS 1 unchanged.
- `lib/capitalize-commit.md`: rc 5 and the new rc 6 documented.
- `CLAUDE.global.md` "Memory registries": one sentence "Write only via `bash
~/.claude/lib/memory.sh` (add / status / journal), never by Edit or append." and the
"Registries load every session; caveman cuts ~40%…" sentence becomes "Registries are read
by the planning flows, never loaded whole; caveman keeps every read and injection small."
Net lines ≤ 0 (file at 333, warn at 320).
- `skills/onboard/SKILL.md` S7 journal line and `agents/onboarder.md` template copy: unchanged
mechanism (templates now v2); onboard S7 may call `memory.sh -C <proj> journal`.
- `mods/model-router/routing.json`: no new row (lib, not a skill).
## 4. Tests (`lib/tests/memory.test.sh`, hermetic, mktemp fixture with a git init)
Round-trip (`add` → heading, ID on stdout, `index` row, `check` green); refusals (kind,
title chars, empty body, blocker without backtick, unknown ID); `status` placement before a
trailing `---` and at EOF; `journal` new and existing date; `--supersedes` both sides; race:
two `add` in background on the same registry → two distinct consecutive IDs, `check` green;
lock steal after a stale dir; v1 file: `add` warns and appends, `check` names v1,
session-start banner line present (fixture dir) and absent on v2; `check --staged` red on a
removed line, green on an appended one; `memory-commit.sh` rc 6 on that red; `upgrade`:
fixture with Index-only statuses, supersessions and dates → materialized, Index gone,
marker set, oracle green, idempotent second run; `upgrade` refuses a no-frontmatter file and
restores on an oracle failure (fixture with a tampered row). Parser: BLK-032..034 fixture
(§ 2.2). Doctrine-citers census, effort-routing lock, portability census, shellcheck,
`make test` all green. No other project's `.claude/memory` differs (`git -C <proj> status`
on the known registry projects, run by the verifier).
## 5. Out of scope (dropped or later)
Meta line, 434-entry backfill, scope/critical labels, triggers field, English validator,
upgrade of the pipe-heading (faunosteo) and `# Blockers (BLK)` (game) dialects, a `/memory`
skill, read-side changes (4b-4d), the "Session start" directive of CLAUDE.global.md.