From da40dba796616d01aeebd41b75a6f78ba46cc344 Mon Sep 17 00:00:00 2001 From: bchanot Date: Fri, 6 Nov 2026 17:36:33 +0100 Subject: [PATCH] =?UTF-8?q?chore(memory):=20BLK-045=20+=20BDR-139=20+=20LR?= =?UTF-8?q?N-265,=20LRN-266=20=E2=80=94=20bugfix=20safety=20residuals?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .claude/memory/blockers.md | 8 + .claude/memory/decisions.md | 9 + .claude/memory/journal.md | 1 + .claude/memory/learnings.md | 12 ++ .claude/tasks/TODO.md | 11 +- .../2026-11-06-safety-residuals-1530.md | 65 +++++++ .../plans/2026-11-06-safety-residuals-1530.md | 184 ++++++++++++++++++ 7 files changed, 285 insertions(+), 5 deletions(-) create mode 100644 .claude/tasks/contracts/2026-11-06-safety-residuals-1530.md create mode 100644 .claude/tasks/plans/2026-11-06-safety-residuals-1530.md diff --git a/.claude/memory/blockers.md b/.claude/memory/blockers.md index 76b831b..f597f5f 100644 --- a/.claude/memory/blockers.md +++ b/.claude/memory/blockers.md @@ -383,3 +383,11 @@ rules: - **Real cause**: unknown. Not set by the repo (`lib/cc.sh`, hooks: no OOMScoreAdjust). Suspects: inherited from launcher (dtach under `systemd-run --user --scope`, sshd, or the RC/remote-control process). - **Solution**: none yet. Next: trace `/proc//oom_score_adj` up the parent chain of a live claude; then set `OOMScoreAdjust` (e.g. 500) on the `cc` scope so a claude runaway dies first. - **Status**: open 2026-11-06. + +## BLK-045 — Hook-running test suites could reach real claude CLI: fail-open inline stubs, 3 suites unstubbed [resolved] (2026-11-06) + +- **Date**: 2026-11-06 +- **Friction**: hook-running test suites could still reach real `claude` CLI (BLK-043 family). Inline stubs in detect-plan + session-digest ran `claude probe` before checking stub won PATH; red control did not stop suite. graphify-gate, memory, push-guard ran `hooks/session-start.sh` with no stub; cc.test.sh shims same fail-open shape. +- **Real cause**: stub pattern (LRN-263) copied inline, fail-open: failed write (no `set -e`) or noexec TMPDIR (`command -v` skips non-exec) → real CLI; relative work dir passes same-cwd check, breaks after hook's `cd`. +- **Solution**: shared `lib/tests/claude-stub.sh`: `stub_first_or_die` (command -v == stub else exit 1), `claude_stub_install` (absolute dir via `cd -P`, every step `|| exit 1`, control from `/`, `GIT_CEILING_DIRECTORIES`), `claude_stub_calls`; 6 suites adopt, each ends zero-call check; `lib/tests/claude-stub.test.sh` proves fail-closed (no-op chmod script + sentinel fake claude). Commits dc5f127, 7ca6b18 on bugfix/safety-residuals. +- **Status**: resolved dc5f127 diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index c43b7b6..a972187 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1503,3 +1503,12 @@ Supersedes [[BDR-030]]. - **Alternatives rejected**: fine parser with carrier/wrapper lists (r2, endless holes); doctrine + soft_deny only (no deterministic refusal); ask (inert in headless sub-agents, BDR-090); folding into withheld guard-bash.sh (BLK-022 spec would turn red). - **Residuals**: destination built outside the text; old-style tar C letter, long-option abbreviations; tool names built by expansion; archive members escaping a safe destination; the cd-then-ssh FP; prose or a heredoc body quoting a complete extraction command into a system dir is refused too (it hit this memory write: memory bodies go through Write + --body-file, prose uses ` ` placeholders). - **Gates**: verifier ECARTS(2) → CONFORME; security PASS ×2 (4 MEDIUM then 2 MEDIUM fixed: size cap, control-byte RS, obfuscated names, globs, cpio pass-through, busybox timing); 134+ tests under gawk/mawk/busybox awk; make test green. Commits 5507972..f02fd8a, settings 42e37cb via index, docs 8d5a7bd. + +## BDR-139 — Pre-commit exempts only .claude/{memory,tasks,audits,deploy}/ + .githooks/, --no-renames [accepted] (2026-11-06) + +- **Date**: 2026-11-06 +- **Status**: accepted +- **Decision**: gitflow pre-commit exempts on main/develop only staged sets wholly under `.claude/memory/`, `.claude/tasks/`, `.claude/audits/`, `.claude/deploy/`, `.githooks/`; listed with `git diff --cached --name-only --no-renames`. `.claude/rules/`, `.claude/settings.json`, agents, skills = code for hook → branch first. Commit c5bd0f8; tests `lib/gitflow-test.sh` T21d-h; both hook copies regenerated; citers CLAUDE.global.md, gitflow-aiguillage.md, settings.json prose. +- **Why**: `.claude/**` let project config read by every session (rules, settings) land on protected base unreviewed; `--name-only` printed only rename destination → `git mv .claude/rules/x .claude/tasks/x` hid deletion. Allowlist = exactly side-car paths skills commit (memory-commit, deploy-commit, /tour audits): no skill flow taxed. Develop history: 1 commit (858e7a7, `.claude/settings.json`) would now need branch. +- **Alternatives rejected**: keep `.claude/**` (BDR-045 status quo, leak stays); also exempt `.claude/settings.json` (user picked no: config = reviewed change); size/heuristic narrowing (BDR-045 (D), fuzzy). +- **Residual**: hook fails open if `git diff --cached` errors (pre-existing; Gitea protection backstop). Partly revises [[BDR-045]] (exemption narrowed, aiguillage unchanged). See [[LRN-084]]. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 7e2149c..53601b5 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -701,3 +701,4 @@ rules: - 2026-11-06: machine OOM reboot 2026-11-05 23:55 root-caused: detect_plan `claude config get planType` fork bomb via SessionStart (BLK-043), SD13 fake HOME trigger. /bugfix: 3 lenses → r2 (hotfix off main, worktree), GATE 0 MET, verifier ECARTS(1 SC2016) → CONFORME, security PASS ×2; 49aa2ff. BLK-044 open (oom_score_adj -1000). Merge + Part B pending. - capitalize pre-compact: 2 learnings (hook never calls claude CLI; worktree ignored symlinks + diff3); TODO BLK-043 merge checked, Part B kept. 4c digest switch committed 4a7ce37. - 2026-11-06: BLK-043 Part B /hotfix 2f45452: session-digest suite stubs claude CLI (SD0 control, SD15 zero calls), 53/53 under TasksMax=256, security PASS (MEDIUM stub-first-on-PATH queued in TODO shortcut). 4c merge pending user. +- 2026-11-06: 4c merged ddb04f4. /bugfix safety-residuals (bugfix/safety-residuals): 5 items 9b3961e d93f06c dc5f127 97c6afc c5bd0f8 + gate round 7ca6b18; plan r3 after 3 lenses + confirm (0 BLOCKER, 8 MAJOR folded); GATE 0 MET, verifier ECARTS(2) → CONFORME, security PASS x2. BLK-045, BDR-139, LRN-265/266. Merge on signal; 4d next. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index 9e22d3f..c8e1a47 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1966,3 +1966,15 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s - **Pattern**: fresh `git worktree` lacks gitignored symlinks of main tree (`skills/darwin-skill`) → suites reading them go red (run-reconcile T6c): environment, not diff. Recreate link before blaming change. - **Context**: hotfix worktree 2026-11-06; back-merge conflict used diff3 style. - **Future use**: worktree setup → mirror ignored symlinks (`git status --ignored`). Conflict resolution here: strip `|||||||` base marker too, not only `<<<<<<<`/`=======`/`>>>>>>>`. + +## LRN-265 — awk reads an assignment-shaped path operand as var=value and reads stdin: normalize at entry (2026-11-06) + +- **Pattern**: awk takes an operand matching `^[A-Za-z_][A-Za-z0-9_]*=` as `var=value` assignment, not file → reads stdin. User path `x=1.md` or dir `a=b` → checks pass vacuously, content from stdin (empty, or tty hang). Fix at entry point, not per call site: prefix `./` only to assignment-shaped relative paths (output byte-identical otherwise); `printf '%s\n'` not `echo` (`-n` name). +- **Context**: `lib/memory.sh` `--body-file`, `check`/`upgrade` dir; ~30 awk calls take file operands; fix 9b3961e + 7ca6b18. Regression runs ``) + suite, `hooks/instructions-loaded.sh` (log `~/.claude/logs/instructions-loaded.jsonl`, session + agent ids), `!.claude/rules/` here + socle, `/onboard split` + onboarder `MODE: split`, generators emit docker/testing/ci from `templates/project-rules/`. Baseline 2026-10-26 `/context`: 32.2k total, Memory files 11.6k, project CLAUDE.md 2.1k. - [x] Proof, this repo (journal 2026-10-26: headless 17:00:07Z 4 Project `path_glob_match`, sub-agent 17:00:33Z loads rules too; `/context` after merge = the 2026-10-28 baseline 30.5k; verified 2026-11-02 /reconcile). Was: `/context` after the merge; one fresh session Reading one file per rule → 4 Project `path_glob_match` lines; one sub-agent Read → does a path rule load inside a sub-agent. Results in the journal. - [x] User step: `claude mcp remove -s user higgsfield` (done: `~/.claude.json` mcpServers empty 2026-11-02; higgsfield is a claude.ai connector, denied per profile since phase 5). - - [ ] Phase 2 folds: narrow the pre-commit `.claude/**` exemption so a rules-only commit cannot land on develop/main (deferred 2026-10-26; NOT done by phase 2 2026-11-02, still open: its own /feat on the generated pre-commit). + - [x] Phase 2 folds: narrow the pre-commit `.claude/**` exemption so a rules-only commit cannot land on develop/main (deferred 2026-10-26; NOT done by phase 2 2026-11-02, still open: its own /feat on the generated pre-commit). Done 2026-11-06 c5bd0f8 (BDR-139): allowlist memory/tasks/audits/deploy + .githooks, --no-renames. - [x] **Phase 0b, per-repo pass** (2026-10-27: 10 repos classified; split on branches awaiting the user's merge: zenquality 1942dcf 4 rules 46%, game 527bdcc 2 rules, angelscar356 ab75ecd 1 rule; keep-everything verdict, no branch: config, integration_alphalink, robin_petier, trucks_at_work, bchanot-cv, for_you, nuit-folle (all sections always-on by the S4 rule); faunosteo 7a75974 11 rules on the user's feature branch, 31.9k → 27.2k; zenquality/game/angelscar356 merged 0ff05f1/d9be6b1/853b55b; proof per repo = the user's next session there) (after phase 0 merges; via `/onboard split`, one `chore/claude-md-split` per repo off develop, approval per repo, never an automatic merge; `/context` before/after in that repo's journal). Order by size: faunosteo 52,322 chars (on feature/v1-1-clients-animals with 5 dirty files: finish or stash first, S1 refuses otherwise), zenquality 23,378, game 14,918 (on feature/replay-hint), robin_petier 12,895, config 4,990, integration_alphalink 4,249. None has `.claude/rules/` yet; all use the `.claude/*` file form (BDR-003). Sections a sub-agent needs stay always-on unless the phase 0 sub-agent proof says path rules load there (proof 2026-10-26: they do; verify per repo). - [x] Before faunosteo: `###` granularity shipped 2026-10-27 (feature/rules-h3-extract ab5049e: `extract '### title'`, `sections --depth 3`, split rows `### `). Was: decide `###` granularity (STEP 6 review 2026-10-26). - [x] /feat extract-hardening (2026-10-27, 14a93e3: `_rules_out_path_ok` refuses absolute, `..`, existing or dangling-link out; mkdir and rule-write rc checked before the source rewrite; S0.3 prose in the lib case order; 139 checks). Was: /hotfix after 0b, lib/project-rules.sh `extract` (security gate 2026-10-27, pre-existing, non-blocking): check the `> "$out"` group and `mkdir -p` rc before rewriting `$src` (today a failed rule write still removes the section, rc 0); `[ -e "$out" ] || [ -L "$out" ]` and refuse `..`/absolute `<out>`; onboarder S0.3 says `####x` is a bare title but the lib rejects it (align the prose). Its path-bound content (i18n, Schemas, Stores, PDF, Supabase, Storage, 12.6 KB) sits in `###` subsections of the always-on `## Project conventions`; `##`-only extract moves ~1.5% of the file. Option: `extract` accepts a `###` heading (section ends at the next heading of the same or higher level), `sections --depth 3`. User decides; `game` also has a `'` in `## 4. POINTS D'ATTENTION…` (S4 refuses it until renamed, or extract by index). @@ -36,7 +36,7 @@ Shared rules for every phase: - [x] Phase 4a parked minors, code half (/feat memory-v2-minors 2026-11-01, e4fb8f7 + 48ade8f: negated status words, dead empty steal, body `## ` refused at add, `_mem_blob` rc 1/2, rc 6 names dropped partial stages, reflow; A2 Index comment-edge + A7 rc 6 upgrade wording dropped as moot, 0 `## Index` left outside faunosteo). Doc half still open, next line. Original ledger `.superpowers/sdd/2026-10-27-memory-v2-write/progress.md`: empty `memory.lock.steal` never stale (manual rm); `## Index` comment-edge mismatch; `upgrade` header doc lacks the non-table refusal; memory-commit rc 6 message misleading on a v1→v2 heading-rewrite upgrade; labelled "not resolved yet" reads resolved on v2; body `## ` line splits an entry (refuse at add); `-C` + relative `--body-file` (say absolute in § WRITE); tour/deploy/audit-delta § WRITE pointer; reconcile.sh:24-25 and :41-42 stale comments; `_mem_blob` → `git cat-file blob`; evals template "Later status" line; partial stage dropped on rc 6; 39 pre-existing >80-char lines in reconcile.sh / memory-commit.sh. - [x] Phase 4a minors, doc half (/feat memory-v2-minors-docs 2026-11-01): § WRITE intro says every verb takes `-C` and `--body-file` is absolute; tour/deploy/audit-delta point at § WRITE; evals template `Later status` line; rc 6 text done by the code half's doc sync (18e6370). - [ ] MIGRATION.md:209 shows `memory.sh -C <project> add … --body-file …` with no absolute-path note (same trap as § WRITE, parked by the docs-half challenge 2026-11-01): next doc pass. - - [ ] memory.sh awk operand (security LOW 2026-11-01): a `--body-file` named `x=1.md` is read by awk as a variable assignment in `_mem_fence_open` and `_mem_body_heading` (stdin read, check bypassed; `cat` still inserts the body). Fix: `awk '…' < "$f"`. Also `_partial_stages` passes the path to `git ls-files -s --` as a glob pathspec (quote with `:(literal)`). + - [x] memory.sh awk operand (security LOW 2026-11-01): a `--body-file` named `x=1.md` is read by awk as a variable assignment in `_mem_fence_open` and `_mem_body_heading` (stdin read, check bypassed; `cat` still inserts the body). Fix: `awk '…' < "$f"`. Also `_partial_stages` passes the path to `git ls-files -s --` as a glob pathspec (quote with `:(literal)`). Done 2026-11-06 9b3961e (`_mem_path_safe` at entry points, LRN-265). - Facts 2026-10-24 (scratchpad memeval, 434 entries): registries ~1M chars, never in always-on context, read only by /feat /bugfix /ship-feature (analyze-before-plan); Index drift 6 rows; status in 3 places (title tag, body Status line, Index column) → reconcile false-open BLK-032..034; no single writer (Edit needs a Read of a 357k file, so real writes are ad hoc python/bash); 8 projects on this machine hold v1 registries. Verified 2026-10-25: `lib/reconcile.sh:60-67` drops the entry's OWN header while BLK-032..034 carry `[resolved]` there (the false-open); nothing machine-reads `## Index` (analyze-before-plan.md:42, reconcile.sh:9, test T1); 1 of 1,290 entries across the 8 projects above a 1% accent ratio. - `lib/memory.sh` = single writer, like gitflow.sh: `add <kind> --title --body-file [--status --supersedes]` allocates next ID from headings (never the Index) under `flock` (concurrent conversations, phase 5), appends the entry; `status <ID> <new>` appends a dated status line (append-only); `journal "<line>"`; `index` prints the Index on demand from headings; `check [--staged]` = the validator (heading pattern, ID = max+1 and unique, no removed line from an existing entry outside a /prune-memory commit, new BLK quotes ≥1 error verbatim). The validator runs in `add` and `check` + make test, NOT in the generated pre-commit (undecidable there, and it exits 0 on working branches). No English check (doctrine stays). - Status: `reconcile_blk_current_status` reads the own-header `[tag]` first, then "last status-bearing line wins" (one parser, shared by memory.sh status and reconcile). Fixes BLK-032..034 false-open; regression test on those three. @@ -88,7 +88,7 @@ Shared rules for every phase: - [x] **Phase 2, guards** (shipped 2026-11-02 on feature/phase2-guards, merge on user signal: bench `.claude/tasks/plans/2026-11-02-phase2-bench/` (16 ask, 7 deny approved; quoted finish rule, `gitflow_finish*`, `bash -s*` not approved), rtk rc 3 passthrough 60ee4a9, router write guard with a session skill latch 22ff57b + 9bbd1d5, code-limits hook f21e265, locks T62/T63 9887c14, settings 6899a72, release finish in the main loop 536d39e, doctrine 0bf4620, CHANGELOG c3a6977; contract `.claude/tasks/contracts/2026-11-02-phase2-guards-1545.md`) (redesigned 2026-10-25 after a 3-lens challenge, re-challenged the same day: native ask gate, guard hosted in model-router, interpreters in prose, commit-msg hook deferred) - [ ] Phase 2 residuals (stated 2026-11-02): Bash write forms are outside the routing guard (the harness auto-mode "prefer Bash" path); a register.ts reload resets the skill latch; `.claude/worktrees/` writes are code; code-limits state dirs stay in TMPDIR; not caught by a static rule: `… | bash -s`, a sourced `gitflow_finish`, `git -C <dir> merge` (soft_deny prose only). - - [ ] Phase 2 security gate follow-ups (2026-11-02, non-blocking): MEDIUM `rtk read -n .env` / `rtk read a.txt .env` typed directly pass every static deny (rc 3 → passthrough, no rule) → bench `Bash(rtk read * .env*)`, `Bash(rtk read * */.env*)` + `*/rtk` twins and teach phase2.jq the `* <path>` shape; LOW code-limits state dir (`mkdir -m 700`, owner check); LOW awk evasions (`system (`, `awk -f`, `gawk`/`mawk`); LOW pre-existing `cat x.key` (no dir prefix) parity gap; doctor.sh:255 jq message should name code-limits and push-guard. + - [ ] Phase 2 security gate follow-ups (2026-11-02, non-blocking): MEDIUM `rtk read -n .env` / `rtk read a.txt .env` typed directly pass every static deny (rc 3 → passthrough, no rule) → bench `Bash(rtk read * .env*)`, `Bash(rtk read * */.env*)` + `*/rtk` twins and teach phase2.jq the `* <path>` shape; LOW code-limits state dir (`mkdir -m 700`, owner check); LOW awk evasions (`system (`, `awk -f`, `gawk`/`mawk`); LOW pre-existing `cat x.key` (no dir prefix) parity gap; doctor.sh:255 jq message should name code-limits and push-guard. MEDIUM rtk read part done 2026-11-06 97c6afc (2 rules, bench R3-R7, LRN-266); the LOWs stay open. - [ ] User hand edit (phase 2 hand-over): remove the 6 dead deny entries (`Bash(docker run * -v /:*)`, `Bash(git push * :*)`, `Write(**/.git/config)`, `Write(**/.gitconfig)`, `Write(~/.gitconfig)`, `Write(~/.config/git/config)`) and, if wanted, the 6 obsolete `rtk cat|head|tail` forms; lib/tests/push-guard.test.sh T41 (the 4 Write lines) and T42 (base = last release) must be edited alongside. - Killed by the challenges: the phrase-list merge gate; the `$.ui.ask` mod gate (its BDR-068 exception detector was never true: finish runs in the user's reply turn; a hard_deny naming mod sources was the robustness BLOCKER); G2 destructive guard (BLK-022, stays a user-driven task); whole-file code-limit reports (1498 lines > 80 cols across 92 files, over-fires); parsing commit text from Bash; Bash write-form detection in the routing guard (no measured Bash evasion, every inline write was Edit/Write). - Merge gate = native `ask` rules in settings.json, no mod (user pick 2026-10-25; bench r3 G1-G7: all forms DENIED headless incl. `"$HOME"`, absolute path, after `source`; `start` RAN): `Bash(bash */gitflow.sh finish*)`, `Bash(gitflow_finish*)`, `Bash(git merge *)`; evaluate in the same bench `Bash(git pull *)` and `git push x:develop` forms before adding them. Trade-off accepted: the BDR-068 /close auto-finish gets one dialog click (ask beats allow, no exemption); release-executor finish prompts too (its dispatcher runs finish inline if a sub-agent cannot prompt, BLK-018 option b). hard_deny line: "never edit `permissions.ask` to skip the gate". @@ -119,11 +119,12 @@ Shared rules for every phase: - 4c follow-up from the 4b live proof (2026-11-04): `memory_pending` lists milestones of the current session only, so a `/capitalize` run right after `/clear` misses the previous session's `fix:`/finish milestones (they stay in the store). Option: list earlier-session milestones marked `(earlier session)`. Doctrine (capitalize before /clear) covers the normal path. - **4d feedback and promotion.** Plan r1 (draft, not challenged): `.claude/tasks/plans/2026-11-05-memory-feedback-4d-1834.md`. Log read 2026-11-05: 1 real record, no decision possible; it cannot show usefulness or misses alone and transcripts live 7 days. Order: 4d.1 log fields `cands` + `ms` → 4d.2 weekly reader (log × transcripts, labels.tsv) → 4d.3 gate (≥20 prompt + ≥10 tool injections, or 5 weeks) with thresholds fixed now → 4d.4 /prune-memory + BDR-100 promotion, conditional. Starts after the 4c merge; 4 open choices in the plan. - [ ] shortcut: the injection log lives under `l:<root>` store keys (about 28 KiB each, 200 records and 64 KiB at most); `sweepLogs` counts them with the `p:` keys and evicts the oldest log key (by its newest record, never the current root's) once the total nears the engine's 4 MiB store cap; upgrade = one global log key or a smaller per-root cap (`mods/memory/hooks/register.ts`). - - [ ] residual: the pre-existing `memory.sh check` call in `hooks/session-start.sh` is not time-bounded (the digest's `memory.sh index blocker` call is); upgrade = wrap it in `timeout 2`. + - [x] residual: the pre-existing `memory.sh check` call in `hooks/session-start.sh` is not time-bounded (the digest's `memory.sh index blocker` call is); upgrade = wrap it in `timeout 2`. Done 2026-11-06 d93f06c (SD16). - [x] BLK-043 hotfix merged 2026-11-06 (`bd5e661` main, `7e47bea` develop, back-merged into feature/memory-recall `3564e3e`, worktree removed). - [x] BLK-043 Part B: suite-wide `claude` PATH stub + final empty-log check in `lib/tests/session-digest.test.sh` (SD0/SD15, done 2026-11-06 via /hotfix; security PASS, MEDIUM folded into the shortcut below). - - [ ] shortcut (BLK-043 gate 2 LOWs): `lib/tests/detect-plan.test.sh` unchecked `mktemp -d` (empty WORK → real `claude probe`), `bash -c "source '$LIB'"` interpolation, no `GIT_CEILING_DIRECTORIES` on hook runs; and the memory, graphify-gate, push-guard suites run the hook with no `claude` stub. Upgrade = `|| exit 1` + `command -v claude` assert, positional args, ceiling dir, shared stub helper. Same gap in `lib/tests/session-digest.test.sh` SD0 (gate MEDIUM 2026-11-06): `claude probe` runs before any check that the stub is first on PATH (stub write failure or noexec TMPDIR → real CLI), a red SD0 does not stop the suite; LOW: log path interpolated into the generated stub unquoted. + - [x] shortcut (BLK-043 gate 2 LOWs): `lib/tests/detect-plan.test.sh` unchecked `mktemp -d` (empty WORK → real `claude probe`), `bash -c "source '$LIB'"` interpolation, no `GIT_CEILING_DIRECTORIES` on hook runs; and the memory, graphify-gate, push-guard suites run the hook with no `claude` stub. Upgrade = `|| exit 1` + `command -v claude` assert, positional args, ceiling dir, shared stub helper. Same gap in `lib/tests/session-digest.test.sh` SD0 (gate MEDIUM 2026-11-06): `claude probe` runs before any check that the stub is first on PATH (stub write failure or noexec TMPDIR → real CLI), a red SD0 does not stop the suite; LOW: log path interpolated into the generated stub unquoted. Done 2026-11-06 dc5f127 + 7ca6b18 (shared `lib/tests/claude-stub.sh`, 6 suites, BLK-045). - [ ] BLK-044: trace origin of `oom_score_adj=-1000` on claude processes; set `OOMScoreAdjust` on the `cc` scope so a runaway claude dies first. + - [ ] safety-residuals gate LOWs (2026-11-06, bugfix/safety-residuals): `rtk read -n server.key` / `rtk read id_rsa` at repo root pass (`.key`/`.pem`/`id_*` rtk denies all need `*/`; pre-existing, bench before adding); session-start `memory.sh check` and digest unbounded when `timeout` is absent (stock macOS); pre-commit allowlist fails open if `git diff --cached` errors (pre-existing, Gitea backstop); `lib/memory.sh` `_mem_path_safe` line > 80 chars; `claude-stub.sh` interpolates the mktemp log path into the generated stub (test-only). - Proof: recall precision on ≥20 real prompts and ≥10 real errors, target ≥ the 14/22 baseline; digest after a real compaction; redaction test on the ledger; `/context` delta; captured-failure demo: an error from session N recalled in session N+1. ### Actionable diff --git a/.claude/tasks/contracts/2026-11-06-safety-residuals-1530.md b/.claude/tasks/contracts/2026-11-06-safety-residuals-1530.md new file mode 100644 index 0000000..41dbedd --- /dev/null +++ b/.claude/tasks/contracts/2026-11-06-safety-residuals-1530.md @@ -0,0 +1,65 @@ +# CONTRACT — safety-residuals +- date: 2026-11-06 | flow: bugfix | branch: bugfix/safety-residuals (off develop ddb04f4) +- status: active +- plan: .claude/tasks/plans/2026-11-06-safety-residuals-1530.md (r3) + +## REQUEST (verbatim — IMMUTABLE) +dans ce cas merge it. puis on fait le bugfix pours 1 2 3 4 5 et on verra ensuite pour la 4d + +(context: the 5 items of the /reconcile 2026-11-06 report: 1 suites that can reach the real claude CLI; 2 `rtk read -n .env` passes every deny; 3 session-start `memory.sh check` unbounded; 4 memory.sh awk reads an assignment-shaped path as an assignment; 5 pre-commit `.claude/**` exemption too wide.) + +## CLARIFICATIONS +Q: item 5 allowlist? / A: .claude/memory, .claude/tasks, .claude/audits, .claude/deploy (+ .githooks); .claude/settings.json NOT exempt. [gated 2026-11-06] +Q: shape? / A: one bugfix branch, one commit per item, order 4, 3, 1, 2, 5; final gates over the range. [gated 2026-11-06] +Q: safety / A: every hook-running suite, lib/gitflow-test.sh and the bench run under `systemd-run --user --scope -q -p TasksMax=256`; the real claude CLI runs only inside the bench's run.sh (--setting-sources local); bench run from a cwd with no .env; settings.json written via jq to tmp, `jq empty`, mv. [gated 2026-11-06] +Q: criterion 8 scope (GATE 1 ECARTS 2026-11-06) / A: orchestrator ruling: "shellcheck clean" means no NEW finding vs develop (ddb04f4) on every touched shell file; the 4 findings already on develop's memory.test.sh (SC2016 x3, SC1090) are out of scope. No new `# shellcheck disable` anywhere in the range. [gated 2026-11-06] +Q: item 2 gate / A: deny lines added ONLY if R3, R4, R6, R7 DENIED and R5 RAN, each `sent` = its cmd, every control RAN; otherwise item 2 stops, nothing added, reported. [gated 2026-11-06] + +## ACCEPTANCE CRITERIA +1. Item 4: assignment-shaped body file and check dir are read as files; existing output unchanged; memory suite green. + CHECK: cd /home/bchanot/Documents/claude && grep -q '_mem_path_safe' lib/memory.sh && systemd-run --user --scope -q -p TasksMax=256 env PATH="$HOME/.bun/bin:$PATH" bash lib/tests/memory.test.sh </dev/null >/home/bchanot/.cache/claude-tmp/claude-1000/-home-bchanot-Documents-claude/049658c4-3f30-4849-8ba6-906177262d8a/scratchpad/c1.out 2>&1 && echo C1_GREEN + EXPECT: C1_GREEN + EVIDENCE: MET exit=0 marker-found :: C1_GREEN + (amended 2026-11-06 by the orchestrator: bun prepended to PATH, T18 needs it and the Bash tool PATH lacks ~/.bun/bin) +2. Item 3: the session-start `memory.sh check` call is time-bounded; session-digest suite (with its new hang case) green. + CHECK: cd /home/bchanot/Documents/claude && systemd-run --user --scope -q -p TasksMax=256 bash lib/tests/session-digest.test.sh </dev/null >/home/bchanot/.cache/claude-tmp/claude-1000/-home-bchanot-Documents-claude/049658c4-3f30-4849-8ba6-906177262d8a/scratchpad/c2.out 2>&1 && echo C2_GREEN + EXPECT: C2_GREEN + EVIDENCE: MET exit=0 marker-found :: C2_GREEN +3. Item 1: shared helper fails closed; its own suite and every adopting suite green. + CHECK: cd /home/bchanot/Documents/claude && test -f lib/tests/claude-stub.sh && for t in claude-stub detect-plan graphify-gate push-guard cc; do systemd-run --user --scope -q -p TasksMax=256 bash lib/tests/$t.test.sh </dev/null >/home/bchanot/.cache/claude-tmp/claude-1000/-home-bchanot-Documents-claude/049658c4-3f30-4849-8ba6-906177262d8a/scratchpad/c3-$t.out 2>&1 || exit 1; done && echo C3_GREEN + EXPECT: C3_GREEN + EVIDENCE: MET exit=0 marker-found :: C3_GREEN +4. Item 1: every hook-running suite sources the helper and ends with a zero-call check; no inline `claude probe` left outside the helper. + CHECK: cd /home/bchanot/Documents/claude && for t in detect-plan session-digest graphify-gate memory push-guard; do grep -q 'claude-stub.sh' lib/tests/$t.test.sh || exit 1; done && ! grep -l '^claude probe' lib/tests/*.test.sh | grep -q . && echo C4_WIRED + EXPECT: C4_WIRED + EVIDENCE: MET exit=0 marker-found :: C4_WIRED +5. Item 2: bench evidence recorded in results.tsv for R3-R7 and, only if every row met its want, the 2 deny rules are present and settings.json is valid JSON. + (judged by the verifier from results.tsv and settings.json; push-guard T63 pins both rules when added) +6. Item 5: allowlist hook; rules, settings.json and a rules→tasks rename blocked on develop; memory, tasks, deploy, audits allowed; both hook copies equal the emitter. + CHECK: cd /home/bchanot/Documents/claude && grep -q -- '--no-renames' lib/gitflow.sh && cmp -s githooks/pre-commit .githooks/pre-commit && systemd-run --user --scope -q -p TasksMax=256 bash lib/gitflow-test.sh </dev/null >/home/bchanot/.cache/claude-tmp/claude-1000/-home-bchanot-Documents-claude/049658c4-3f30-4849-8ba6-906177262d8a/scratchpad/c6.out 2>&1 && echo C6_GREEN + EXPECT: C6_GREEN + EVIDENCE: MET exit=0 marker-found :: C6_GREEN +7. Item 5 citers: no doctrine line still says `.claude/**` is exempt. + CHECK: cd /home/bchanot/Documents/claude && ! grep -n '\.claude/\*\*' CLAUDE.global.md lib/gitflow-aiguillage.md settings.json | grep -i 'exempt' && echo C7_CITERS + EXPECT: C7_CITERS + EVIDENCE: MET exit=0 marker-found :: C7_CITERS +8. shellcheck clean on every touched shell file. + CHECK: cd /home/bchanot/Documents/claude && shellcheck lib/memory.sh hooks/session-start.sh lib/gitflow.sh lib/tests/claude-stub.sh lib/tests/claude-stub.test.sh lib/tests/detect-plan.test.sh lib/tests/session-digest.test.sh lib/tests/cc.test.sh .claude/tasks/plans/2026-11-02-phase2-bench/bench.sh .claude/tasks/plans/2026-11-02-phase2-bench/run.sh && echo C8_LINT + EXPECT: C8_LINT + EVIDENCE: MET exit=0 marker-found :: C8_LINT +9. Each regression test is red against develop's code and green after (memory x=1.md, session-start hang, helper fail-closed, hook rename/rules cases). + (judged by the verifier from the executor reports: each item report names its red-before evidence) + +## FILE SCOPE +- lib/memory.sh, lib/tests/memory.test.sh +- hooks/session-start.sh, lib/tests/session-digest.test.sh +- lib/tests/claude-stub.sh (new), lib/tests/claude-stub.test.sh (new), lib/tests/{detect-plan,graphify-gate,push-guard,cc}.test.sh +- .claude/tasks/plans/2026-11-02-phase2-bench/{bench.sh,run.sh,README.md,cases.tsv,results.tsv}, settings.json +- lib/gitflow.sh, lib/gitflow-test.sh, githooks/pre-commit, .githooks/pre-commit, CLAUDE.global.md, lib/gitflow-aiguillage.md + +## EXECUTION LOG (orchestrator, from executor reports + own reruns) +- Item 4 9b3961e — red on HEAD lib: `FAIL T19-assign-body-heading-rc`, `FAIL T19b-assign-body-written`, `FAIL T19c-assign-dir-read`; after: memory PASS=268 FAIL=0 (bun on PATH). +- Item 3 d93f06c — red with develop's hook: `FAIL SD16-hang-bounded: got[no] want[yes]`; after: session-digest 55/0. +- Item 1 dc5f127 — red with a helper copy lacking `stub_first_or_die claude`: `FAIL Ta-message`, `FAIL Ta-sentinel-absent` (fake claude reached); after: claude-stub 5/0, detect-plan 8/0, session-digest 54/0, graphify-gate 18/0, memory 269/0, push-guard 130/0, cc 30/0. +- Item 2 97c6afc — bench results.tsv: R3 DENIED, R4 DENIED, R5 RAN, R6 DENIED, R7 DENIED, every -ctl RAN, every `sent` = cmd, mode auto; red: push-guard T63 FAIL before the settings edit, 130/0 after; settings.json valid JSON, diff = 2 added deny lines. +- Item 5 c5bd0f8 — red on the old emitter: T21d, T21e, T21f, T21h FAIL (196/4); after: gitflow-test 200/0, review-guards 5/0 (G5 drift green). Deviation: `githooks/` regenerated through `_gitflow_write_hook` (the writer `global-hooks` calls) instead of `global-hooks`, which may run `git config --global core.hooksPath`; `cmp githooks/pre-commit .githooks/pre-commit` holds. diff --git a/.claude/tasks/plans/2026-11-06-safety-residuals-1530.md b/.claude/tasks/plans/2026-11-06-safety-residuals-1530.md new file mode 100644 index 0000000..e0a6077 --- /dev/null +++ b/.claude/tasks/plans/2026-11-06-safety-residuals-1530.md @@ -0,0 +1,184 @@ +# Bugfix plan: five safety residuals from finished phases (2026-11-06) — r3 + +Branch: bugfix/safety-residuals off develop (ddb04f4). One commit per item. +r2 after the 3-lens challenge (correctness CONCERNS(2), robustness +CONCERNS(5), simplicity CONCERNS(1); no BLOCKER). Changes vs r1 are tagged +[r2: lens n]. + +## RELATED MEMORY +- BLK-043 / LRN-263 (item 1): hooks never call the claude CLI; hook-running + tests stub it and cap tasks. Item 1 completes LRN-263's "future use". +- BDR-136 (item 2): shell rules are added only once bench-proven; the bench + is `.claude/tasks/plans/2026-11-02-phase2-bench/`. +- LRN-074 (item 4): system awk may be mawk; no gawk-only flag. +- BDR-045, LRN-084 (item 5): the `.claude/**` exemption was kept so the + side-car memory commit and standalone /capitalize, /close land in place; + BDR-045 rejected "narrow by size/scope" as fuzzy. Item 5 narrows by an + exact path allowlist (user choice 2026-11-06), a partial revision of + BDR-045, recorded as a new BDR on commit. + +## Safety rules for the whole run +- Every run of a hook-running suite, of `lib/gitflow-test.sh` and of the + bench goes through `systemd-run --user --scope -q -p TasksMax=256`. +- The real `claude` CLI is never run, except by the bench's `run.sh` + (`claude -p --setting-sources local`: no user settings, no hook). +- The bench runs only after its own hardening (item 2 step 1) and from a + cwd holding no `.env` (the session scratchpad). +- Live paths: `settings.json`, `lib/`, `githooks/` (~/.claude links to + this tree; global core.hooksPath = ~/.claude/githooks). settings.json is + written only via `jq … > tmp && jq empty tmp && mv tmp settings.json`. + [r2: robustness 7; r3: confirm 2] +- Rollback of an open item: `git restore --staged --worktree -- <its + paths>` (or `git stash push -- <paths>`), THEN `git checkout develop`; + the next session start in each onboarded repo re-syncs its `.githooks/` + from the (restored) lib. [r3: confirm 1] +- Execution: one item at a time, in order 4, 3, 1, 2, 5 (smallest blast + radius first, the machine-wide guard last); each item committed once + its own suites pass, before the next starts. + +## 1. Suites that can reach the real claude CLI + +ROOT CAUSE: the LRN-263 stub is copied inline in detect-plan and +session-digest and is fail-open: `claude probe` runs before any check that +`command -v claude` is the stub; a failed stub write (no `set -e`) or a +noexec TMPDIR (command -v skips a non-executable file) reaches the real +CLI; a red positive control does not stop the suite. graphify-gate (:61), +memory (`banner()` :689) and push-guard (:356) run hooks/session-start.sh +with no stub. cc.test.sh (:30-38) shims `claude`, `systemd-run`, `dtach` +with the same fail-open shape while lib/cc.sh runs `systemd-run … dtach … +exec claude` [r2: robustness 3]. A relative work dir passes a +same-cwd check but stops resolving after the `cd` every hook run does +[r2: robustness 4]. + +FIX: +- New `lib/tests/claude-stub.sh` (sourced): + - `stub_first_or_die <cmd> <expected-path>`: `command -v <cmd>` must + equal the path, else print `<cmd> stub not first on PATH` on stderr + and exit 1. + - `claude_stub_install <work-dir>`: refuse empty or missing dir; make it + absolute (`cd -P "$1" && pwd`) [r2: robustness 4]; write + `<dir>/stub/claude` (log path expanded at creation), `chmod +x`, each + step `|| exit 1`; prepend `<dir>/stub` to PATH and export it; + `stub_first_or_die claude <dir>/stub/claude`; positive control run as + a child from another cwd: `(cd / && claude probe)`, log must hold + exactly 1 line else exit 1 [r2: robustness 4]; empty the log; export + `GIT_CEILING_DIRECTORIES=<dir>` so no hook run walks into an enclosing + repo [r2: robustness 9, simplicity 3: applied uniformly]. + - `claude_stub_calls`: line count of the log. +- detect-plan, session-digest: inline stub replaced by the helper. +- graphify-gate, memory, push-guard: helper installed before the first + hook run (memory: directly above `banner()`, never near the top: $FIX is + the fixture repo itself) [r3: confirm 6]; each suite ends with `no-claude-calls` = 0 before its summary. +- cc.test.sh: after writing its shims, `stub_first_or_die` for claude, + systemd-run and dtach against `$FX/bin/*`. [r2: robustness 3] +- `X=$(mktemp -d) || exit 1` at the mktemp of each suite touched here + (detect-plan, session-digest, graphify-gate, memory, push-guard, cc). + [r2: robustness 10; no extra `[ -d ]`, simplicity 3] +- detect-plan: `bash -c 'source "$1"; detect_plan' _ "$LIB"` (both sites). +- Regression suite `lib/tests/claude-stub.test.sh`: + (a) fail-closed: in a subshell, `chmod() { :; }` shadows chmod so the + stub stays 0644; PATH also holds a second dir with a fake `claude` that + writes a sentinel; `claude_stub_install` must exit 1 with + `claude stub not first on PATH`, sentinel absent. + [r2: correctness 5, simplicity 2] + (b) relative dir: install from a relative dir name, then + `(cd / && command -v claude)` = the absolute stub path. + (c) happy path: rc 0, `claude_stub_calls` = 0 after install. + +## 2. `rtk read` with a leading flag or file on a root-level `.env` + +ROOT CAUSE: the rtk read deny twins were generated as `rtk read X*` and +`rtk read */X*`. A root-level target after a flag or another file +(`rtk read -n .env`, `rtk read a.txt .env`) matches neither; rtk rewrite +rc 3 passes it through (60ee4a9). Targets under a `*/` prefix are +already covered: the `*` right after `rtk read ` absorbs `-n sub` or +`a.txt sub` (matcher `*` spans spaces, bench A1, LRN-194(c)). +[r2: simplicity 1, correctness 6] + +FIX: +- Step 1, harden the bench before any run [r2: robustness 5]: + bench.sh `W="$(mktemp -d)" || exit 1`; run.sh `cd "${4:?}" || exit 1`, + with run.sh's usage line and README.md making `dir` mandatory. + [r3: confirm 7] +- Step 2, bench rows (cases.tsv), run from the scratchpad, contained: + - R3 deny `Bash(rtk read * .env*)`, cmd `rtk read -n .env` → DENIED. + - R4 deny `Bash(rtk read */.env*)` (the EXISTING rule), cmd + `rtk read -n sub/.env` → DENIED (proves no `* */X` twin is needed). + - R5 deny `Bash(rtk read * .env*)`, cmd `rtk read -n README.md` → RAN. + - R6 deny `Bash(*/rtk read * .env*)`, cmd + `/home/bchanot/.local/bin/rtk read -n .env` → DENIED. + [r2: robustness 8] + - R7 deny `Bash(*/rtk read */.env*)` (EXISTING), cmd + `/home/bchanot/.local/bin/rtk read -n sub/.env` → DENIED. [r3: confirm 5] + A NO_TOOL_CALL verdict, or a `sent` column that differs from the + cases.tsv cmd, is rerun once, not counted as a rule failure. + [r2: correctness 7; r3: confirm 4] +- Step 3, only if R3, R4, R6, R7 DENIED (each with `sent` = its cmd), R5 RAN and every control RAN: add + `Bash(rtk read * .env*)` and `Bash(*/rtk read * .env*)` to + `permissions.deny` (`.env.*` is contained in `.env*`), pin both in + push-guard's T63 list. Any other outcome → item 2 stops, reported, + nothing added. If R4 is not DENIED, item 2 stops too (the `*/` twins + then need their own bench). + +## 3. session-start `memory.sh check` not time-bounded + +ROOT CAUSE: hooks/session-start.sh:319 runs `bash "$_mem_lib" check +.claude/memory` unbounded; the digest (:377) uses `timeout 2` when present. + +FIX: same shape as the digest (`tmo=()`, `command -v timeout && tmo=(timeout +2)`, `"${tmo[@]}" bash …`, bash 3.2 safe as the digest is). Regression in +session-digest: a memory.sh that sleeps 10 s on `check` → hook returns in +< 3.5 s, rc 0 (mirror SD12). + +## 4. awk reads an assignment-shaped path operand as an assignment + +ROOT CAUSE: awk treats an operand matching `^[A-Za-z_][A-Za-z0-9_]*=` as a +variable assignment and reads stdin instead. memory.sh passes user paths as +awk operands: `--body-file` to `_mem_fence_open`, `_mem_body_heading` and +`_mem_entry_text` (the entry text itself is copied by awk, so today the +entry gets stdin's content, not the file's) [r2: correctness 4], and the +`check` / `upgrade` dir argument. + +FIX: `_mem_path_safe <p>`: prints `./<p>` only when p matches the +assignment shape, else p unchanged; empty in, empty out +[r2: correctness 2+3, robustness 1]. Applied to the body file in +`memory_add` and to the `check` / `upgrade` dir AFTER the +`${1:-.claude/memory}` default and the usage guard. Every existing output +stays byte-identical (T7f unchanged). Regression in memory.test.sh, every +call `</dev/null` [r2: correctness 4, robustness 11]: +`add … --body-file x=1.md` whose body holds an unfenced `## ` line → rc 2; +`add … --body-file x=1.md` with a clean body → the entry holds that body; +`check a=b` reads `a=b/*.md`. + +## 5. Pre-commit `.claude/**` exemption too wide + +ROOT CAUSE: lib/gitflow.sh emit (:490) whitelists any staged set under +`.claude/` or `.githooks/`, listed with `git diff --cached --name-only`, +which shows only a rename's destination [r2: correctness 8, +robustness 2]. + +FIX (user choice 2026-11-06: memory, tasks, audits, deploy; settings.json +NOT exempt): +- Emitter: exempt only when every staged path is under `.claude/memory/`, + `.claude/tasks/`, `.claude/audits/`, `.claude/deploy/` or `.githooks/`; + list with `git diff --cached --name-only --no-renames`; BLOCKED hint + names the allowlist. +- Order: emitter edit → tests (lib/gitflow-test.sh, contained) green on + the emitter → only then regenerate. [r3: confirm 2] +- Regenerate both hooks in the same commit: `.githooks/pre-commit` + (`bash lib/gitflow.sh install-hook`) and `githooks/pre-commit` + (`bash lib/gitflow.sh global-hooks "$PWD/githooks" '~/.claude/githooks'`); + drift proof T19a, T19d, G5. [r2: correctness 1, robustness 6] +- Tests in lib/gitflow-test.sh: relabel T3; add to T14/T21 on develop: + `.claude/rules/x.md` only → BLOCKED; `.claude/settings.json` only → + BLOCKED; `git mv .claude/rules/x.md .claude/tasks/x.md` → BLOCKED; + memory-only, tasks-only, deploy-only, audits-only → allowed. + [r3: confirm 3] [r2: simplicity 4] +- Citers reworded to the allowlist: CLAUDE.global.md:160, :172, :174; + settings.json:606 (environment prose); lib/gitflow-aiguillage.md:35. + Grep `\.claude/\*\*` again after the edit. [r2: simplicity 4] + +RISK: medium. Item 5 changes a guard every repo runs: committing +`.claude/settings.json` or rules on develop now needs a branch (1 such +commit in develop's history, 858e7a7). Item 2 depends on the bench. +Items 1, 3, 4 are local to tests and libs.