diff --git a/.claude/memory/blockers.md b/.claude/memory/blockers.md index 07b69a4..c79ae7c 100644 --- a/.claude/memory/blockers.md +++ b/.claude/memory/blockers.md @@ -1,4 +1,5 @@ --- +format: 2 type: blockers_registry entry_prefix: BLK schema: @@ -16,45 +17,6 @@ rules: # Blockers registry (BLK) -## Index - -| ID | Date | Friction | Status | -|----|------|---------|--------| -| BLK-001 | 2026-04-22 | `rtk curl` breaks JSON pipelines | upstream | -| BLK-002 | 2026-04-23 | `rmdir` denied in sandbox on empty directory | resolved | -| BLK-003 | 2026-05-12 | `scripts/screenshot.mjs` hardcoded macOS path blocks PNG cards on Linux | upstream | -| BLK-004 | 2026-05-20 | `/ship-feature` wrapper at `~/.claude/commands/` points to deleted agent files post-refactor | resolved | -| BLK-005 | 2026-05-21 | gstack submodule rename (checkpoint→context-save) breaks profile entries | resolved | -| BLK-006 | 2026-05-21 | `profile.sh current` false-negative via `~/.claude` symlink (`cd` not `cd -P`) | resolved | -| BLK-007 | 2026-06-02 | 6 gstack source skills (ios-*, spec) unlinked post-bump — invisible to profiles + `gstack on` | resolved | -| BLK-008 | 2026-06-23 | gstack ./setup on Ubuntu 26.04: Playwright chromium unsupported → gstack browser (/browse, /qa, screenshots) silently dead | resolved (211c7d4) | -| BLK-009 | 2026-06-25 | user-level path-scoped rules (`paths:` frontmatter in `~/.claude/rules/`) never inject — broken in CC 2.1.190 (#21858) | resolved (2026-07-06) | -| BLK-010 | 2026-06-27 | init-project: scaffold (STEP 5) + bootstrap README (5b) have no deterministic commit owner; worktree `add -b` on unborn HEAD | resolved (uncommitted) | -| BLK-011 | 2026-06-27 | init-project STEP 13 GSD post-FINISH creates ROADMAP.md → stranded doc (3rd post-FINISH artifact) | resolved (STEP 12 removed) | -| BLK-012 | 2026-06-29 | gitflow_init half-applied: socle-commit failure swallowed → hook activated on partial run → re-run self-blocks | resolved | -| BLK-013 | 2026-06-30 | `make plugin` Error 127 — npm absent on apt-`nodejs` host (Step 4 gsd-pi aborts, Steps 5-10 + residual cleanup never run) | resolved (env) | -| BLK-014 | 2026-07-01 | `make install` aborts npm EEXIST on `~/.local/bin/claude` when claude already installed via native installer — no presence guard | resolved | -| BLK-015 | 2026-07-03 | `gitflow_finish` ignored its ` ` args → merged the CHECKED-OUT branch not the one named → wrong-branch merge (audit LOT3) | resolved | -| BLK-016 | 2026-07-04 | rtk compression PATH-dead 30 days — 6/5070 Bash commands compressed (~460K tokens missed); installer sources cargo env so its own check passes, Claude tool shell never gets ~/.cargo/bin | resolved | -| BLK-017 | 2026-07-17 | Bing Webmaster API unusable for a multi-client agency: OAuth swamp (localhost redirect refused, rotated single-use refresh tokens race our parallel dispatch), API key = wrong model (client-owned sites) | open/deferred | -| BLK-018 | 2026-07-20 | release-executor finish span blocked by permission classifier (human signal invisible to subagent) — 2026-07-… | open | -| BLK-019 | 2026-09-01 | notify-attention bell silent, toast OK (VS Code client default) — 2026-09-01 | superseded by BLK-028 | -| BLK-020 | 2026-09-02 | notify-attention: both channels dead on one VS Code client — 2026-09-02 | superseded by BLK-028 | -| BLK-021 | 2026-09-22 | Bash tool dead mid-session ("every command exits 1"): /tmp usrquota blown by a dead session's probe HOMEs — 2… | open | -| BLK-022 | 2026-09-22 | `hooks/guard-bash.sh` withheld by the safety classifier; executable spec shipped instead — 2026-09-22 | open | -| BLK-023 | 2026-09-28 | floor-guard SKIP pattern `xit(` (Jasmine) matches any `exit(` in python/JS test helpers → false ECARTS; workaround: no `exit(` in inline python, bash derives rc from output — 2026-09-28 | resolved | -| BLK-024 | 2026-09-29 | update-all.sh re-fetched vendored skills but never re-applied the effort pins (lost until next `make plugin`); my first fix placed the re-apply BEFORE the late 21st refresh — rtk-truncated grep read as complete — 2026-09-29 | resolved | -| BLK-025 | 2026-09-30 | deny rule `Bash(npm install -g *)` bypassed unknowingly by the alias `npm i -g` (pasted user instruction ran as typed); deny patterns are literal prefixes — 2026-09-30 | resolved (partial) | -| BLK-026 | 2026-10-06 | `make test` red on macOS: 13 suites, GNU-only idioms in suite + 7 libs (SIGPIPE under pipefail, `sed -i`, `wc` padding, `stat -c`, `realpath -m`, bare `timeout`, `grep -oP`) | resolved | -| BLK-027 | 2026-10-06 | this machine never ran `make link`/`make plugin`: no global `core.hooksPath` → post-commit push never fired, branches landed ahead of upstream; 11 vendored skills + `~/.claude/.env` missing | resolved (link) / open (plugin) | -| BLK-028 | 2026-10-06 | notify-attention on a VS Code client: bell + toast silent-degradation faults (merge of BLK-019 + BLK-020): terminalBell sound default off, ext hooks only terminals born after activation, Code muted in Windows mixer | resolved | -| BLK-029 | 2026-10-08 | Claude Code mods (2.1.294): alias → id resolution for a model set by a hook lags the Agent tool's (`sonnet` → `claude-sonnet-5`, 404); Agent tool schema refuses full ids | upstream | -| BLK-030 | 2026-10-15 | model-router kept routing best-tier phases to Fable out of usage credits: each new session + each hold lapse lost a turn to 429 `model_requires_usage_credits`; breaker reactive only | resolved | -| BLK-031 | 2026-10-16 | model-router: session starting on Fable w/o credits lost 1st turn + each hold lapse; probe skipped kept cur | resolved | -| BLK-032 | 2026-10-19 | Main loop pinned on Fable in long sessions: session model Fable 1M + downgrade cap 120k + prompt rule `plan` → inline code on Fable xhigh; feat A+B shipped (BDR-123), closed by feat C 786ee13 | resolved | -| BLK-033 | 2026-10-21 | Guardrails residuals: probe trusted plan `supabase.url`, redirects free of budget, unread bodies read CLOSED, `str(URLError)` hid budget signal; rules 5 FP / 7 misses | resolved | -| BLK-034 | 2026-10-22 | mods.test.sh red on CLI 2.1.306: whole-output `warning` grep caught advisory plugin-directory section (ICON_MISSING, blocking: false); verdict = `--strict` exit code now | resolved | - --- ## BLK-001 — `rtk curl` returns compressed schema in pipes @@ -240,6 +202,7 @@ rules: - **Solution**: `"accessibility.signals.terminalBell": { "sound": "on" }` in CLIENT-side user settings.json (`c:/Users//AppData/Roaming/Code/User/`). Unreachable from remote: real SSH remote, not WSL (no `/mnt/c`, `/proc/version` no Microsoft). User applied, retest → both channels OK. - **Status**: resolved (per-client-machine, not repo-portable). - **Reference**: `~/.claude/hooks/notify-attention.sh` header already documented the setting; never applied. New client machine → bell mute again while toast works. Silent-degradation class [[LRN-047]]. +- **Status (2026-10-28, upgrade)**: superseded by BLK-028 ## BLK-020 — notify-attention: both channels dead on one VS Code client — 2026-09-02 - **Friction**: client-side prereqs applied on Windows box (ext `wenbopan.vscode-terminal-osc-notifier` + `accessibility.signals.terminalBell` sound:on), window reloaded. AskUserQuestion → nothing. `idle_prompt` 90s wait → nothing. Direct write `\a\a` + OSC 777 to claude own pty (`/dev/pts/2`) → nothing. Second client machine, same SSH server, same hook, same registries → both channels OK. @@ -260,6 +223,7 @@ rules: - **Status**: resolved (A: ext hooks only terminals born after activation → install ext THEN start/re-attach session; B: Code app volume 0 in Windows mixer). - **Lesson**: two independent client faults presented as one symptom ("nothing works"). Splitting probe = run signal in FRESH terminal + play VS Code's own sound preview. Preview bypasses terminal/BEL/hook/dtach/ext → isolates renderer audio in one step. Do that FIRST next time, before any server-side archaeology. - **Reference**: [[BLK-019]] bell-only variant (resolved differently — setting alone insufficient here), [[LRN-145]] terminalSequence-not-/dev/tty pattern. Silent-degradation class [[LRN-047]]. +- **Status (2026-10-28, upgrade)**: superseded by BLK-028 ## BLK-021 — Bash tool dead mid-session ("every command exits 1"): /tmp usrquota blown by a dead session's probe HOMEs — 2026-09-22 - **Friction**: previous session on `feature/21st-cli-migration` lost its shell before tests + commit: every Bash call, `echo` included, returned 1. Its harness file `imptest2/step8d-test.sh` landed as 0 bytes. @@ -335,18 +299,21 @@ rules: - **Reference**: [[BLK-030]], [[LRN-218]], contract `.claude/tasks/contracts/2026-10-16-router-probe-session-model-1850.md`. ## 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] +- **Date**: 2026-10-19 - **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] +- **Date**: 2026-10-21 - **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] +- **Date**: 2026-10-22 - **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. diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 7bffcd9..b38e7c9 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -1,4 +1,5 @@ --- +format: 2 type: decisions_registry entry_prefix: BDR schema: @@ -18,133 +19,6 @@ rules: # Decisions registry (BDR) -## Index - -| ID | Date | Title | Status | -|----|------|-------|--------| -| BDR-001 | 2026-04-22 | Uniform --help helper via session-start hook (option C) | accepted · won't-build 2026-06-30 | -| BDR-002 | 2026-04-23 | Move tasks/ + introduce memory + audits under .claude/ | accepted | -| BDR-003 | 2026-04-23 | Gitignore wildcard + negations pattern for .claude/ | accepted | -| BDR-004 | 2026-04-27 | Adopt auto permission mode as default | accepted | -| BDR-005 | 2026-04-27 | `motion` as default animation library; advisor stays read-only | accepted | -| BDR-006 | 2026-05-03 | Caveman as 4th always-on plugin (output compression) | accepted | -| BDR-007 | 2026-05-04 | Skill profiles partition gstack by usage (design / dev / qa / audit / minimal) | accepted | -| BDR-008 | 2026-05-04 | Profile system v2: extend to plugins + MCPs + CLIs (web/seo/web-full/backend) | accepted | -| BDR-009 | 2026-05-05 | Mandate caveman format on .claude/memory/ registries | accepted | -| BDR-010 | 2026-05-07 | Gate GEO independently at ≥17/20 in client-handover pipeline | accepted | -| BDR-011 | 2026-05-07 | Client handover deliverable: 4-chapter structure + ZenQuality branded HTML/PDF | superseded by BDR-013 (6-chapter doc) | -| BDR-012 | 2026-05-07 | client-handover cover: white bg + green accents + PNG logo default | accepted | -| BDR-013 | 2026-05-11 | client-handover: 6-chapter doc — promote scores §2 + NAP §4 | accepted | -| BDR-014 | 2026-05-11 | Personal SKILL.md descriptions: "Use when [triggers]…" pattern + 1024-char spec limit | accepted | -| BDR-015 | 2026-05-12 | Exclude broken gstack symlinks from /darwin-skill scope (external ownership) | accepted · trigger cleared by BDR-043 | -| BDR-016 | 2026-05-15 | doc-syncer: README AUTO+unconditional, DEPLOY.md prod-only + 14-section VPS template | accepted | -| BDR-017 | 2026-05-18 | `full` profile = web-full + plan + dev superset for /init-project MVP | accepted | -| BDR-018 | 2026-06-02 | `profile gstack on/off` verb — toggle gstack keeping active-profile label | accepted | -| BDR-019 | 2026-06-09 | Remove `disable-model-invocation` repo-wide — align skills with CLAUDE.md routing | accepted | -| BDR-020 | 2026-06-11 | `/audit-delta`: per-axis SHA markers + always-on fix gate + unreachable-first-run = full report-only | accepted | -| BDR-021 | 2026-06-27 | CLAUDE.md restructure: contradiction purge, project-specific sections labeled, critical sections never compressed | accepted | -| BDR-022 | 2026-06-18 | doc-syncer scoped to public docs; `.claude/` + `CLAUDE.md` read-only context, never targets; conventions + clean mode | accepted | -| BDR-023 | 2026-06-19 | Merge /close into /capitalize — 2 modes + TODO reconcile; /close alias | accepted | -| BDR-024 | 2026-06-27 | `profile show --plain` = claude-free parse contract for the design gate | accepted | -| BDR-025 | 2026-06-27 | Design gate profile-based; remedy `/profile design`; magic required-but-manual; unknown → fail-visible; claude via PATH-repair | accepted | -| BDR-026 | 2026-06-27 | Secret source-of-truth outside the repo (`~/.claude/.env`) reached via a `repo/.env` symlink | accepted | -| BDR-027 | 2026-06-27 | Minimal npm-via-nvm bootstrap over a centralized prereq lib | accepted | -| BDR-028 | 2026-06-27 | Hand-curated config install-immutable (auto-revert guard) + de-vendor installer-managed skills | accepted | -| BDR-029 | 2026-06-27 | Installer auto-fixes gstack browser on an OS newer than its pinned Playwright supports | accepted | -| BDR-030 | 2026-06-27 | gstack skills activated ON-DEMAND per profile, not pre-installed; OFF by default stays | accepted | -| BDR-031 | 2026-06-27 | global CLAUDE.md lightening = COMPRESSION, not path-scope / externalization | superseded by BDR-125 · 275-line target superseded by BDR-062 | -| BDR-032 | 2026-06-27 | skill `/validate` → `/web-validate` (rename user surface, keep internals) | accepted | -| BDR-033 | 2026-06-27 | design-gate §4: anim-lib suggestion — suggest-only, non-blocking, stateless 1-line | accepted | -| BDR-034 | 2026-06-26 | Coupled-capitalize invariant v1 — memory commit auto per dev flow (Frame 2) | accepted | -| BDR-035 | 2026-06-26 | Analyze-before-plan invariant v1 — read-before bookend of coupled-capitalize | accepted | -| BDR-036 | 2026-06-27 | Doc-sync coupled invariant — commit docs doc-syncer patches (twin of BDR-034, BUILT not reordered) | accepted | -| BDR-037 | 2026-06-27 | v2 capitalize Stop-hook rejected → wire /capitalize+/close to the include | accepted | -| BDR-038 | 2026-06-27 | deploy skill: per-project learning runbook, two-moment cold-resume | superseded by BDR-054 (NEXT.sh, hand-back) | -| BDR-039 | 2026-06-29 | Gitea branch protection = Option-1 owner-pushable, not require-PR | accepted | -| BDR-040 | 2026-06-29 | doc-syncer MINOR-shape oracle: deterministic floor under LLM's MINOR call | accepted | -| BDR-041 | 2026-06-30 | /reconcile = deterministic declared-vs-real engine + thin gated skill (reconciler, not lister) | accepted | -| BDR-042 | 2026-06-30 | /release-candidate = thin orchestrator over gitflow release; the tag lives in the skill, not the lib | accepted | -| BDR-043 | 2026-06-30 | BDR-015 trigger cleared — 5 ex-broken gstack symlinks repaired → darwin re-baseline back in scope (unblocked, NOT run) | accepted | -| BDR-044 | 2026-06-30 | auto-skill-dispatch won't-build — under-routing fear inverted to over-routing by cartography, then measured: model discriminates (clear→route, ambiguous→ask, trivial→abstain) | accepted · won't-build | -| BDR-045 | 2026-07-01 | Standalone memory/doc skills branch to chore/* via aiguillage (hook exemption kept) | accepted | -| BDR-046 | 2026-07-01 | Claude Code installs via official native installer (curl claude.ai/install.sh), drop npm from install.sh | accepted | -| BDR-047 | 2026-07-01 | ECC audit → zero import; local config ahead of reference | accepted | -| BDR-048 | 2026-07-03 | semgrep security gate: engine version + rulesets PINNED, never --config auto; upgrade = deliberate visible human jump | accepted | -| BDR-049 | 2026-07-03 | verifier = fresh + blind (no iteration history) + disk-contract + PROOF-or-fail; mute ≠ PASS; scope enrichment via human micro-gate | accepted | -| BDR-050 | 2026-07-03 | universal pipeline (contract→dev inline→fresh verify→fresh security, loops bounded 3× in main loop) with per-flow weighting; hotfix failure = revert not loop | accepted | -| BDR-051 | 2026-07-04 | contract enrich-at-gate: the contract grows ONLY at a human micro-gate ([gated] marker); the verifier judges the ENRICHED contract, not the seed | accepted | -| BDR-052 | 2026-07-05 | /tour auto mode = branch-as-gate: no mid-run approval gates; unmerged chore branch + per-project TOUR.md = deferred human gate; reconcile report-only; loop bounded 3× | accepted | -| BDR-053 | 2026-07-06 | ctx7 single surface: keep find-docs skill, kill context7.md rule | accepted | -| BDR-054 | 2026-07-06 | supersede BDR-038 NEXT.sh/hand-back artifacts — shipped impl removed both (52f6678, LRN-102) | accepted | -| BDR-055 | 2026-07-07 | job5: delete memory-commit/doc-commit `pending` verbs — v2 hook rejected (BDR-037), J4-17 closed MOOT | accepted | -| BDR-056 | 2026-07-07 | job6: deps policy = latest gated by integration, not KEEP-PINNED by default | accepted | -| BDR-057 | 2026-07-07 | job7: secrets by reference not by value; redact at capture, not just at rest | accepted | -| BDR-058 | 2026-07-07 | job8: darwin-skill reinstall full pinned tree, detached HEAD (skills CLI single-file-fetch gap) | accepted | -| BDR-059 | 2026-07-07 | job8: explicit ask-gate for all 4 magic MCP tools, empty allow stays empty | accepted | -| BDR-060 | 2026-07-08 | job9: CC orchestration floor = v2.1.172 (nested dispatch), supersedes implicit v2.1.83 whole-system floor | accepted | -| BDR-061 | 2026-07-08 | job9: seo/geo analyzers → fix-bundle→L1 by doctrine (validator-analyzer pattern), not by version constraint | accepted | -| BDR-062 | 2026-07-08 | supersede BDR-031's 275 CLAUDE.md target — 305 assumed reality (extraction done at job1; more compression costs clarity > tokens); guard threshold realigned 280→320 | accepted | -| BDR-063 | 2026-07-10 | GSC multi-account: OAuth2 installed-app flow + label-keyed token store, explicit (account,property) args, no global state | accepted | -| BDR-064 | 2026-07-14 | global memory split: repo file → CLAUDE.global.md (deployed name unchanged), CLAUDE.md freed for project scope; consumer/maintainer wording rule | accepted | -| BDR-065 | 2026-07-14 | transient planning artifacts (superpowers spec/plan): committed during run, deleted post-merge; git history = archive; codified in project CLAUDE.md | accepted | -| BDR-066 | 2026-07-15 | Model routing: reflection inline (session big model) + sonnet-pinned executors + blocking gate | accepted | -| BDR-067 | 2026-07-16 | first public release: versioning reset to v1.0.0 (override "never restart at v1.0.0") — 2026-07-16 | SHIPPED | -| BDR-068 | 2026-07-16 | /capitalize + /close auto-persist memory (finish→develop + push); scoped LRN-069 exception — 2026-07-16 | implemented on feature/close-auto-persist | -| BDR-069 | 2026-07-16 | permissions deny: keep broad `.env.*` glob, keep `.env.example` name (option A) — 2026-07-16 | implemented on chore/fix-inert-write-deny-rules | -| BDR-070 | 2026-07-17 | claude-seo: cherry-pick scripts into our tree, never install; /seo stays sole entry | accepted | -| BDR-071 | 2026-07-17 | No viable free backlink source → Off-page axis stays brand-mentions-only (FINAL, not placeholder) | accepted | -| BDR-072 | 2026-07-17 | SPA: honest refuse (On-page N/A, not zero), no headless browser (R2 over R1) | accepted | -| BDR-073 | 2026-07-17 | Scoring: LLM judges findings+severity, engine does the arithmetic (deterministic /20) | accepted | -| BDR-074 | 2026-07-17 | Remove config-protection edit-block guardrail | accepted | -| BDR-075 | 2026-07-17 | Framework-wide 3-way adversarial plan-challenge phase | accepted | -| BDR-076 | 2026-07-19 | Dispatched judgment agents pinned OPUS; session model = orchestration + inline reflection ONLY | accepted | -| BDR-077 | 2026-07-19 | Model-tiering v2: 4-tier explicit routing, mode-based splits, no-inherit dispatches | accepted | -| BDR-078 | 2026-07-20 | ctx7 coverage: central fast-libs list + once-per-session reminder hook; every code path covered | accepted | -| BDR-079 | 2026-07-20 | profile `set` symmetric on managed externals + MCPs | accepted | -| BDR-080 | 2026-07-21 | Bug routing inverted: /bugfix primary, /investigate explicit-only | accepted | -| BDR-081 | 2026-07-30 | Config recalibrated for Claude 5 family (Opus 5 dispatch tier) | accepted | -| BDR-082 | 2026-08-02 | seo/geo analyzers de-prescribed for Opus 5 (C1) | accepted | -| BDR-083 | 2026-08-24 | Contract gates: deterministic floor (GATE 0) under the fresh verifier | accepted | -| BDR-084 | 2026-08-24 | /tour multi-project: parallel runners (LRN-083 derogation, bounded), runner inherits session model | accepted | -| BDR-085 | 2026-08-25 | User permanent rules: writing-style always-on in rules/, web build+security path-scoped | accepted | -| BDR-086 | 2026-08-26 | darwin: threshold gates full loops; verified defects fixed regardless of unit score (paired-validated, batched checkpoint) | accepted | -| BDR-087 | 2026-09-03 | Stop hook = attention signal only, never control flow; one script for Notification + Stop | accepted | -| BDR-088 | 2026-09-15 | gstack Playwright bump shared via lib, re-applied after submodule update; update helper never touches the submodule tree | accepted | -| BDR-089 | 2026-09-15 | No Playwright browser-cache pruner; read-only doctor report — .links proved 0 bytes reclaimable | accepted | -| BDR-090 | 2026-09-15 | Destructive shell work → autoMode soft_deny/hard_deny; `ask` tier abandoned (inert under auto) | accepted | -| BDR-091 | 2026-09-16 | Ask, don't guess: open-choice sweep (3 classes) at plan step + mid-run CLASS channel supersede "one question upfront" | accepted | -| BDR-092 | 2026-09-16 | docker + node framed by the classifier via autoMode.allow + soft_deny; ask entries retired | accepted | -| BDR-093 | 2026-09-22 | 21st.dev: magic MCP → CLI + skill pack; staged install past the ~/.claude/skills symlink; CLI = gate's required-manual | accepted | -| BDR-094 | 2026-09-22 | impeccable: global-scope install through the repo symlinks, pin + @latest fallback, output-read failure check | accepted | -| BDR-095 | 2026-09-22 | Data-loss guardrails: static deny for transfer/destructive tools, push every commit, brief ≠ user authority | accepted | -| BDR-096 | 2026-09-24 | Branch deletion guard: lib-only delete after verified merge, main/develop undeletable at the ref layer | accepted | -| BDR-097 | 2026-09-24 | graphify from 200 tracked code files: the banner informs, the user decides | accepted | -| BDR-098 | 2026-09-24 | CLAUDE.global.md density pass 352 → 270: compression only, three name-obvious routing lines dropped | accepted | -| BDR-099 | 2026-09-24 | C2 coherence: 30 doctrine/skill tensions resolved, doctrine wins, BDR-068 kept as the written exception | accepted | -| BDR-100 | 2026-09-24 | Guardrail evasion and partial rule changes get mechanisms, not lessons: refusal ends the attempt, citers census in make test | accepted | -| BDR-101 | 2026-09-25 | `full` = default profile: no selection ⇒ full in force, `reset` applies it, install applies it | accepted | -| BDR-102 | 2026-09-27 | agent-skills: no plugin, vendor 3 skills + build floor-guard + routing census + rest-api rule | accepted | -| BDR-103 | 2026-09-27 | 6-repo review: 5 verdicts, 3 criteria (grep-verified coverage, per-session cost, doctrine conflict); stars decided nothing | accepted | -| BDR-104 | 2026-09-28 | MengTo motion pack: vendor 5 scroll skills pinned via shared lib/vendor-skills.sh + build personal skill site-motion; 17 skipped | accepted | -| BDR-105 | 2026-09-28 | skill-catalog prune: 9 gstack out via GSTACK_REMOVED, full ⊇ every profile, max = everything, brightdata + frontend-design plugin off, security-guidance Stop review off, design gate asks `21st login` and waits | accepted | -| BDR-106 | 2026-09-28 | superpowers: 7 wired skills vendored at v6.4.1 via lib/vendor-skills.sh (always_on lock class), plugin + marketplace dropped, citers by bare name, doctrine map for the 4 non-vendored refs | accepted | -| BDR-107 | 2026-09-28 | Effort tiering: session high, effort pins on 20 agents (BDR-077 second axis), entry level on 30 skills, five paired shifter skills, max at loop caps + ship-feature 4b | accepted | -| BDR-108 | 2026-09-29 | Effort round: level on every skill next to its model pin (3 repo + 25 vendored via `lib/effort-pins.txt` re-applied after the LAST vendoring step of install + resync), design stack ONE level (high), model pins stay tier aliases: quality/price trade-off = tier × effort, never version | accepted | -| BDR-109 | 2026-09-30 | Higgsfield pack: npm CLI `latest` + 8 upstream skills git-cloned into gitignored `skills-external/higgsfield-*`, OFF by default, in no profile; two toggles (`higgsfield` = allowlist of 7 media skills, `higgsfield-websites` = landing-page aid, never website create/deploy/publish); CLI presence by probe; routing on explicit ask | accepted | -| BDR-110 | 2026-10-06 | Shell portability doctrine: native userland on macOS AND Linux, no Homebrew GNU tools on PATH; `lib/tests/portability-census.test.sh` locks deterministic GNU-only idioms | accepted | -| BDR-115 | 2026-10-08 | model-router mod: pin = entry default, sub-tasks route finer; one writer per axis; full ids from the mod table; built-ins-only agents table until frontmatter pins go; state in closure | accepted | -| BDR-116 | 2026-10-11 | model-router first-use confirmation: tracked routing.json = source of phases + rows + decisions; engine dialog at first use; project exceptions in user scope keyed by normalized remote; model never writes; census tolerates a decided row | accepted | -| BDR-117 | 2026-10-12 | shared gstack helpers live in lib/gstack-removed.sh, not in a new lib | accepted | -| BDR-118 | 2026-10-12 | Rust default language for new projects / whole-project rewrites, always-on rule file | accepted | -| BDR-119 | 2026-10-16 | impeccable = Build path for all UI; GATE-BLOCK swaps frontend-design for impeccable | accepted | -| BDR-120 | 2026-10-18 | Secure-by-default guardrails: always-on rule file + /guardrails stdlib scanner, passwords in api domain | accepted | -| BDR-121 | 2026-10-18 | Guardrails fix loop reuses bugfix circuit; scanner = contract oracle, baseline re-pass | accepted | -| BDR-122 | 2026-10-19 | Guardrails split: /a11y standalone on shared scan engine, injection + exposure domains, exposure proven live by read-only probe | accepted | -| BDR-123 | 2026-10-21 | Routing policy: opus session model, Fable via best-tier rows for orchestrator reflection + merge gates, sonnet writes, doctrine ceiling on Fable main; supersedes parts of BDR-066 / BDR-115 | accepted | -| BDR-124 | 2026-10-23 | Foreign code keeps its own style (lib/code-origin.sh, `git config claude.origin`), limits strict in our code only | accepted | -| BDR-125 | 2026-10-23 | Context mod: subtract-only JIT injection + deterministic guards; supersedes BDR-031 (conditional load proven reliable) | accepted · phases 0-5 planned | -| BDR-128 | 2026-10-27 | Project path rules: one bash oracle (lib/project-rules.sh), /onboard split subtract-only, generators born split, InstructionsLoaded proof hook | accepted · 0b pending | - --- ## BDR-001 — Uniform --help helper via session-start hook (option C) @@ -695,14 +569,17 @@ rules: - **Reference**: read-phase analysis (no hook code ever written); wiring commit (capitalize STEP 5B) follows. Completes [[BDR-034]] rollout; applies [[BDR-033]] doctrine to REJECT (not all nudges — the determinism split is [[LRN-061]]). See [[LRN-061]], [[LRN-047]], [[LRN-049]], [[LRN-054]]. ## BDR-038 — deploy skill: per-project learning runbook, two-moment cold-resume +- **Date**: 2026-06-27 - **date**: 2026-06-27 - **status**: accepted - **decision**: New `/deploy` skill = per-project runbook in `.claude/deploy/`. 5 artifacts: `PROCEDURE.md` (runbook, in-place edits), `INCIDENTS.md` (`DEP-NNN` ledger, append-only), `STATE.json` (deploy oracle, committed), `PENDING.json` (cold-resume bridge, gitignored), `NEXT.sh` (instantiated checklist, gitignored, hand-run). Two-moment spine: BEFORE (delta-instantiate `NEXT.sh` + hand back) → user deploys OUT-OF-BAND → AFTER (react: MARK success or LEARN from failure). Cold cross-session resume via `PENDING.json` (disk = only memory across the gap). Learn = atomic patch+incident (one `deploy-commit.sh` call, both files). New helper `lib/deploy-commit.sh` (allowlist `.claude/deploy/`). Built via subagent-driven-development (4 tasks). - **why**: deployment memory that LEARNS (runbook patched in place per failure) beats a frozen runbook; disk-bridge so a resume survives session loss. - **alternatives**: tag-oracle (rejected — lightweight-tag date unreliable, rebase-fragile, [[LRN-063]]); separate append-only ERRORS log (rejected — git history of `PROCEDURE.md`+`INCIDENTS.md` suffices, no `resolved-by` field); `NEXT.sh`-as-bridge (rejected — ephemeral ≠ persistent → separate `PENDING.json`); reuse doc/memory-commit (rejected — neither can commit `.claude/deploy/`, [[LRN-064]]). - **reference**: `skills/deploy/SKILL.md`, `lib/deploy-commit.sh`, `templates/deploy/`; branch `feat/deploy-skill` (b210e8d..79741e3, kept un-merged); spec `docs/specs/2026-06-27-deploy-skill-design.md`, plan `docs/plans/2026-06-27-deploy-skill.md`. +- **Status (2026-10-28, upgrade)**: superseded by BDR-054 (NEXT.sh, hand-back) ## BDR-039 — Gitea branch protection = Option-1 owner-pushable, not require-PR +- **Date**: 2026-06-29 - **date**: 2026-06-29 - **status**: accepted - **decision**: Protect `main` + `develop` on every gitflow-migrated Gitea repo with **Option 1 (owner-pushable)**: `enable_push=true` + `enable_push_whitelist=true` + `push_whitelist_usernames=[owner]`. Blocks force-push, branch deletion, and pushes by non-owners — while letting the owner push their LOCAL gitflow merges directly. NOT require-PR / required-review. @@ -711,6 +588,7 @@ rules: - **reference**: `lib/gitflow-migrate.sh` `_protect()` (POST `/repos/{o}/{r}/branch_protections`, owner whitelist); applied to all 6 repos 2026-06-29 (journal). Hook backstop in `lib/gitflow.sh` (pre-commit); CLAUDE.md "Version control — gitflow (universal)". Pairs with [[LRN-069]] (the `git push` ASK gate at the tool-call layer). ## BDR-040 — doc-syncer MINOR-shape oracle: deterministic floor under LLM's MINOR call +- **Date**: 2026-06-29 - **date**: 2026-06-29 - **status**: accepted - **Problem**: doc-syncer AUTO MODE classifies drift NONE/MINOR/SIGNIFICANT by LLM judgment, no deterministic backstop. SIGNIFICANT mislabeled MINOR → silent auto-patch + auto-commit, skips the SIGNIFICANT gate (RISK-1). Follow-up [[BDR-036]] flagged. @@ -872,6 +750,7 @@ rules: - **Alternatives rejected**: `latest` (pipx house default, graphifyy-style) — fine for comfort tools, wrong for a blocking gate; `--config auto` — telemetry + non-determinism. - **Reference**: plugins.lock.json `semgrep` entry, install-plugins.sh STEP 7.5, update-all.sh step 6.2 — branch feature/semgrep-install `ccfecc9`. Conditions [[LRN-047]], [[LRN-085]]. Coverage caveat of the community rulesets: [[LRN-092]]. - **Addendum 2026-07-03** (lot 3, measured): rulesets = `p/security-audit` + `p/secrets` + **`p/owasp-top-ten`**. owasp-top-ten is REQUIRED not optional — measured on realistic Flask code, the 2-ruleset baseline missed SQL injection + path traversal ENTIRELY (0 findings); owasp's taint rules catch them. Severity map: secrets ERROR→CRITICAL, other ERROR→HIGH (block), WARNING/INFO→reported. Blocking threshold = ERROR (per-RULE, not per-vuln — same class can straddle ERROR/WARNING; blocking WARNING too floods FP). FP measured shell/md only (faunosteo, game: sole added blocking ERROR = Dockerfile `missing-user` hygiene, contained by gate-mode diff-scoping). **Re-evaluate owasp FP at the first real web/python app project** (shell/md repos don't represent where the gate runs). See [[LRN-094]], agents/security-auditor.md branch feature/security-auditor `2b297bd`. +- **Status (2026-10-28, upgrade)**: accepted ## BDR-049 — Verifier doctrine: fresh + blind + disk-contract + proof-or-fail @@ -880,6 +759,7 @@ rules: - **Rationale**: dev self-score is always confident → not a gate. Verifier fed history anchors on prior verdicts → telescopic drift. Context-only contract dies at compaction, the verbatim with it. - **Alternatives rejected**: dev self-assessment as gate; cumulative verifier context ("cheaper" but anchored); gitignored run files (lose escalation reference + session-death survival). - **Reference**: lib/contract-interview.md + agents/verifier.md + lib/tests/contract-verifier.test.sh (31 locks) — branch feature/contract-verifier `6aed5ee`. Behavioral GREEN: planted-gap → ECARTS(2) exact; conform-under-injected-history → CONFORME (blindness held). Twin of [[BDR-048]] (security gate). Conditions [[LRN-048]], [[LRN-083]]. +- **Status (2026-10-28, upgrade)**: accepted ## BDR-050 — Universal verify+secure pipeline, weighted per flow (loops in the main loop) @@ -888,6 +768,7 @@ rules: - **Rationale**: the value is the INDEPENDENCE of the gate (fresh subagent vs a rich contract), NOT delegating the dev — so dev stays inline in light flows and weighting lives on loops+questions, never on skipping a gate. hotfix reverts because a 3× loop would reintroduce the weight its identity excludes. - **Alternatives rejected**: dispatch the dev too (turns feat into ship-feature-bis); one merged "quality" gate (see [[LRN-095]] — orthogonal gates degrade if fused); hotfix loops like feat (breaks its 1-attempt identity). - **Reference**: lib/verify-secure-loop.md + wired feater/bugfixer/hotfixer + lib/tests/loops-light.test.sh (27 locks) — feature/verify-loops `0f0162d`. Behavioral GREEN (feat fixture): CONFORME→BLOCK(1) SQLi→fix→re-verify CONFORME→re-scan PASS, order invariant held. Builds on [[BDR-048]] [[BDR-049]]. Conditions [[LRN-083]] [[LRN-095]]. +- **Status (2026-10-28, upgrade)**: accepted ## BDR-051 — Contract enrich-at-gate: the contract grows only at a human micro-gate - **Date**: 2026-07-04 @@ -895,6 +776,7 @@ rules: - **Rationale**: raw request underspecifies (one-line "add validation" hides the schema-rejection requirement the design surfaces); verifier judging only the seed → every design decision unverified. Gating the growth keeps the contract honest (no silent scope creep) AND complete (design criteria are verified). Only flow where the contract is mutable mid-run — bounded to gate moments. - **Alternatives rejected**: freeze contract at creation (design criteria unverified — seed too thin); let dev enrich ([[BDR-049]] failure mode — dev justifies everything, scope constrains nothing); second contract per design (loses single-reference property). - **Reference**: ship-feature STEP 0e+3, init-project STEP 1+4, feature/verify-loops `1c69de2`. Behavioral GREEN: a `[gated 2026-07-04]` design criterion (reject unknown config keys) was read + judged NOT-MET by a fresh verifier across 3 rounds (dogfood). Builds on [[BDR-049]] [[BDR-050]]. +- **Status (2026-10-28, upgrade)**: accepted ## BDR-052 — /tour auto mode: branch-as-gate, declared state read-only @@ -903,6 +785,7 @@ rules: - **Rationale**: mid-run gates defeat the skill's point (hands-off grouped sweep, user away). Auto-checking TODO reproduces the exact lie /reconcile catches — RED-proven, baseline did it. Branch+report = same approval semantics as audit-delta's 3c gate, moved after the fact where a headless run can afford it. - **Alternatives rejected**: per-phase AskUserQuestion gates (audit-delta model — blocks headless); one consolidated pre-fix gate (still blocks); auto-edit TODO on oracle proof (inference ≠ approval); plain-branch fallback on non-gitflow repos (violates lib-only doctrine → report-only instead). - **Reference**: skills/tour/SKILL.md + CLAUDE.md routing (feature/tour-skill `73e6a1c`). TDD trail [[LRN-099]] [[LRN-100]] [[EVAL-014]]. +- **Status (2026-10-28, upgrade)**: accepted ## BDR-053 — ctx7 single surface: keep find-docs skill, kill context7.md rule @@ -911,6 +794,7 @@ rules: - **Rationale**: rule = ~490 tok/session session-start duplicate of the skill (job1 F10 + job2); skill self-suffices (876-char description carries the triggers, body has full CLI flow). Purge-in-installer beats one-shot rm: survives re-runs + manual `ctx7 setup`. - **Alternatives rejected**: kill skill keep rule (rule always-on, costs every session even non-lib work; skill lazy — wrong direction); hand-trim generated files (fight the generator, LRN-039 class); hand-edit lock hash (algo undocumented). - **Reference**: chore/ctx7-single-surface; job1 F10, job2 F8/F13. User decision 2026-07-06. +- **Status (2026-10-28, upgrade)**: accepted ## BDR-054 — supersede BDR-038: NEXT.sh file + AskUserQuestion hand-back removed from /deploy @@ -1077,12 +961,14 @@ rules: - **Alternatives rejected**: (plugin install) → both `/seo` coexist namespaced → non-deterministic dispatch, silently loses our FR-legal axis on an unpredictable fraction of runs. (install nothing) → forgoes render_page/url_safety/unlighthouse we lack. - **Verdict on parity**: their README lies (dual JSON-LD validator = 2 hyperlinks, zero `.py` calls; "zero-network"/"fully offline" false). Our system is more honest; we keep FR-legal (their whole repo: 2 hits), fix-bundle+ownership, trajectory-17/20, NAP anti-seed. - **Files**: none installed. Findings drove the whole seo-geo-integrity branch (21 commits). +- **Status (2026-10-28, upgrade)**: accepted ## BDR-071 — no viable free backlink source: Off-page axis stays brand-mentions-only — 2026-07-17 - **Decision**: I1's narrowed Off-page axis (brand mentions from STEP 6 only, backlinks+authority declared §14-unauditable) is the FINAL state, not a placeholder awaiting data. - **Why**: measured, not assumed. GSC has no links endpoint (API = Search Analytics/Sitemaps/Sites/URL-Inspection only; links report UI-only). Common Crawl hyperlinkgraph domain-edges = **17.3 GB gzipped** (+879MB vertices, +2.3GB ranks), HEAD-measured live. Scanning it per-audit is non-viable + abusive to a nonprofit. The reference impl (claude-seo commoncrawl_graph.py:169) caps download at 500 MiB = **2.9% of edges**, sorted by source ID → arbitrary slice reported as a backlink profile, "70/100 health". A random sample dressed as a measurement — the exact failure class the branch removes. - **Consequence**: B1/B2/B3 all killed. Weight (10-15%) unchanged — re-deriving for an axis that won't widen churns historical scores for nothing. - **Only free viable source**: Bing GetUrlLinks — first-party only (never a competitor), blocked on client's Bing account → raises W2's value ([[BLK-017]]), does not unblock it. +- **Status (2026-10-28, upgrade)**: accepted ## BDR-072 — SPA: honest refuse, no headless browser (R2 chosen over R1) — 2026-07-17 - **Decision**: rendercheck verdict `client-rendered` → On-page axis N/A, excluded from weighted global, NEVER scored zero. No Playwright, no Chromium. User-arbitrated. @@ -1090,12 +976,14 @@ rules: - **GEO angle (sharper)**: AI crawlers (GPTBot/PerplexityBot/ClaudeBot) are WORSE at JS than Googlebot — fetch HTML, largely don't execute. A client-rendered site is near-invisible to the engines the audit serves → §0 alert + SSR/SSG top user action, aligns CLAUDE.global "public sites never SPA". - **Alternatives rejected**: R1 Playwright (~300MB Chromium, breaks bash+curl purity) — user chose refusal. Refusing IS the finding. - **Files**: lib/seo-data/render_check.py, seo/geo STEP-5 gates (20d3082). +- **Status (2026-10-28, upgrade)**: accepted ## BDR-073 — deterministic scoring: split LLM judgement from arithmetic — 2026-07-17 - **Decision**: LLM emits WHICH findings + severity (irreducible judgement); engine computes the /20. Reuses /harden's scale (-15/-8/-3/-1, clamp, /5 into /20) → one vocabulary across the family. - **Why**: /harden had a real scale (SKILL.md:435), /seo had NONE → every axis felt → two runs over identical code diverged, while /client-handover gates on 17/20. H2 sharpened it: once drift reports real change, a self-moving score is visibly noise. Same principle as engine-side cannibalisation grouping — never hand a model 1000 rows to add. - **Makes computable (was prose)**: "N/A is not a zero" (R2 on-page, I1 off-page) → axis excluded + weights renormalised, verified all-20 with 2 N/A → global 20.0. Prevalence: affected/sampled shift severity ONE step (≥50% escalate, single de-escalate). - **Files**: lib/seo-data/score.py (4818c61). +- **Status (2026-10-28, upgrade)**: accepted ## BDR-074 — Remove config-protection edit-block guardrail [accepted] (2026-07-17) Deleted hooks/config-protection.sh + its settings.json PreToolUse registration + lib/tests/config-protection.test.sh. Hook blocked model Edit/Write on quality-gate files (settings.json, gitflow.sh, .githooks, doctor.sh, hooks, lib/tests, lint) via one-shot .claude/.config-edit-ok sentinel. Removed per user req — friction editing own config > guardrail value; user = human operator. Residual: gitflow pre-commit guard + Gitea branch protection still block direct code commits main/develop; only edit-time block gone. Alts rejected: warn-only (exit0+log), targeted relaxation. Supersedes any prior config-protection decision. @@ -1157,6 +1045,7 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Why**: leaving a verified destructive path (hotfix `git restore .` wiping tolerated user edits, file scored 85) unfixed = score-worship; rubric serves quality, not the inverse. - **Alternatives rejected**: strict threshold (ships known bugs); optimize-everything (cost, HL-4 diminishing returns). - **Reference**: run 2026-08-26, commits 6eceedb..6eac7fb, `.claude/audits/DARWIN-2026-08-26.md`. +- **Status (2026-10-28, upgrade)**: accepted ## BDR-087 — Stop hook = attention signal only, never control flow - **Date**: 2026-09-03 @@ -1531,3 +1420,9 @@ Branch feature/user-writing-web-rules, UNMERGED (human gate). - **Alternatives rejected**: block-list `paths:` parsing (spec shape inline; pre-flight `check` at S0/S1 moves the failure before any write); mod-based injection (BDR-125 says phase 0 no mod); dep-dir filter unconditional (vetoed `vendor/**`); `git add .claude/rules` dir (a pre-existing rule made visible by the negation would ride along); whole-file Write for the pointer (subtract-only). - **Residuals**: `###` granularity before faunosteo (12.6 KB path-bound content under always-on `## Project conventions`; `##`-only moves 1.5%), user decides (TODO 0b); `game` heading with `'` refused until renamed or extract by index; `extract -n` dry run deferred; T11b + AC2 hardcode 4 rules; `InstructionsLoaded` key on older CLIs unverified (check `claude --version` on work machine before pull); pre-commit `.claude/**` exemption lets a rules-only commit land on develop → phase 2. - **Refs**: spec `docs/superpowers/specs/2026-10-26-claude-md-split-design.md`, plan r3 `docs/superpowers/plans/2026-10-26-claude-md-split.md`, contract `.claude/tasks/contracts/2026-10-26-claude-md-split-0042.md`, commits abfa416..0b59687. [[BDR-125]], [[BDR-003]], [[BDR-065]], [[LRN-154]], [[LRN-232]], [[LRN-233]], [[EVAL-051]]. + +## BDR-129 — Memory registries v2: lib/memory.sh single writer, format: 2 without Index, shared parser, rc 6 chokepoint, oracle upgrade [accepted] (2026-10-28) +- **Decision**: `lib/memory.sh` = single writer + reader of `.claude/memory` registries (add/status/journal/index/check [--staged]/upgrade, `-C dir`). v2 = same file, `format: 2` frontmatter, no `## Index`. Status parser shared with `lib/reconcile.sh`: strict on v2 (heading `[tag]` or labelled status line, last wins, `memory_closed` = resolved|superseded|deprecated), legacy lexical reader kept on v1 (13 v1 repos: open sets identical). `memory-commit.sh` runs `check --staged`: staged v2 registry rewriting an entry line, new duplicate, bad heading, open fence, deletion or downgrade → unstaged, rc 6. Lock = bash noclobber file in git common dir, token unlock, serialized steal, verified backup restored on failure/signal. `upgrade`: Index-only dates/statuses → body lines, dialect headings → `## ID — title (date)`, one-way verdict repair (v1-closed→strict-open only), oracle else rc 2 file untouched; refuses duplicate IDs, non-table Index. +- **Why**: Index drifted (16 rows missing), status in 3 places, BLK-032..034 false-open (prose words), no single writer (ad hoc Edit/python on 357k files). Phase 4a of [[BDR-125]]. +- **Alternatives rejected**: `flock(1)` (absent on macOS, [[BDR-110]]); `mkdir` lock (uutils 0.10 not atomic, [[LRN-236]]); generated Index kept (drift by construction, [[LRN-055]]); upgrade via /prune-memory curation (no oracle); strict parser on v1 (regressed 4 of 13 repos: title-suffix, `date: · status:`, `**Statut** :`). +- **Refs**: contract `.claude/tasks/contracts/2026-10-27-memory-v2-write-2030.md`, plan + spec `docs/superpowers/{plans,specs}/2026-10-27-memory-v2-write*`, commits a423594..aab9e4d, upgrade 9698473. [[LRN-237]], [[EVAL-052]]. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index 156c547..a376fa6 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -1,4 +1,5 @@ --- +format: 2 type: evals_registry entry_prefix: EVAL schema: @@ -17,58 +18,6 @@ rules: # Evals registry (EVAL) -## Index - -| ID | Date | Output | Action | -|----|------|--------|--------| -| EVAL-001 | 2026-04-23 | `.claude/` restructure plan (ship-feature STEP 2) | keep | -| EVAL-002 | 2026-06-02 | `profile gstack on/off` verb implementation | keep | -| EVAL-003 | 2026-06-11 | darwin optimization run on `audit-delta` skill | keep | -| EVAL-004 | 2026-06-11 | darwin eval 26 perso skills + 4-bug fix round | keep | -| EVAL-005 | 2026-06-23 | Obsolete `claude --effort max` alias missed across Step 9 edits | correct | -| EVAL-006 | 2026-06-25 | prune-memory v1.1 TDD — 6 guards (0a3e766), validated on real data | keep | -| EVAL-007 | 2026-06-26 | Coupled-capitalize machinery — TDD 13 + e2e, surgical scope proven | keep | -| EVAL-008 | 2026-06-27 | Doc-sync coupled machinery — 28/28 real-exec, swap-sweep caught prior debt | keep | -| EVAL-009 | 2026-06-27 | deploy skill subagent-driven build: multi-stage review + pressure-test net-positive | keep | -| EVAL-010 | 2026-06-29 | prune-memory hardening: RED-7 deterministic fix + RED-8 accept + 34-row index backfill | keep | -| EVAL-011 | 2026-06-30 | /reconcile build: RED contaminated→corrected (unguided control), GREEN behavioral confirmed, dogfooded on itself | keep | -| EVAL-012 | 2026-06-30 | /release-candidate build: RED (gitflow fans out, no tag) → GREEN 5/5 (tag), throwaway-repo flow replay | keep | -| EVAL-013 | 2026-06-30 | /reconcile real-usage on live repo: known gap + 2 unanticipated (header-marker drift class) + false-positive rejected off-fixture, 0 false assertion | keep | -| EVAL-014 | 2026-07-05 | /tour GREEN run: 6/6 RED gaps closed, disk-verified; re-verify caught agent's own regression | keep (skill shipped). REFACTOR additions not re-run through 3rd full pass — re-test at first real u… | -| EVAL-015 | 2026-07-05 | /tour first REAL run (report-only, bchanot-cv): REFACTOR additions validated; premise corrected by user | keep. Skill validated on real drift; two refinement candidates noted (report-commit placement, serv… | -| EVAL-016 | 2026-07-05 | /deploy first REAL run (bchanot-cv): bootstrap→instantiate→hand-back→mark, full cycle OK | keep. Two-moment contract works in-session; disk artifacts coherent throughout. | -| EVAL-017 | 2026-07-06 | job2 audit: fresh-context verify pass caught 3 explorer false claims | harness-semantics claims from explorers ALWAYS cross-check vs docs/live evidence; file-content clai… | -| EVAL-018 | 2026-07-06 | job3 docs-drift audit + execution: 46/46 findings verified, 20/23 fixes shipped (B1 blocked, D2-D5+B6 skipped by decision), zero residual on re-sweep | keep | -| EVAL-019 | 2026-07-06 | job4 test-gap audit + execution: 11 specs + 5 fixes/seams, every mutation red-green verified, zero residual | keep | -| EVAL-020 | 2026-07-07 | job6 dep upgrade execution: 5 deps sequenced by risk, 2 real STOP gates hit and resolved live, zero regression | keep. Branch unmerged (`chore/job6-deps-upgrade`, gitflow finish = separate human signal per CLAUDE… | -| EVAL-021 | 2026-07-08 | adversarial review of the 9-job series (release/1.0.0..develop) + remediation | keep. Remediation branch unmerged (human gate). Fil-rouge guard now prevents the partial-fix class… | -| EVAL-022 | 2026-07-08 | job9 model pins (BDR-060) were smoke-tested but never recorded as an EVAL (M5 trace) | keep — record backfilled here, no re-smoke required. | -| EVAL-023 | 2026-07-16 | post-merge ronde on the model-routing refactor (BDR-066) — clean, 5 edge gaps found + fixed | keep — all 5 fixed (bugfix/model-routing-edge-fixes, merged 5f159f3); census 47→57 now locks each. | -| EVAL-024 | 2026-07-16 | deny-list design pass (BDR-069) — core fix sound, 1 unauthorized weakening caught by classifier not by me | keep — fix landed (07ca738), weakening reverted. Lesson: vague delegation ("je te laisse en juger")… | -| EVAL-025 | 2026-07-17 | opening seo/geo inventory (subagents): 7/7 verifiable claims false or overstated; real contact corrected all, 6 plan corrections + 4 features killed at measurement | keep | -| EVAL-026 | 2026-07-17 | 3-way plan challenge caught 4 BLOCKERs dogfooding own plan (2026-07-17) | — | -| EVAL-027 | 2026-08-24 | contract-gates behavioral RED: 16/16 fresh unprimed runs followed new doctrine (GATE 0 order, vacuous oracle, ABANDONED routing, scope temptation resisted) | keep | -| EVAL-028 | 2026-08-26 | darwin v2.1 paired run 54 units: 60 paired verdicts 0 revert/tie; skeptics found 3 real residuals — engaged, not rubber-stamp | keep | -| EVAL-029 | 2026-09-15 | 4-agent plan challenge: 6 BLOCKER; 3 of 3 confirmation-pass BLOCKERs came from the fixes themselves; caught a false 654 MB orphan claim | keep | -| EVAL-030 | 2026-09-24 | 2026-09-24 self-audit: two regressions and one guardrail bypass came from my own process, not from the tools | BDR-100 mechanisms shipped; re-run census at next doctrine wave | -| EVAL-031 | 2026-09-25 | /feat run for BDR-101: challenge round earned its cost, two blockers sat in my own premises | keep challenge round on state-detection plans; check live state before planning; pin grep in oracles | -| EVAL-032 | 2026-09-27 | 4 parallel feater executors, one tree, gate loop: verifier caught a vacuous test, security caught a partial-write; my oracles wrong twice | keep same-tree parallel dispatch with disjoint FILE SCOPE + orchestrator-owned shared files; blind verifier stays; measure oracles on precedents | -| EVAL-033 | 2026-09-28 | case 7: 2 analyzers + 2 executors + 3 re-dispatches; verifiers caught shape, convention and my wrong count; security caught an env override | brief names the scratchpad path explicitly (3 /tmp leftovers); keep blind verifiers; count claims get an artifact | -| EVAL-034 | 2026-09-28 | catalog prune + 21st gate: two challenge rounds each found what r3 missed (nested SKILL.md, fixture cp lists, in-session export); my ledgers failed twice (heredoc CHECKs); 5 executors DONE first pass; verifier gap = tool false positive | keep the confirmation pass on any plan that changed materially; one-line CHECKs; grep fixture cp lists before a `source` | -| EVAL-035 | 2026-09-28 | thinking-share measurement, 6 days of transcripts (10,955 requests): thinking = 8 % of weighted spend, 97 % of it in the main loop; sonnet subagents at xhigh think 26 tok/request; cache reads = 53 % | pins = explicitness not savings; main-loop effort + context size are the levers; A/B after rollout | -| EVAL-036 | 2026-09-28 | A/B `/reconcile` headless, session high vs skill entry low: requests 18→15, output 12374→9038 (−27 %), thinking 3135→2248 (−28 %), time 96.5→78.4 s (−19 %), n=1 | keep low on bookkeeping skills; repeat on a reflection skill before touching the medium/high split | -| EVAL-037 | 2026-09-28 | correction of EVAL-035/036 counts: transcript records are per content block; deduped by message.id → main-loop thinking share 99.9%, thinking share of weighted cost 5.6%, sonnet think/msg 26→0.2, A/B requests 9→8 | conclusions hold (sharper: main-loop thinking 96.6%→99.9%, weighted-cost thinking corrected 8.4%→5.6%); effort-audit.py dedupes from a3b479e+ | -| EVAL-038 | 2026-09-29 | correction of EVAL-037: 94 % of sub-agent usage records carry no `output_tokens_details` (Fable subs at xhigh read 0 thinking, impossible with always-on thinking) → sub-agent thinking UNMEASURED, not ≈0; main loop 100 % counted; weighted-cost split (61/39) still holds | `effort-audit.py` prints coverage + CAVEAT; cite the cost split only; agent effort pins stay unmeasured; a tier move on a price argument = judgment, not figure | -| EVAL-039 | 2026-09-30 | ship-feature run higgsfield-pack: plan dry-run in scratch → 0 executor failure on 7 tasks; challenge found 7 MAJOR I missed; floor-guard caught 2 shellcheck suppressions of mine; final review found README/code gap | keep | -| EVAL-040 | 2026-10-08 | model-router w1a plan: 3 challengers + 1 confirmation found 2 BLOCKER + 14 MAJOR on a plan judged closed; executor then passed every gate first time | keep the round, never dispatch a mod plan without it | -| EVAL-041 | 2026-10-09 | model-router W1-C plan: 3 lenses FATAL (4 BLOCKER + 20 MAJOR) then 2 confirmations each FATAL with a NEW BLOCKER in my own revision; executor DONE first pass, 3 short text/hardening rounds | one confirmation is not enough when a revision removes a whole mechanism; the plan carried the risk, the code almost none | -| EVAL-042 | 2026-10-10 | model-router W2 plan r1 → r4: 3 lenses (1 BLOCKER), 2 confirmations (1 BLOCKER then 0); W2-A verifier 3× ECARTS on coverage clauses only, W2-B ECARTS(7) → CONFORME; gate A→B read from engine records | second confirmation paid again (BLOCKER on my own r2 slot); compound coverage criterion = endless ECARTS; engine jsonl replaces the live log | -| EVAL-043 | 2026-10-11 | model-router W3-A: 3 lenses + 1 confirmation (census BLOCKER, project-tree layer dropped), feater DONE + 4 rounds, verifier 3× then re-verify after a REAL security BLOCK (credential fragment in the tracked key) | challenge + security gates both earned their cost; coverage-shaped criteria still cost 3 verifier rounds; live mod side effects misread as a test leak | -| EVAL-044 | 2026-10-11 | model-router W3-B (dialog with context): 3 lenses converged on 2 BLOCKERs of my r1 (inline rows, phase edits) + 1 confirmation; feater DONE + 2 coverage rounds; verifier 3× to CONFORME; security PASS; user's first real decision through the new dialog | the lenses pay most when the plan adds a data shape; coverage criteria still cost rounds; live dialogs during the gates must be announced and their data reconciled before commit | -| EVAL-045 | 2026-10-11 | model-router W4-B (prompt classifier): 3 lenses (BLOCKER: unbounded classify await) + 1 confirmation; feater DONE + 1 round; verifier ECARTS(2) → CONFORME; security PASS 0 findings; LRN-210 applied (one coverage clause per criterion) | first wave since W2 with no verifier cap: per-clause criteria + abort paths declared unverifiable up front cut the rounds to one | -| EVAL-048 | 2026-10-23 | model-router feat C keyword cap: 3 lenses FATAL(4)/FATAL(5)/CONCERNS on r1 (3 BLOCKER: run-slot shadow, probe-test hang, reload fail-open), mechanism rewritten, confirmation SOLID; verifier CONFORME 1st pass; 1st verifier died 429 on Fable | -| EVAL-051 | 2026-10-27 | CLAUDE.md split: plan r1→r3 FATAL(5), 12 SDD tasks clean, RED/GREEN + dry run, sonnet final 3 Important, opus 2 Important 8 Minor; extract rc 0 on failed rewrite survived 5 reviews | failure-path test per rewriting function; review a cross-repo tool on real inputs | - --- ## EVAL-001 — `.claude/` restructure plan @@ -117,6 +66,7 @@ rules: - **Method / why missed**: I treated the pre-existing `CLAUDE_LINES` as established and only touched the lines I was adding/removing. Spotting the redundancy needs cross-referencing TWO config layers (shell alias vs settings.json) — a semantic check I never ran. Masked further: the user's `.bashrc` is hand-managed and the alias line wasn't even present, so it looked inert. - **Anomaly**: not just dead config — a CLI flag (`--effort max`) silently OVERRIDES the settings.json value (`xhigh`). Real correctness bug. - **Action**: when editing installer shell-config, audit EACH existing line against the current settings.json / CLAUDE.md source of truth, not only the lines being changed. Removed the alias + added cleanup. General rule: reconcile config to ONE source of truth across env/alias/settings layers. +- **Status (2026-10-28)**: correct (Index Action, upgrade) --- @@ -147,6 +97,7 @@ rules: - **Action**: keep. BLK-010 (scaffold/unborn-HEAD) + BLK-011 (GSD ROADMAP post-FINISH) + MINOR-gate strengthening = separate chantiers. ## EVAL-009 — deploy skill subagent-driven build: multi-stage review + pressure-test net-positive +- **Date**: 2026-06-27 - **output**: `/deploy` skill (helper + SKILL.md + templates + bootstrap), built via subagent-driven-development (4 tasks; fresh implementer + per-task spec+quality review each). - **method**: per-task review (sonnet; opus on the keystone) + writing-skills pressure-test (fresh agent on a `PENDING.json`+moved-HEAD fixture) + final whole-branch review (opus). - **anomalies**: (1) the PLAN's code carried 3 latent bugs — missing `git add` for new files, SC2086 unquoted `$viol`, comment-before-shebang SC1128 — all caught by the implementer's TDD+shellcheck gate → plan-code is a DRAFT, the test gate is load-bearing. (2) the final whole-branch review caught 2 Important seam-bugs INVISIBLE to per-task reviews: target-repo `.claude/`-ignored silent no-op ([[LRN-066]]) + `NEXT.sh`-absence non-regeneration → holistic review earns its keep. (3) pressure-test confirmed the cold-resume discipline holds under temptation (the agent excluded the moved-HEAD `0034`). (4) a reviewer subagent bugged out once (user killed it) → re-dispatched clean (transient, not a finding). @@ -296,6 +247,7 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse - **Method**: paired same-judge 3-majority per round (v2.1); judges live-exec where artifact executable (5 units: skills-perso, profile, plugin-pair, status-reporter, gitflow). Absolute scores triage-only. Totals main-thread (LRN-018 applied). - **Anomalies**: (1) 0 reverts/ties in 60 verdicts — homogeneous-better checked: skeptic lens found real residuals 3x (doctor.sh cost source, hotfix RULES leftover restore, FILE(S) new-marker) → judges engaged. (2) census lock RED on line-rewrap, make test caught → LRN-144. (3) head-pipe masked grep exit 2x → LRN-143. - **Action**: v2.1 paired = standard. Post-run absolute rescore skipped by design (would be judge-noise theater). +- **Status (2026-10-28)**: keep (Index Action, upgrade) --- @@ -385,6 +337,7 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse - **Method**: 3 blind opus challengers (simplicity CONCERNS(3), robustness CONCERNS(6), correctness FATAL(8)) + 1 confirmation (CONCERNS(4)); every BLOCKER/MAJOR closed by a named plan change (r2, r3); then feater, GATE 0, verifier, security. - **Anomaly**: r1 carried 2 BLOCKER (explicit Agent `model` overridden at every step; Skill bridge answer shape refused by the output schema → doublon kept) + 10 MAJOR, all invisible to me: spike levers carried over as design (`agentsNext`, per-step model rewrite), a table copying 21 pins = third source of truth, writes on main from sub-agent loops. Confirmation found 4 more MAJOR (explicit params vs in-agent writes, `e.wait`, vacuous test assertions, haiku effort). Executor then DONE first pass, verifier CONFORME 6/6, security PASS: the plan was the whole risk. - **Action**: a mod plan always goes through the full round + confirmation; test assertions must read the one line that carries the value; spike code is a FACT source, never a design source ([[BDR-115]], [[LRN-205]], [[LRN-206]]). +- **Status (2026-10-28)**: keep the round, never dispatch a mod plan without it (Index Action, upgrade) ## EVAL-041 — model-router W1-C: the plan was the whole risk, two confirmations were needed - **Date**: 2026-10-09 @@ -434,6 +387,7 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse - **Action**: keep the single confirmation pass mandatory after any r2 that changes the mechanism (not just wording); when a plan says "fail closed", name the picker and its fallback value in the plan; TODO residuals (parentModel inheritance, usage lag, TTL const) carried, not dropped. Links [[BDR-116]], [[LRN-216]], [[EVAL-045]]. ## EVAL-048 — model-router feat C: lenses killed r1 mechanism; second mechanism passed every gate first time +- **Date**: 2026-10-23 - **Method**: /feat. r1 = cap in `wantedModel` mirroring classifier. 3 blind lenses: correctness FATAL(4), robustness FATAL(5), simplicity CONCERNS(1). BLOCKERs: capped prompt slot shadowed held run (both correctness + robustness), probe-test one-line swap hangs (route tool answer probes), cap fail-open on `sessionModel` '' (/reload-plugins). r2 = effort-only routes at 3 writers + user pick (derived orchestrate too). 1 confirmation: SOLID, 5 MINOR applied (r2.1). feater DONE no deviation, 509 tests; GATE 0 12/12 MET; verifier CONFORME 14/14 1st pass; auditor PASS 0 findings; doc-sync SIGNIFICANT 5 patches. - **Anomalies**: author r1 claim "identical to classifier" false: classifier never runs under a held route, prompt rules do. First verifier dispatched on Fable died 429 (credits out): LRN-224 residual (spawn path unprobed) seen live; retry landed on opus floor. Push of remote branch delete + first /feat Skill call blocked by auto-mode classifier. @@ -453,3 +407,9 @@ Dogfood: 3 blind lenses attacked the v1 plan for the plan-challenge feature itse - **Method**: 0d analyzer; brainstorm 4 user answers; plan r1 → r3 (correctness FATAL(5): SIGPIPE, rc 127, dry run on develop blocked, unchecked commit rc, 80 cols). SDD 12 tasks sonnet/medium, 12 task reviews clean (1 controller resolve avg, mostly attribution lines + oracle facts). RED (current skill stops at plugin-probe) → GREEN (S5 table, nothing written) → dry run on a branched scratch (2 rules in HEAD). Sonnet final review 3 Important → 89334f2. GATE 0 MET 14/20 runnable; verifier ECARTS(3) → ECARTS(1 = user MCP step); security PASS, 1 LOW. Opus/xhigh craft: 0 Critical, 2 Important, 8 Minor, ran the lib on the 6 real 0b targets (56 sections conserved) → 0b59687, re-review 0 open. `make test` all GREEN, suite PASS=93. - **Anomalies**: `extract` rc 0 on a failed rewrite passed 3 challengers + 12 task reviews + 1 final review: nobody tested an I/O failure (only logic refusals). `##`-only granularity misses faunosteo's payload (12.6 KB under `###`): found only because the reviewer ran the tool on the real targets. Headless proof 0 lines (model skipped Read). T10h-j named a guard the test could not observe. Brief tally arithmetic wrong (96 vs 93). Final review found 3 Important the 12 task reviews missed (dep-dir veto of `vendor/**`, misleading error, gitignore newline glue): per-task scope hides cross-task consequences. - **Action**: Review Focus lists a failure-path test per function that rewrites a file; a tool meant for other repos gets a reviewer run on their real inputs before merge; a load proof prompt names the tool call ([[LRN-232]]); test names state the observable. Links [[BDR-128]], [[LRN-233]]. + +## EVAL-052 — Memory v2: 12 review layers, each caught what green gates missed [keep] (2026-10-28) +- **Output**: phase 4a memory v2 (lib/memory.sh + 7 citer tasks + dialect migration), 2026-10-27/28. +- **Method**: 2 plan-challenge rounds (3 lenses each, reference lib run before the plan), 8 task reviews, 4 fix rounds on Task 8, verifier ×2, security gate, controller proof on 14 repo copies, opus xhigh final review + scoped re-review. +- **Anomalies**: each layer caught what earlier green layers missed. Challenge: two classifiers, BLK-019/020 false-open, uutils mkdir lock. Task reviews: G4 guard dodged by string split (rejected), `###` verdict flip ×4 shapes. Verifier: 3 EVAL Index actions lost. Controller proof: template path after `-C` (relative call only). Opus final, after all gates green: lock spin on unwritable `.git` (no rc), bare-prefix `status BLK` writing BLK-001, bullet-list Index facts dropped (trucks_at_work), 59+106 duplicate Date lines (`**Date** :` spacing). One implementer tried `--no-verify` in a temp repo (denied). +- **Action**: keep the full stack for libs that rewrite user data; add a real-data copy proof with the user's own invocation before the final review. [[BDR-129]], [[LRN-237]]. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index ebd2e25..f134d5e 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -665,3 +665,6 @@ rules: - Phase 0b run (10 repos, faunosteo excluded: on the user's feature branch): 3 splits on chore/claude-md-split, merge on user go — zenquality 4 rules (Memory files 19.4k → 14.5k, project row 10k → 5k), game 2 rules (16k → 14.9k), angelscar356 1 rule (16.2k → 15.4k); 7 keep-everything (overview/stack/commands/structure/conventions only, S4 rule). `gitflow start` refreshed zenquality's own .githooks → S0 STOP on a dirty tree, committed as chore ed10340, re-dispatched. Three onboarder runs in parallel, one repo each, all clean first pass. - faunosteo split on the user's feature branch (user choice): 11 rules (10 ### under Project conventions + Docker), Memory files 31.9k → 27.2k, project row 22.3k → 17.7k, 7a75974. Phase 0b done: 4 repos split, 7 keep everything. - /feat extract-hardening (feature/extract-hardening 14a93e3 + docs 9160ce2): `_rules_out_path_ok` (absolute, `..`, exists or dangling link → rc 2, reason on stderr), mkdir + rule-write rc checked before the source rewrite, S0.3 prose in lib case order, 116 → 139 checks. Plan r1 `if ! { … } > "$out"` blind to a failed redirect (2 BLOCKER, bash 5.3.9 probe) → `|| { …; return 2; }`; r2 confirmation CONCERNS(1) (GNU mkdir stderr also says "cannot create"). Verifier CONFORME 8/8, security PASS. LRN-235. Three follow-ups in TODO (emit rc, rewrite keeps $tmp, lexical `..`). Merge on user go. + +## 2026-10-28 +- Phase 4a memory v2 shipped on feature/memory-v2-write: lib/memory.sh single writer, registries v2 (9698473), shared parser fixes BLK-032..034, upgrade migrates 12/14 repos on copies (game, trucks_at_work refused). 2 challenge rounds + 8 task reviews + 4 Task 8 fix rounds + verifier x2 + opus final (lock spin, bare-prefix status, bullet Index). BDR-129, LRN-236, LRN-237, EVAL-052. Merge on user go. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index b51844b..acc804e 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -1,4 +1,5 @@ --- +format: 2 type: learnings_registry entry_prefix: LRN schema: @@ -16,242 +17,6 @@ rules: # Learnings registry (LRN) -## Index - -| ID | Date | Pattern | Applies to | -|----|------|---------|------------| -| LRN-001 | 2026-04-22 | `rtk` shape-compression breaks pipes | any pipeline chaining `rtk curl/cat/read` into `jq`, `python -c`, `awk` | -| LRN-002 | 2026-04-23 | Moving report-file paths requires grepping bash READS, not just WRITES | any refactor that moves a generated file used by a dispatcher | -| LRN-003 | 2026-04-27 | Claude Code `disable*` settings use sentinel string `"disable"`, not boolean | any change to `permissions.defaultMode` or related blocker keys | -| LRN-004 | 2026-04-27 | `framer-motion` rebranded `motion` Nov 2024 — different packages per framework | any new project recommending animation lib; auditing legacy imports | -| LRN-005 | 2026-05-03 | `claude plugin install` does NOT enable — separate `claude plugin enable` required | every plugin installer targeting ALWAYS-ON status | -| LRN-006 | 2026-05-03 | `caveman-shrink` (and any MCP middleware proxy) non-functional without upstream wrapper | any MCP middleware/proxy package — never `claude mcp add` it bare | -| LRN-007 | 2026-05-06 | `toggle-external.sh enable` missed source-only state (3rd lifecycle case) | toggle scripts for tools with separate install + symlink steps | -| LRN-008 | 2026-05-06 | Biggest skill-quality wins from edge-case tables, not workflow rewrites | any skill <85 — first check for FAILURE PATHS / EDGE CASES / ERROR HANDLING section | -| LRN-009 | 2026-05-06 | Dry-run scoring noise wrongly triggers reverts on already-strong skills | darwin-skill ratchet on skills >91 — relax or use real subagent eval | -| LRN-010 | 2026-05-06 | `~/.claude/skills,agents` symlink to Documents/claude — git from `~/.claude` fails | any optimization or batch edit on personal skills/agents | -| LRN-011 | 2026-05-07 | Single subagent emits N independently-gated scores → labeled extraction + axis-aware loop + per-axis escalation | any audit pipeline shipping multiple gated metrics from one subagent | -| LRN-012 | 2026-05-07 | Bash heredoc + stdin pipe collision = silent empty output | any shell pipeline piping data into `python3 - <<'PY' ... PY` (or any heredoc'd interpreter) | -| LRN-013 | 2026-05-07 | marked CLI 16.x ignore stdin, dump own cli.js source | any shell MD→HTML via npx marked — use `-i FILE` not stdin | -| LRN-014 | 2026-05-11 | Pandoc base gfm strips header id attrs — need `gfm+gfm_auto_identifiers` | any MD→HTML/PDF with cross-references (`[§4](#nap)`) via pandoc | -| LRN-015 | 2026-05-11 | BrightLocal Free Tools retired 2026 — Moz Local Citation Checker is free replacement | client SEO/NAP docs — re-validate tool URLs + free-tier status annually | -| LRN-016 | 2026-05-11 | Pandoc GFM checkbox markup breaks adjacent-sibling CSS — target `li > input` directly | styling task-list checkboxes in pandoc-rendered HTML/PDF | -| LRN-017 | 2026-05-12 | Thin-dispatcher SKILL.md round-1 win = fallback + frontmatter triggers (+15 to +30) | any `/darwin-skill` round-1 on a dispatcher SKILL.md | -| LRN-018 | 2026-05-12 | Darwin eval subagents drift on total math — recompute in main thread | any subagent-driven SKILL.md rescore | -| LRN-019 | 2026-05-15 | Deployable-project doc split: README dev-quickstart + DEPLOY 14-section prod-VPS topology | any onboard/doc-syncer/scaffold producing docs for a deployable project | -| LRN-020 | 2026-05-18 | profile-sentinel-collision: literal labels in cmd output must not match profile filenames | a CLI reporting a real named-identifier OR a "nothing applied" state — keep sentinels outside the namespace (string-eq consumers break) | -| LRN-021 | 2026-05-20 | Refactor commands→skills must sweep `~/.claude/commands/` for orphan wrappers | any refactor moving `agents/foo.md` → `skills/foo/SKILL.md`; onboard/init-project audits | -| LRN-022 | 2026-05-21 | audit `lib/profiles/*.profile` against the gstack skill list after every submodule bump | any gstack submodule bump / external-skill-source move; a "missing:" warning = upstream rename/deletion (link.sh can't fix) | -| LRN-023 | 2026-05-21 | scripts invoked via symlink must resolve `$REPO` with `cd -P` (physical), not logical `cd` | any script invoked via a symlink that derives its repo root from `$BASH_SOURCE` (cd -P/realpath; Python .resolve()) | -| LRN-024 | 2026-06-02 | New sibling command sharing logic → extract helper + refactor existing caller, never copy-paste; assert pre/post state equality | adding a subcommand/branch reusing logic inline in a peer command | -| LRN-025 | 2026-06-02 | `.gitignore` gstack allowlist must cover ALL toggleable skills (incl. parked) — else enabling one = untracked git noise | any toggle that moves local-symlink skills into a tracked dir; post-submodule-bump reconcile | -| LRN-026 | 2026-06-09 | `disable-model-invocation: false` = ENABLED not blocking; only `true` blocks (model + orchestrator); binary, no per-caller | Claude Code skill frontmatter; deciding self-route/chain vs human-only entry point | -| LRN-027 | 2026-06-11 | Agents improvise audit boundaries from file dates when no machine state — periodic skills need machine-readable state file, never inference | any recurring/periodic skill needing "since last run" semantics | -| LRN-028 | 2026-06-11 | "no-skill" subagent baselines invalid when the skill is installed globally | any A/B skill eval / TDD RED baseline / darwin with-vs-without — control must REMOVE the capability, not omit mention | -| LRN-029 | 2026-06-11 | an edit adding an exception to a blanket rule will contradict it — counterbalanced blind judges catch it | skill/doc/spec edits adding a branch/exception; scoring any self-modified artifact (counterbalanced blind judges) | -| LRN-030 | 2026-06-18 | Opus 4.8 under-delegates subagents/memory/custom-tools by default — counter via explicit CLAUDE.md fan-out rule | any Opus 4.8 session; tuning delegation; inline-vs-subagent decision | -| LRN-031 | 2026-06-19 | Skill value = gate + anti-noise + determinism, not re-coding what a capable agent does free | building/reviewing any skill; writing-skills TDD fixture design | -| LRN-032 | 2026-06-19 | a rule has a domain; applying it outside = category error — check artifact type first | invoking a limit/convention/style rule — confirm it governs THIS artifact class | -| LRN-033 | 2026-06-19 | multibyte separator breaks `printf %-Ns` byte-width padding — pad via `${#}` char-count | aligning any column with non-ASCII (·, —, box-drawing, accents) | -| LRN-034 | 2026-06-21 | narrated state ≠ ground truth; the missed alarm was internal contradiction — verify vs git | anyone asserts "X is done" — verify (git/file/grep) before building on it | -| LRN-035 | 2026-06-21 | honest dedup: name-mention ≠ definition-instance; a dosage rule can make "dedup" a no-op | any "X repeated N times → factor it" — audit what each occurrence IS | -| LRN-036 | 2026-06-21 | `command -v ` in a shelled-out script depends on PATH carrying the cli's bin, not the alias | any script shelling out a CLI from a hook/subshell | -| LRN-037 | 2026-06-21 | verify the load-bearing scenario on the REAL subject in REAL context, not a stub/logic argument | any "fixed/works" claim on a critical path — produce the real run output | -| LRN-038 | 2026-06-23 | Playwright host-platform override for distros newer than its hardcoded support list | any pinned tool with an OS allowlist breaking on a fresh OS upgrade | -| LRN-039 | 2026-06-23 | installers drift hand-curated config → snapshot+trap-restore guard; anchor gitignore for pollution | audit a fresh install with `git status` right after `make install` | -| LRN-040 | 2026-06-23 | OS newer than a pinned tool = TWO layers (version build + security policy) | "tool X broke after an OS upgrade" — check both build-support and OS hardening | -| LRN-041 | 2026-06-23 | a check reading a symlink an earlier install step makes → false negative if that step's precondition unmet | any "X not found in FILE" where FILE is a symlink/derived path | -| LRN-042 | 2026-06-23 | `npx skills add` / gstack `./setup` resolve install target RELATIVE TO CWD — repo CWD = wrong dir | before any `npx add` / ` init` that materializes a dotfile dir, set CWD | -| LRN-043 | 2026-06-25 | CLAUDE.md skill-routing: cut name-obvious lines, keep only non-derivable signal + dense catch-all | compressing any routing/dispatch table whose entries the model sees elsewhere | -| LRN-044 | 2026-06-25 | Edit/Write refuse to write THROUGH a symlink — pass the resolved real path | before editing any `~/.claude/...` config file — resolve it first | -| LRN-045 | 2026-06-25 | renaming a command: audit exact-name leak-guard / forbidden-token regexes | when renaming, grep the BARE old token inside regex/test/gate files | -| LRN-046 | 2026-06-25 | Destructive skill: deterministic oracle (byte-identical / count census) > semantic judge | any destructive/irreversible skill; behavioral-oracle TDD | -| LRN-047 | 2026-06-25 | A noisy safety guard (13/13 FP) = a guard you learn to ignore = risk → refine, don't tolerate | any guard/alert/lint that can false-positive | -| LRN-048 | 2026-06-25 | A "0/OK/pass" must prove it LOOKED (counted both sides), else verify hard-wired to pass | any verify/test/lint reporting success | -| LRN-049 | 2026-06-25 | non-destructive repeated nudge: stateless-minimal surface > state marker (conditional on stakes) | any repeated advisory in a stateless surface — bound noise before reaching for a marker | -| LRN-050 | 2026-06-25 | on a symlinked/live file, show-before-write is the ONLY control gate | before editing any file — check if it is live, treat pre-write diff as an approval gate | -| LRN-051 | 2026-06-26 | `git commit -- pathspec` strict on no-match → filter scoped commits to changed paths | any scoped-commit automation | -| LRN-052 | 2026-06-26 | Hash-anchoring: 2 cases it does NOT apply (pre-code founding, squash-merge) | capitalizing founding/arch decisions; squash repos | -| LRN-053 | 2026-06-26 | Read-before teeth = verifiable disposition in the artifact, not the act of reading | any read-before / check-before wiring | -| LRN-054 | 2026-06-26 | No deterministic oracle for "already in context" → never add a presence-skip branch | skip-if-seen optimizations over conversation state | -| LRN-055 | 2026-06-26 | Body `## ID —` headings = drift-immune index; the `## Index` table is not | choosing a substrate to index/select over | -| LRN-056 | 2026-06-26 | `grep PAT dir/*.md` on absent dir ERRORS (exit 2), not no-op → guard `[ -d ]` | any glob-fed scan that must no-op on nothing | -| LRN-057 | 2026-06-26 | Match consumption mechanism to consumer (mechanical / external-cognitive / inline) | wiring any produce→consume invariant | -| LRN-058 | 2026-06-27 | Same bug-class ≠ same fix — verify the twin shares the fix's PRECONDITION before replicating | porting a fix to a "same bug" twin | -| LRN-059 | 2026-06-27 | Step-number SWAP flips meanings (sweep refs) ≠ letter-suffix insertion (shifts nothing) | any pipeline renumber | -| LRN-060 | 2026-06-27 | Fail-closed guard proven by what it REFUSES (loudly); pass dynamic lists as argv not separator-string | automated scoped-commit / destructive guards | -| LRN-061 | 2026-06-27 | Runtime net for an unwired skill → check the wiring first (deterministic gap = fix structurally; non-det aléa = net OK, cf BDR-033) | "build a hook/watcher to catch when X isn't done" | -| LRN-062 | 2026-06-27 | deploy first-run detection = file-existence, never `git describe` | any "first run vs incremental" tool — detect by explicit on-disk marker | -| LRN-063 | 2026-06-27 | delta-since-marker = `git diff --name-only X HEAD` (two endpoints), never rev-list/three-dot | any delta-since-checkpoint over git — explicit two endpoints for tree diff | -| LRN-064 | 2026-06-27 | surgical-commit helper family partitions `.claude/`; new subtree needs own allowlist sibling | adding a committable `.claude/X` subtree | -| LRN-065 | 2026-06-27 | cross-session cold-resume skill = disk-bridge read-first (audit-delta convention) | any "do work → user acts out-of-band → resume later" skill | -| LRN-066 | 2026-06-27 | surgical-commit must fail LOUD on git-ignored target paths (else silent no-op) | any helper relying on `git status --porcelain` to detect changes | -| LRN-067 | 2026-06-28 | pipeline that LOOKS 2-level can terminate at SAME level; human-mediated step (interactive menu) masks the double-action until automated | replacing an interactive/human step with a deterministic one over a delegated sub-skill | -| LRN-068 | 2026-06-29 | enforcement-bootstrap must be transactional: activate the guard LAST + gate it on the bootstrap commit succeeding; precheck identity | any init that installs a hook/protection AND commits | -| LRN-069 | 2026-06-29 | token-authed remote writes under CC perms: inline-env (never `export`), token in header not argv, keep `git push` on ASK as the gate | scripting git/curl writes to a private remote from tool calls | -| LRN-070 | 2026-06-29 | clean-tree-gated migration blocked by a dirty submodule → diagnose pointer-vs-content; for a local edit use `submodule..ignore=dirty`, never blind reset | migrating/releasing a superproject whose submodule carries intentional local edits | -| LRN-071 | 2026-06-29 | fail-loud must cover the helper's OWN commit, not just its inputs — 3rd occurrence of the swallowed-commit pattern (a failed op masked by a later returning-0 statement) | any helper whose return value gates a downstream "success" — audit every fallible internal op propagates, esp. the commit | -| LRN-072 | 2026-06-29 | a stranded-artifact bug can be fixed by NOT creating the artifact (negative diff), not by plumbing its commit — if the producing step is speculative/unused, delete it | a stranded/duplicated/uncommitted-artifact bug — before building machinery, ask if the PRODUCING step is wanted; speculative-at-creation → remove, deliberate-on-demand → keep | -| LRN-073 | 2026-06-29 | a skill's worked-example must use FICTIONAL ids, never live registry ids (they prime real-data behavior) | any skill/agent with a worked example over the SAME data it operates on — use reserved/fictional ids; test deterministically that no live id appears | -| LRN-074 | 2026-06-29 | system `grep`/`awk` may be ugrep/mawk: don't assume flag-parsing, use `/usr/bin/grep`, watch the RED go red (4th command-assumption miss this session) | any shell test/guard riding on grep/awk/sed semantics — pin `/usr/bin/`, run the assertion, confirm it reds on the defect before trusting green | -| LRN-075 | 2026-06-30 | skill-vs-no-skill RED must test the UNGUIDED control: a "use git + justify" baseline makes a capable agent succeed (contaminated RED); real failure shows only on the tempting prompt | building any skill whose value is determinism/gate over a capable agent — strip guidance AND tempt the failure; control succeeds → don't author (or rescope) | -| LRN-076 | 2026-06-30 | append-only registry status mutates in place (UPDATE/FINAL blocks): CURRENT status = LAST status line, not Index, not first; range scan inclusive of next header bleeds a sibling's status word | parsing any in-place-mutated status; take last line, bound entry exclusive of next header | -| LRN-077 | 2026-06-30 | test fixtures must carry NEUTRAL names — a name that telegraphs the answer lets the subject pass by reading the name, not doing the work | designing any test fixture/path; same symptom as [[LRN-074]] (passes for WRONG reason), distinct cause (leaky fixture vs assumed command) | -| LRN-078 | 2026-06-30 | semver number DERIVES from the change nature, not "justify a target"; solo-repo "breaking" = requires a migration of own usage; a removal nothing invokes = Removed not breaking | choosing a release version; classifying MAJOR/MINOR/PATCH; deciding if a removal is breaking | -| LRN-079 | 2026-06-30 | orchestrator-skill TDD = replay the prescribed flow on a throwaway repo (gitflow-test style): RED runs the flow minus the new step → the outcome assertion reds on the gap | testing a skill that orchestrates an existing mechanic + one new step | -| LRN-080 | 2026-06-30 | before adding an instruction "to make the model do X", measure if it ALREADY does X — universal conventions (--help…) it often does; the behavioral RED can KILL the chantier (phantom value) | proposing any global instruction to elicit a behavior; CLAUDE.md additions | -| LRN-081 | 2026-06-30 | Claude commit trailers (Co-Authored-By + Claude-Session) only on Claude-COMPOSED content; a commit merely STAGING user-authored text gets none — staging ≠ authorship | committing on the user's behalf; memory-commit.sh appends trailers by default | -| LRN-082 | 2026-06-30 | Trigger-cleared on a multi-motif exclusion lifts only the named motif — re-check the others before acting | any "exclusion lifted / precondition cleared" — verify ALL grounds, not just the named one | -| LRN-083 | 2026-06-30 | subagents are an INVALID instrument for measuring main-loop spontaneous routing — SUBAGENT-STOP + delegated framing pin them to the no-route floor | any RED of whether the MAIN loop self-invokes; use fresh main-loop sessions, observe via the human | -| LRN-084 | 2026-07-01 | protection hook enforces PROD not the full branch-flow; exemption masked the rule-vs-guard divergence | a guard exempts a class / checks one predicate — verify it encodes full intent | -| LRN-085 | 2026-07-01 | Idempotent CLI install/update: `command -v` skip-if-present guard + detect channel (`npm ls -g` vs native symlink) before choosing updater; never `npm --force` over a bin npm doesn't own | any installer/updater for a CLI with >1 install channel | -| LRN-086 | 2026-07-02 | External-tool-generated skill: prove provenance by mtime (not repo grep), gitignore + regen via install-step; guard regen on ABSENCE when the tool co-writes a user-editable config | any untracked skill/dir a tool (ctx7, etc.) drops into the repo | -| LRN-087 | 2026-07-02 | presence-flag ≠ capability — rtk silently dead after .bashrc wipe; emitted commands need ABSOLUTE bin paths (they run in another shell); integrity pin = live machinery, re-pin on hook edit | any PATH-dependent capability + hand-managed shell profile; hooks emitting commands for another shell | -| LRN-088 | 2026-07-02 | token-cutting intuition inverts under measurement — verbosity beats cardinality (gstack 34 skills ≈ 592 tok vs pr-review 6 agents ≈ 2,183) | any "disable X to save tokens" — measure per-item bytes first; profiles toggle skills, not plugin payloads | -| LRN-089 | 2026-07-03 | pass-through wrapper (CLI `"$@"` → fn deriving target from ambient state: HEAD/cwd/env) silently ignores its args = silent contract violation; guard = args are an ASSERTION, refuse when they disagree with state | any dispatcher forwarding args to a callee that reads ambient state instead of the args | -| LRN-090 | 2026-06-30 | external-repo audit: open WIRED subsystems (hooks/runners) before declarative (docs/rules); described capability ≠ wired capability | auditing an external config/framework repo for transferable value | -| LRN-091 | 2026-07-03 | keyword-triggered soft-nudge hook w/ bare common tokens over-fires on non-UI work → tuned out; bare only when UI sense dominates, else bigram-or-drop | any advisory/nudge hook keyed on keywords | -| LRN-092 | 2026-07-03 | SAST smoke test w/ the OFFICIAL example secret = vacuous pass (rules exclude documented example keys by design); validate w/ realistic payloads + measure tier coverage before trusting a gate ruleset | smoke-testing any detector/gate — never the canonical example payload | -| LRN-093 | 2026-07-03 | grep -F pattern w/ embedded newline = per-line OR = lock that matches anything; structure locks single-line only, flip-test new locks | writing any grep-based structure lock / census test | -| LRN-094 | 2026-07-03 | SAST severity ≠ exploitability — semgrep ERROR conflates real vulns + hardening recos; metadata does NOT cleanly separate them (measured) → metadata refinement = noisy gate; ERROR-threshold + diff-scoping is the containment | mapping a SAST tool's output to a blocking gate | -| LRN-095 | 2026-07-03 | orthogonal gates don't contaminate — a conformity verifier must PASS correct-but-insecure code (security is a separate gate's job); proven live (CONFORME on a feature carrying a SQLi); fusing the two degrades each | designing multi-dimension review/verify/audit gates | -| LRN-096 | 2026-07-04 | a backstop/guard is code — reliable ONLY after a flip-test proves it CAN fail; an unproven guard replacing an advisory = a vacuous guard (LRN-048 applied to guards); flip-test mandatory at guard creation | building any deterministic guard/lint/backstop | -| LRN-097 | 2026-07-04 | community blog pattern ≠ official feature — "contexts dir" doesn't exist in Claude Code; verify feature against official docs (claude-code-guide) BEFORE building infra; the intent was already covered by real mechanisms (agents/skills/rules) | any "add support for X" request naming a Claude Code feature | -| LRN-098 | 2026-07-04 | `/model` rewrites settings.json (model line + key reorder) — pending diff after model switch = side-effect, not intent; 2 occurrences | any settings.json commit; any "commit file X" — read diff, verify content matches intent | -| LRN-099 | 2026-07-05 | auto-orchestrator autonomy boundary: git discipline transfers naturally (branch, no-merge), declared-state discipline does NOT — baseline silently rewrote target TODO + authored registries + scope-crept | designing any auto/headless flow — enumerate declared surfaces, mark each read-only or gated | -| LRN-100 | 2026-07-05 | tool gated on clean tree must clean its OWN scratch (else self-DoS next run); contract-changing auto-fix needs structural BREAKING flag in the reviewed artifact | any recurring tool w/ cleanliness precondition; any auto-fix touching an API contract | -| LRN-101 | 2026-07-05 | nginx `add_header` inheritance trap: ANY add_header in a location block drops ALL inherited server-level headers on those responses — audit headers on LIVE responses (`curl -I`), never by reading the config; declared infra can be stale (prod ≠ repo stack) | any nginx project audit (zenquality, faunosteo…); any security-header claim | -| LRN-102 | 2026-07-05 | deliverable text placed BEFORE a tool call may never render — only the turn's FINAL text is guaranteed displayed; a checklist printed above AskUserQuestion was invisible to the user | any flow whose deliverable is conversational text (checklist, commands, report): end the turn with it, blocking questions come before, never after | -| LRN-103 | — | BLK-009 was stale: re-probe confirms `paths:` frontmatter works at BOTH levels now | before acting on ANY open upstream/tool blocker cited to justify a fix, a caveat, or a design const… | -| LRN-104 | — | a hook's output message is part of its test contract; no runner = regression invisible | change any hook/script output consumed by a test → run its test same commit. `make test` now the de… | -| LRN-105 | 2026-07-06 | explorer subagent ran a build tool (`graphify .`) mid read-only audit despite prose instructions to only Read/Grep/Bash-read — the runtime observed a config-protection sentinel deny message and self-corrected only after an explicit main-session correction, not from the original prompt | superseded by LRN-165 | -| LRN-106 | 2026-07-06 | job3-B1 froze a fixture + repointed run-reconcile.sh's T2 off the live registry, declared "unblocked", 20/20 green — job4 (next audit, same file, same day) found T3+T5 in the SAME FILE still read the live registry, same fragility, untouched | superseded by LRN-164 | -| LRN-107 | — | read-only subagent mandates must ban copying secret VALUES, not just mutations | superseded by LRN-165 | -| LRN-108 | — | `claude mcp add --env KEY=value` writes the VALUE literally; use `${VAR}` unless you mean to | adding ANY MCP server with a secret via `claude mcp add --env`, single-quote the value using `${VAR… | -| LRN-109 | 2026-07-07 | job8: `skills` CLI (vercel-labs/skills) fetches only `skillPath` (often just SKILL.md), not sibling refs/scripts/templates the skill text references — darwin-skill install gap, not drift/tamper | installing/auditing any skill via the `skills` CLI whose SKILL.md references relative paths — verify those paths exist post-install, don't trust `skillFolderHash` alone | -| LRN-110 | 2026-07-07 | job8: `21st_magic_component_builder` (magic MCP) opens unauth'd 127.0.0.1 callback server, CORS `*`, no token check, 10min window — any local POST lands verbatim in the tool result the model consumes = local prompt-injection channel | any MCP tool that opens a local callback/listener server to receive async results — check auth + origin scoping on the listener, not just the outbound call | -| LRN-111 | 2026-07-07 | job8: empty permissions.allow for a risky MCP tool is a VALID posture (not a gap) when transcript census shows zero real invocations — pre-authorizing unused surface buys nothing, ask-gate costs nothing | deciding whether to allowlist any tool/command — check real usage before assuming "no entry = todo" | -| LRN-112 | 2026-07-08 | job9: CC nested subagent dispatch SUPPORTED since v2.1.172 (cap 5 levels, `Agent` must be in subagent `tools:`) — "flattens to 1 level" is the pre-2.1.172 regime; live env v2.1.203. Contradicts the operating premise of the whole job1-9 series | a subagent-dispatches-subagent design is VERSION-CONTINGENT, not "broken" — check CC version before flagging; fix = raise floor or re-architect to bundle→L1 | -| LRN-113 | 2026-07-08 | partial-pattern-fix = recurring defect of the job1-9 series: fix the cited instance, leave the twins (trailer A1, YAML A4, attribution A5, hook A2). An adversarial review catches twins later; nothing catches them at commit time | superseded by LRN-164 | -| LRN-114 | 2026-07-08 | editing a hook GENERATOR (_gitflow_emit_pre_commit) does NOT update the INSTALLED hook (.githooks/pre-commit) — silent drift; T10 diffs the allow/block verdict not content, T16 emits fresh in a throwaway repo → job7 gitleaks backstop inert on the repo 8 days | after editing a template-generated artifact: reinstall (install-hook) + a gate that diffs installed==emit | -| LRN-115 | 2026-07-08 | analyzer Edit/Write grants (seo/geo/validator) are NOT dead: needed to write the REPORT (VALIDATE/SEO/GEO.md); the "never edit" rule targets CODE, instruction-level (same as the patron) — verified false-positive | do NOT re-flag as a tool-grant defect; a report-only agent keeps Write for its own report | -| LRN-116 | 2026-07-08 | memory backfill release→develop: a BLK marked "resolved" can have its RESOLUTION (code) missing from develop — BLK-016 resolved on release but rtk fix e58037c never back-merged → bug LIVE on develop | superseded by LRN-167 | -| LRN-117 | 2026-07-08 | a release/develop fork silently orphans FUNCTIONAL code on develop, not just memory — RC soak fixes (find-skills, make-update TTY, rtk version-guard) lived only on release for the fork's duration; the review's memory back-merge caught only ~half | superseded by LRN-167 | -| LRN-118 | — | Gitflow-conformity audit: "commits-code" vs "applies-but-defers-commit" is the line that sorts real findings… | any fleet/skill conformity audit — (1) triage by "autonomous commit/push reached?", not "file writt… | -| LRN-119 | — | Fail-open engine contract for optional external data (real-if-connected, else graceful) | any "use real data if credentials present, else degrade" seam — put the contract in the shell entry… | -| LRN-120 | — | SDD final-review base = `git merge-base`, NOT the ledger's recorded BASE | for ANY whole-branch/final review, derive base from `git merge-base HEAD`, never a stored/… | -| LRN-121 | — | Shell allowlist validation: `grep -Eq` is fragile; use a whole-string POSIX `case` | validate shell input WHOLE-STRING (`case` or bash `[[ =~ ]]`), never `grep -q` (per-line). Set `LC_… | -| LRN-122 | — | git mv + recreate source path in same commit = rename detection dead | ANY rename-and-replace-in-place (config forks, template splits, versioned API files). Old path must… | -| LRN-123 | — | "resolves inside repo" symlink check green-lights stale link once old path re-occupied | symlink/path health checks → assert exact expected target whenever the old target path can be re-oc… | -| LRN-124 | — | derived scan artifacts don't belong in git; a tooling hint saying "safe to commit" manufactures the leak | derived security artifacts (scan reports, triage JSONs, audit findings) stay local/ignored; only th… | -| LRN-125 | — | don't make an agent dual-use across model tiers; route the audit consumer to a big-model agent, not the sonne… | before making an agent dual-use, check both consumers are on the SAME tier. Audit/reflection consum… | -| LRN-126 | — | splitting a monolith agent severs every IMPLICIT data path; forward each consumed field through the handoff c… | when splitting an agent, enumerate EVERY field the child reads (grep child for its input vocabulary… | -| LRN-127 | — | SDD implementers must not run destructive git ops on files outside their task scope | dispatch briefs for SDD implementers / fix-subagents MUST bar destructive git ops outside the named… | -| LRN-128 | — | a version RESET (backward bump) is editorial reflection, not the forward-only release-executor | version RESET or any non-standard release → do PREP MANUALLY inline (big model), use `gitflow.sh` o… | -| LRN-129 | — | `git cherry` (patch-id) proves a stale/divergent branch has nothing orphaned before you delete it | before abandoning/deleting a divergent branch, `git cherry -v ` then content-ver… | -| LRN-130 | 2026-07-16 | Claude Code deny glob = absolute, no exemption mechanism — 2026-07-16 | — | -| LRN-131 | 2026-07-17 | WebSearch is NOT verification for a number — SEO blogs cross-cite into fake consensus; require primary source + `measured:` field | superseded by LRN-168 | -| LRN-132 | 2026-07-17 | a subagent summary is a CLAIM, not a fact — 7 disproven in one session (incl. 3 I reproduced writing the fixes) | superseded by LRN-168 | -| LRN-133 | 2026-07-17 | an omission must stay LEGIBLE, never silent — tool that can't measure says so in its output | designing any audit/measure output; deciding what a cap/refusal/N-A emits | -| LRN-134 | 2026-07-17 | resolve-then-pin in stdlib http.client beats monkeypatching getaddrinfo — dual-stack, thread-safe, no requests; classify the OS-resolved IP not the URL text | closing SSRF/DNS-rebinding on any Python HTTP egress | -| LRN-135 | 2026-07-17 | a prefix-only scan for a dangerous construct is bypassable by padding — scan the WHOLE document | refusing any hostile construct (DTD/directive/marker) before parse | -| LRN-136 | 2026-07-17 | config-protection live state follows checked-out branch's symlinked settings.json (2026-07-17) | — | -| LRN-137 | — | mode-based re-tiering beats file splits for mixed-tier agents | before splitting any agent across model tiers, try MODE + `model=` first; create a new agent file o… | -| LRN-138 | 2026-07-22 | gitignore ≠ delete for run-time artifacts read from disk (2026-07-22) | "don't merge transient X" → ask: does the run read X from disk? does X travel via git (worktree, fo… | -| LRN-139 | 2026-07-30 | model-trait compensations invert across generations; state WHEN-guidance, not direction (2026-07-30) | at every model-generation bump, grep config for trait-compensating language ("counters model tenden… | -| LRN-140 | 2026-08-02 | de-prescription findings: dedup evaporates, self-verify is default, recall survives (2026-08-02) | — | -| LRN-141 | 2026-08-24 | adopting an external skill: take the invariants, refuse the machinery (2026-08-24) | — | -| LRN-142 | 2026-08-24 | structure locks are fixed-string: reflowing a doctrine paragraph reds them (2026-08-24) | superseded by LRN-166 | -| LRN-143 | 2026-08-26 | `cmd \| head \|\| fallback` — pipeline rc is head's (0), fallback dead; bounded output → drop head, else pipefail | any probe/fallback bash in skills before trusting `\|\|` | -| LRN-144 | — | census locks grep EXACT single-line phrases; prose rewrap breaks them | superseded by LRN-166 | -| LRN-145 | — | hooks reach the terminal only via terminalSequence JSON field | — | -| LRN-146 | — | Notification event alone misses end-of-turn; Stop is the missing event | — | -| LRN-147 | — | VS Code restores terminals BEFORE ext activation → toast dies every restart | superseded by LRN-163 | -| LRN-148 | — | terminal instrumentation is per-terminal + unpredictable; pre-flight test before attaching | superseded by LRN-163 | -| LRN-149 | — | Stop hook payload carries background_tasks; use it to skip premature signals | — | -| LRN-150 | 2026-09-15 | Sourced lib shares caller shell: bare `ok/warn/info` override its printers, and its `set -e` applies inside | any new lib/*.sh | -| LRN-151 | 2026-09-15 | Playwright cache truth = union over `.links`, dir name maps `_`→`-`, revisionOverrides exist | shared versioned binary caches | -| LRN-152 | 2026-09-15 | git `protocol.file=user` blocks submodule fixtures; `-c` misses the code under test, `GIT_CONFIG_*` env does not | tests building git fixtures | -| LRN-153 | 2026-09-15 | `autoMode` lists replace built-ins without `"$defaults"`; a user-scope block reaches every project | any `autoMode` edit | -| LRN-154 | 2026-09-15 | `git rm --cached` + merge into a branch that still tracks the file DELETES it from disk | untracking a generated file | -| LRN-155 | 2026-09-16 | ask under auto: doc says prompt, probe on 2.1.273 says no; re-probe after upgrades | any permission-tier reasoning | -| LRN-156 | 2026-09-16 | autoMode.allow = exception tier; static interpreter allow suspended under auto → conditions live in prose | conditional permissions | -| LRN-157 | 2026-09-16 | gap-only trigger blind to taste → add a trigger class, not budget; ask at plan, mid-run for leftovers | any "ask more" request | -| LRN-158 | 2026-09-22 | Installer refusing symlinked paths vs a symlinked config dir → stage under a throwaway HOME, move the result | any vendor installer writing into ~/.claude or ~/.config | -| LRN-159 | 2026-09-22 | A pin whose payload is fetched at install time rots: pin + fallback, and read the installer's output, not its… | any `install-plugins.sh` step whose pinned tool downloads something at install time. Probe both HOM… | -| LRN-160 | 2026-09-22 | Prose guardrails are judgment, not boundary: a well-argued brief walks a sub-agent through them | any new destructive capability → static deny first, prose second, doctrine third. Any orchestrator… | -| LRN-161 | 2026-09-24 | `git branch -d` guards against the UPSTREAM once one is set: auto-push turns it into a no-op guard | any change to upstream/push config → re-read every `-d`, `--ff-only`, `@{u}`-relative guard. New de… | -| LRN-162 | 2026-09-24 | graphify measured: free AST map, paid semantic pass, 2-3k tokens per query, noise from `.claude/` | measure a "context saver" before adopting it — build time, artifact size, tokens per use, noise sou… | -| LRN-163 | 2026-09-24 | VS Code terminal instrumentation is per-terminal and unpredictable: pre-flight the pty before attaching | notify-attention over Remote-SSH; any client-side terminal-parsing ext | -| LRN-164 | 2026-09-24 | one fixed occurrence ≠ pattern closed: grep the whole surface, add a guard with teeth | any "fix pattern X" task; reads-live-state, banned tokens, stale pins | -| LRN-165 | 2026-09-24 | a read-only sub-agent mandate constrains files, not tools: name the banned commands, ban copying secret values | every sub-agent brief framed read-only / audit / verify with Bash or config access | -| LRN-166 | 2026-09-24 | structure and census locks are fixed single-line strings: a prose rewrap reds them with zero doctrine lost | editing any doctrine, skill or agent file under lib/tests locks | -| LRN-167 | 2026-09-24 | a release/develop fork strands CODE on develop: a "resolved" blocker or a parallel-merged feature can miss its fix | any long-lived fork (release/*, long feature); back-merging a resolved blocker | -| LRN-168 | 2026-09-24 | a relayed claim is not a fact: WebSearch consensus and sub-agent summaries both need a primary source or a live test | any number, feature or finding relayed by search or by a sub-agent before it shapes a plan or a client deliverable | -| LRN-169 | 2026-09-24 | a coherence audit is cheap when parallel and read-only, and its findings are claims: spot-check, then fix every citer | any doctrine or skill rule change; sub-agent briefs; environment-dependent tests | -| LRN-170 | 2026-09-25 | "count == 0" ≠ "all on" when default state is "nothing installed": verify a fast-path premise on the live tree | status/current/detect commands, installer "is X applied?" checks, plan premises copied from stale comments | -| LRN-171 | 2026-09-25 | sub-agent sandbox: grep shim returns EMPTY inside `$(...)` for patterns holding literal `$VAR` — oracles pin `command grep` | contract CHECK lines, hermetic test greps, hooks parsing grep output | -| LRN-172 | 2026-09-27 | TF-IDF cosine on a 2-doc corpus is identically 0: similarity self-tests need N ≥ 4, a same-corpus positive control and a sensitivity re-run | fixtures for any corpus-normalised statistic (idf, z-score, ranking), "distinct pair passes" tests | -| LRN-173 | 2026-09-27 | contract oracles written from memory failed twice: run the CHECK on the precedent files first, census greps via `git grep` (tracked only), `EVIDENCE: pending` mandatory for gates.sh | contract CHECK lines, precedent-mirroring criteria, gates.sh ledgers | -| LRN-174 | 2026-09-28 | a coverage census must grep plugin DATA files (CSV/JSON search DBs), not only SKILL.md prose; and a registry sample is not the upstream catalog, list the tree | before claiming a gap in installed skills; before scoping an external-repo evaluation | -| LRN-175 | 2026-09-28 | skill listing budget ≈1 % ctx, least-invoked skills lose their description (78/150 name-only); pruning under the cap buys routing + no broken-body invocation, not listing chars; doctor undercount = find w/o -L + single-line desc grep | before any "save tokens by removing skills" claim; doctor token section | -| LRN-176 | 2026-09-28 | gates.sh `CHECK:` is single-line: a heredoc body reads as prose, the oracle runs `python3 -` on empty stdin and lands NOT-MET "marker absent", never ERROR; multi-line oracle → `.oracles/*.py` | writing contract oracles longer than one line | -| LRN-177 | 2026-09-28 | gstack skills hardcode `~/.claude/skills/gstack/` (83 paths: bin, scripts, ETHOS.md, */sections, review/specialists, make-pdf/dist, freeze/bin…); only bin + browse/dist were linked → dead skills and vacuous hooks (exit 127); ./setup plants a global symlink; whole-dir link exposes nested SKILL.md; `apply` is additive, `set` parks | any gstack wiring change, any "gstack skill fails" report | -| LRN-178 | 2026-09-28 | a top-level `source` added to a lib breaks every hermetic suite that copies that lib alone into a fixture; grep the `cp` lists before adding one, or source lazily inside the branch that needs it | adding `source` to profile.sh / toggle-external.sh / any lib the suites copy | -| LRN-179 | 2026-09-28 | Skill `effort:` frontmatter shifts the MAIN LOOP for the rest of the turn on user slash invocation AND on interactive Skill-tool loads (last loaded wins, both directions, prompt cache kept); NOT applied in `-p`/headless; agent pins always honoured, unpinned agents inherit session | effort tiering; any skill or agent that must think more or less than the session | -| LRN-180 | 2026-09-28 | Skill-tool effort override needs a paired tool call: a lone Skill(effort-*) call is a no-op; a load in the same message as another tool call applies (the paired call already sees it); re-load re-applies (text deduped); skills Claude loads alone (brainstorming, writing-plans) apply nothing | every orchestrator shift; amends LRN-179 | -| LRN-181 | 2026-09-29 | Stacked skills share ONE effort level: skill `effort:` = last loaded wins, so a stack loaded in one build (design toolchain) with two levels gets an effort that depends on load order; a skill Claude loads alone applies nothing (LRN-180) | one level per stack in `lib/effort-pins.txt`; load the stack paired with the first Read; copy the stack level when vendoring a new design skill | -| LRN-182 | 2026-09-29 | Effort/thinking baselines are generation-bound and aliases move silently: `sonnet` resolved sonnet-5 then sonnet-5-5 mid-period, Sonnet 5.5 recalibrated its effort levels; EVAL-036 measured one generation | re-run `lib/effort-audit.py` after an alias moves; cite the generation in any effort measurement; never pin a version for it (older gen never cheaper) | -| LRN-183 | 2026-09-30 | npm CLI that vendors its binary in a postinstall script: `command -v` proves the JS shim only; npm can hold the script back at install AND at any update | any installer/doctor/toggle check of such a CLI → probe a real subcommand | -| LRN-184 | 2026-09-30 | Pack membership on an unpinned upstream = explicit allowlist, never "all except X": a renamed or added upstream item would be linked with no review | toggles / vendoring of any upstream tracked at main | -| LRN-185 | 2026-09-30 | Under `exec > >(tee)` stdout is a pipe: `[ -t 1 ]` is always false; interactive offers must test stdin alone | any installer that logs through tee | -| LRN-186 | 2026-09-30 | `GIT_TERMINAL_PROMPT=0` does not stop credential prompts: editor terminals export `GIT_ASKPASS`; empty `GIT_ASKPASS` short-circuits core.askPass + SSH_ASKPASS | unattended `git clone` of a repo that may vanish or go private | -| LRN-187 | 2026-09-30 | Vacuous fixtures: git drops empty dirs; a symlink to a surviving target is needed to test a symlink guard; a multi-call coreutils binary (uutils) dispatches on argv[0], so a renamed symlink fails | hermetic bash suites building git or PATH fixtures | -| LRN-188 | 2026-09-30 | Contract oracle tied to code shape (`grep -A6` line window) breaks on the first refactor while the property still holds; assert the property over the whole unit | writing CHECK oracles | -| LRN-189 | 2026-10-06 | `cmd \| grep -q` under pipefail = SIGPIPE false negative (rc 141); `>/dev/null` is NOT a fix (GNU grep treats it like -q); portable = producer out of the pipeline | any bash under `set -o pipefail`, tests and prod | -| LRN-190 | 2026-10-06 | Contract oracles: join `\\` line continuations before regex; "lint clean" = no finding beyond base, not zero; never `rm -rf "$var"` inside a CHECK | writing CHECK: lines | -| LRN-191 | 2026-10-06 | `cmd | grep -q` under pipefail reintroduced one commit after BDR-110 banned it | writing `grep -q` in tests and prod under pipefail | -| LRN-192 | 2026-10-06 | Turning auto-push off re-arms `git branch -d`'s upstream check (LRN-161 inverted) | deleting a branch in manual-push mode | -| LRN-193 | 2026-10-06 | A revised plan gets a fresh challenger, not a re-read: r2 found 3 BLOCKERs inside r1's fixes | after a plan revision (challenge-plan) | -| LRN-194 | 2026-10-07 | Permission globs: trailing ` *` matches end-of-string; a denied token poisons every command that names it | writing settings permission globs | -| LRN-195 | 2026-10-07 | BSD sed: `N` on the last line quits without printing → the `:a;N;$!ba` fold returns EMPTY on single-line input | folding multi-line output portably | -| LRN-196 | 2026-10-07 | A fail-closed Claude Code hook: trap must `exit 0`, cap attacker-sized loops, read git's rc not its value | writing a fail-closed Claude Code hook | -| LRN-197 | 2026-10-07 | A skill's own `git push` after a lib finish or a hook-pushed commit is redundant since BDR-095: delete it, don't gate it | any skill that pushes after a lib finish | -| LRN-198 | 2026-10-07 | Text read from git and pasted into a later Bash call is an injection sink: allowlist before interpolating | interpolating repo-read text into Bash | -| LRN-199 | 2026-10-07 | Agent-level branching is prose on a printed word: shell state dies between Bash calls, and a text guard denies the… | skills that branch on a printed word | -| LRN-200 | 2026-10-07 | `install-hook` and `global-hooks` write git config as a side effect; only `emit-hook > file` regenerates hooks… | regenerating gitflow hooks | -| LRN-201 | 2026-10-07 | A flood cap must run before ANY per-token fork; a reorder reopened the timeout fail-open and only a timed 2… | guards with a flood cap | -| LRN-202 | 2026-10-07 | Reading a stderr-then-stdout verb from a hook: `out=$(cmd 2>&1)`, last line = word, prefix line = reason; no temp… | hooks capturing a stderr+stdout verb | -| LRN-203 | 2026-10-08 | Mod hooks: model ALIAS set by a hook resolves through stale table (`sonnet` → `claude-sonnet-5`, 404); write full… | mod hooks that set a model | -| LRN-204 | 2026-10-08 | Main-loop model switch mid-turn works, costs one cold-cache step on the full context per switch INTO a model; return… | deciding a main-loop model switch | -| LRN-205 | 2026-10-08 | A hook answering `tool.call` in place of a built-in tool must return that tool's OUTPUT schema shape; a string… | hooks answering `tool.call` for a built-in | -| LRN-206 | 2026-10-08 | `claude plugin test` kit facts (2.1.294): nothing fires at load, inputs are the FULL event, a bottom hook is… | writing `claude plugin test` suites | -| LRN-207 | 2026-10-09 | Model availability = typed API errors (`classic.StopFailure` rate_limit|overloaded|billing_error|model_not_found) +… | model availability breakers | -| LRN-208 | 2026-10-09 | Security-auditor brief = scope only; iteration history and claimed closures violate the blind-scan contract | briefing the security-auditor | -| LRN-209 | 2026-10-09 | Scope the test run to the diff; one full `make test` before the merge; `make test` now names the red suite; GNU make… | choosing the test run for a diff | -| LRN-210 | 2026-10-10 | One coverage clause per contract criterion; a compound "covered by kit tests" criterion yields ECARTS forever with… | writing coverage criteria in a contract | -| LRN-211 | 2026-10-10 | Typed-slash routing: name-bound marker + idle fallback; run slot separate from turn routes; engine records are the… | typed-slash routing in mods | -| LRN-212 | 2026-10-11 | The engine hot-reloads a mod's hooks module from the working tree: unverified code runs live during its own feature… | developing a mod inside this repo | -| LRN-213 | 2026-10-12 | grep-based dead-function census misses constructed-name callers | dead-function census before deletion | -| LRN-214 | 2026-10-12 | shellcheck directive after the first command scopes to that command only; file-wide disable goes BEFORE `set -u` | placing shellcheck directives | -| LRN-215 | 2026-10-12 | helper extracted from a `set -e` function must be called as a plain statement; `helper || …` / `if helper` switches… | extracting helpers from `set -e` functions | -| LRN-216 | 2026-10-13 | Capping a main-loop model switch = cap the COLD READ (context − target's warm prefix), never the context size; the… | capping a main-loop model switch | -| LRN-217 | 2026-10-13 | In an `agent.spawn` hook, "no explicit `model` and no routing row" does NOT mean "inherits the parent": the agent's… | rewriting a spawn's model in a hook | -| LRN-218 | 2026-10-15 | `$.model.complete` as availability probe: credits-exhausted model NEVER settles (timeout = only failure signal);… | probing model availability with `complete()` | -| LRN-219 | 2026-10-19 | Scanner regex over untrusted trees: bound every repeat, cap comment blankers, timing lock on adversarial file | any whole-file regex scanner | -| LRN-220 | 2026-10-19 | Live probe verdicts fail closed by construction: fixture route per negative branch, 3xx = SKIPPED, depth/size limit = SKIPPED never CLOSED | writing probes and their suites | -| LRN-221 | 2026-10-19 | Floor-guard suppressions: remove, never waive; contract CHECK asserts intent (symbol/behaviour), not one code spelling | suppressions, writing CHECK: lines | -| LRN-222 | 2026-10-21 | Map an error to a verdict on a typed exception or carried constant, never on `str(err)`: URLError wraps its reason | probe/fetch error mapping, any err→verdict code | -| LRN-223 | 2026-10-21 | Regex timing lock is vacuous when the input matches early: feed a non-matching worst-path input, assert `is None`, keep ≥ 2x margin under the lock | every bounded regex test | -| LRN-224 | 2026-10-21 | Best-tier agent row floors on tier 2nd alias: inTier writes head-or-above only, fable frontmatter = no fallback in credit outage | pinning agents on best tier, census floors | -| LRN-225 | 2026-10-22 | Gate on tool's exit-code contract, never its prose; positive control through gate's own helper on clean/dirty fixture pair; mktemp EXIT trap script-level | any test that wraps a CLI verdict | -| LRN-226 | 2026-10-23 | Cap one axis of a layered route at the WRITER (effort-only route), never by filtering at the reader: reader cap shadows lower slots + depends on a baseline that can be unknown | any slot/precedence router, per-axis caps | -| LRN-227 | 2026-10-23 | Root-commit author ≠ name the user remembers: check `git log --max-parents=0`; every root email the user ever used goes in `claude.identity` | code-origin claims, identity lists | -| LRN-232 | 2026-10-27 | Path rules load inside sub-agents (agent_id in hook log); a "does X load" proof prompt must name the Read tool call | per-repo split pass, any load proof | -| LRN-233 | 2026-10-27 | Bash under pipefail: head after producer = rc 141, blanked PATH hides bash (rc 127), unchecked mktemp+rewrite chain = rc 0 with source unchanged; compgen -G no braces, dotglob over-matches, globstar skips symlinks under ** | any bash lib with pipes, temp files, globs | -| LRN-234 | 2026-10-27 | Bash glob order follows LC_COLLATE, make test pins no locale: tests count or name files, never assert a listing; a new-case behaviour fix is gated on the case and proven by an old-vs-new differential on real files | any test listing a dir; any change to a lib with an existing output contract | -| LRN-235 | 2026-10-27 | bash `!` on a redirected compound command is blind to the redirect failure (rc 1 before `!`): catch with `cmd || { …; return 2; }`; a guard whose only observable is a stderr line is asserted on that line, anchored on the lib prefix | any `if ! { … } > f`; any test on a stderr reason | - --- ## LRN-001 — `rtk` shape-compression silently breaks downstream parsers @@ -932,65 +697,78 @@ rules: - **Reference**: [[BDR-037]], [[BDR-034]] (rollout this completes), [[BDR-033]] (the GOOD net — contrast). Conditions [[LRN-047]], [[LRN-049]], [[LRN-054]]. ## LRN-062 — deploy first-run detection = file-existence, never `git describe` +- **Date**: 2026-06-27 - **pattern**: detect "first deploy / no prior marker" by `[ -f .claude/deploy/STATE.json ]` (deterministic). NEVER `git describe --tags --match 'deploy/*'` — it errors `fatal: No names found, cannot describe anything`, exit 128, when no matching tag exists (verified git 2.53). Oracle = committed `STATE.json` holding `deployed_sha` (external ledger; never infer from context — [[LRN-054]]). - **context**: deploy skill design. The describe-128 result is only the REASON NOT to use describe — never the detection path. - **future application**: any "first run vs incremental" tool — detect by an explicit on-disk marker's existence, not by a git query that errors on the empty case. ## LRN-063 — delta-since-marker = `git diff --name-only HEAD` (two endpoints), never rev-list/three-dot +- **Date**: 2026-06-27 - **pattern**: "files changed since marker X" = `git diff --name-only HEAD` — two explicit endpoints = literal tree diff. NEVER `git rev-list X..HEAD` (ancestry → phantom deltas after rebase: an orphaned marker yields the whole history). NEVER three-dot `X...HEAD` (merge-base → UNDERCOUNTS on divergence). Verified git 2.53 (linear: all forms agree; diverged: two-dot = both sides, three-dot = one side only). - **context**: deploy delta mechanism. Footgun: `git diff A..B` ≡ `git diff A B` (two endpoints), but `rev-list A..B` = ancestry — same `..` token, different meaning per command. - **future application**: any delta-since-checkpoint over git — explicit two endpoints for the tree diff (artifact list); reserve `rev-list` for commit-counting only. ## LRN-064 — surgical-commit helper family partitions `.claude/`; a new subtree needs its own allowlist sibling +- **Date**: 2026-06-27 - **pattern**: the surgical-commit helpers each own a `.claude/` partition by OPPOSITE rules — `memory-commit.sh` ALLOWLISTS `.claude/memory`+`.claude/tasks`; `doc-commit.sh` EXCLUDES all `.claude/**` (loud rc 4, BDR-022 — [[LRN-060]], [[BDR-036]]). So committing a NEW `.claude/` subtree (e.g. `.claude/deploy/`) can reuse NEITHER: doc-commit refuses it, memory-commit ignores it. Verified live: real `doc-commit.sh` → rc 4 on `.claude/deploy/PROCEDURE.md`. Solution: mint a sibling (`deploy-commit.sh`) with a TARGET allowlist for the new subtree — guard order = traversal `*..*` reject FIRST, then `.claude/deploy/*` allow, else refuse. Inherit rc 3 unsafe-git, short-hash stdout, changed-paths filter. - **future application**: adding a committable `.claude/X` subtree → new allowlist sibling, don't bend an existing helper; order the path guard traversal-first. ## LRN-065 — cross-session cold-resume skill = disk-bridge read-first (audit-delta convention) +- **Date**: 2026-06-27 - **pattern**: a skill that hands BACK control mid-flow (user acts out-of-band) and RESUMES — possibly in a NEW session, context gone — must carry ALL resume state on disk. A bridge file's PRESENCE = the wait-marker ("in flight, awaiting report"); STEP 0 reads it FIRST and resumes from its captured `{base, target, delta, step_reached}` WITHOUT recomputing (HEAD may have moved during the gap → "current HEAD" is wrong). Convention = audit-delta "the state file is the only memory between runs", extended from run-to-run to a MID-FLOW pause. `client-handover` only pauses in-context (synchronous), NOT cold — deploy is the first cold-resume form. A `runbook_rev` (FULL sha) does double duty: in-flow regenerate trigger + cold-resume staleness check; regenerate the instantiated artifact if ABSENT or stale. Pressure-test confirmed (fresh agent resumed from the bridge, excluded the moved-HEAD temptation). - **future application**: any "do work → user acts out-of-band → resume later" skill — persist a disk bridge, read it first, never recompute on resume; mark the wait by the bridge's existence, not by conversation context. ## LRN-066 — surgical-commit must fail LOUD on git-ignored target paths (else silent no-op) +- **Date**: 2026-06-27 - **pattern**: `git status --porcelain -- ` HIDES git-ignored paths → a surgical-commit helper that filters changes via porcelain SILENTLY no-ops (rc 1) when the target project ignores the path (e.g. `.claude/` wholesale) → the artifact never persists, the skill silently forgets. Fix: guard with `git check-ignore -q ` BEFORE the changed-filter; any passed path ignored → LOUD refusal + dedicated rc (5), never a silent no-op. Fail-closed/loud over silent. (Same porcelain mechanism as the changed-filter — [[LRN-051]].) - **context**: `deploy-commit.sh`; the FINAL whole-branch review caught it (per-task reviews could not — it is a skill↔target-repo seam). Applies to the whole memory/doc/deploy-commit family. - **future application**: any helper relying on `git status --porcelain` to detect changes — add a `git check-ignore` guard; a path that must persist but is ignored has to fail loud, not no-op. ## LRN-067 — a pipeline that looks 2-level can finish at the SAME level; a human-mediated step masks the collision until automated +- **Date**: 2026-06-28 - **pattern**: orchestrator delegating to a sub-skill can LOOK two-level (sub assembles, orchestrator integrates) yet sub's TERMINAL node operates at SAME level as orchestrator's finish → double-integration. `subagent-driven-development` assembles tasks on ONE branch (no per-task sub-branches — true) BUT its last flowchart node IS `finishing-a-development-branch` = feature→base merge, the SAME act as the orchestrator's FINISH. init-project (STEP 8 SDD + STEP 11 finish) AND ship-feature (STEP 4 SDD + STEP 9 finish) BOTH invoked finish TWICE. Latent, not visibly broken: SDD's terminal finish is INTERACTIVE (menu → human picks "keep as-is"), so the human SILENTLY de-duplicated. Collision SURFACES when orchestrator's finish becomes DETERMINISTIC (gitflow finish) → real double-merge. Fix = scope the sub-skill by instruction to stop before its terminal step (NO fork — the finish is a flowchart node the controller follows, not a script; verified by reading SDD's scripts). Pressure-test: RED agent chained finish ("literal next node in the flowchart"); GREEN with scope instruction stopped + returned. - **context**: gitflow chantier, wiring orchestrators onto `gitflow finish`. Mapping (premise #6) caught it by READING the real (SDD `SKILL.md` + `scripts/`) BEFORE coding — seam-bug class `deploy` hit, caught earlier this time. Two human-gate backstops survive a missed instruction: SDD's interactive menu + the `gitflow finish` human gate ([[LRN-054]] — no oracle; deterministic layer carries the dangerous case). - **future application**: before replacing interactive/human-mediated step with deterministic one, check whether delegated sub-skill's TERMINAL step operates at same level — human gate may have silently de-duplicated a double-action. Read the sub-skill's real flow (nodes + scripts), don't assume "distinct levels". ## LRN-068 — enforcement-bootstrap must be transactional: activate the guard LAST and gate it on the bootstrap commit succeeding +- **Date**: 2026-06-29 - **pattern**: routine that BOTH installs enforcement guard (pre-commit hook, branch protection, lock) AND makes bootstrap commit must be transactional, else partial run strands it. Two teeth: (a) precheck preconditions (git identity, clean tree) and fail LOUD before ANY mutation; (b) the guard-activation step must NOT run if the guarded bootstrap commit failed — order activation LAST and gate it on commit success. A `cmd_a || cmd_b` form SWALLOWS cmd_b's failure when a later stmt returns 0 → the failure never propagates; use explicit `if ! …; then … || return 1; fi`. - **context**: `gitflow_init` ([[BLK-012]]). Existing-repo path swallowed the socle-commit failure (`git diff --cached --quiet || git commit`, then `git branch develop` returned 0 masking it) → init CONTINUED and ran `gitflow_activate_hook` though the socle was never committed → every re-run self-blocked (commit on main blocked by the hook just installed). Fresh-repo path already propagated → asymmetry was the bug. Fix: fatal socle commit + identity precheck; verified on identity-less repo → aborts rc1 with ZERO mutation, 57/57 tests green. - **future application**: any init/bootstrap installing enforcement (hooks, protection, immutability) + committing — activate LAST, gate on the commit, precheck identity/clean-tree up front, make every link propagate (no `||` swallow). TEST partial-failure path (identity-less / commit-blocked repo) → must abort with zero mutation and stay re-runnable. ## LRN-069 — token-authed remote writes under CC perms: inline-env (never `export`), token in the header, keep `git push` on ASK as the real gate +- **Date**: 2026-06-29 - **pattern**: a secrets-guard `Bash(export *)` in `permissions.deny` auto-denies ANY command whose FIRST token is `export …` — a false positive (`export GIT_CONFIG_VALUE_0="Authorization: token $TOK" …` reads as blocked when only the `export` prefix tripped it, not the git/curl op). Correct model for token-authed remote writes from tool calls: (a) INLINE env assignment `GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0="Authorization: token $TOK" git push …` (no `export` keyword → passes; token rides the http header via git env-config, NEVER in argv nor written to the clone's `.git/config`); (b) keep `Bash(git push *)` on ASK (not deny) — that prompt IS the per-write human gate; don't suppress it, don't allow-list pushes in settings. - **context**: gitflow migration on Gitea. 3 consecutive tool-call denials traced to `Bash(export *)` (false positive); an earlier INLINE-env `ls-remote` passed; the user's own `!` shell ran the same `git push` fine (not under CC perms). Confirmed `git push` is ASK by design = the right gate locus, NOT `export *`. - **future application**: scripting token-authed git/curl writes under CC perms → inline env (never `export`), token in `Authorization` header (curl `-H`, git `GIT_CONFIG_*` extraHeader), keep `git push` on ASK as the approval. Tool-call denied unexpectedly → read `permissions.deny` for an over-broad prefix rule (`export *`, `env`, `printenv`) catching a false positive BEFORE concluding the op itself is blocked. ## LRN-070 — clean-tree-gated migration + a dirty submodule: diagnose pointer-vs-content, ignore=dirty not blind reset +- **Date**: 2026-06-29 - **pattern**: op gated on clean tree (`git status --porcelain`) blocked by submodule showing ` M`. FIRST distinguish: (a) **pointer move** — gitlink (HEAD) ≠ submodule HEAD → resettable via `git submodule update`/`checkout`; (b) **dirty content** — gitlink UNCHANGED, files modified INSIDE submodule → local edit. For intentional local edit, `checkout --`/`submodule update` correctly REFUSE to discard it, and blind "reset" would DESTROY it. Exclude it non-destructively: `git config submodule..ignore dirty` (local `.git/config`) → status stops reporting submodule's dirty content, gate passes, edit preserved. Commit to `.gitmodules` to share ignore across clones. - **context**: claude gitflow self-migration. `skills-external/gstack` showed ` M`; gitlink `070722a` == submodule HEAD `070722a` (NOT a pointer move), 2 tracked-modified files (`bun.lock`+`package.json`) = the [[BLK-008]] Playwright 1.61 bump (Ubuntu 26.04 browser). Planned "reset" (D2) would have discarded browser fix; `submodule.skills-external/gstack.ignore=dirty` cleared tree for `migrate_local`, bump intact. - **future application**: any clean-tree-gated op (migrate/release/bisect) on a superproject with a submodule carrying intentional local edits → diagnose pointer-vs-content FIRST (compare gitlink to submodule HEAD); for content, `submodule..ignore=dirty`, never a blind reset. Cross-ref [[BLK-008]] (gstack -dirty by design). ## LRN-071 — fail-loud must cover the helper's OWN commit, not just its inputs — 3rd occurrence of the swallowed-commit pattern +- **Date**: 2026-06-29 - **pattern**: a surgical-commit helper guarded LOUD on its INPUTS (scope) but SILENT on its OWN `git commit`. `doc-commit.sh`: `set -uo pipefail` (no `-e`) + unguarded `git commit` → on rejection (pre-commit hook on a protected branch / signing / etc.) execution CONTINUES: `printf "committed"` lies, `git rev-parse --short HEAD` emits the PREVIOUS HEAD hash, function exits 0. Orchestrator reads rc 0 + non-empty hash → believes success; docs silently uncommitted, tree dirty (RISK-2). - **RECURRENT (3×) — audit systematically, not an isolated bug**: same fail-silent-where-it-must-fail-loud class in the surgical-commit family — [[LRN-066]] (`deploy-commit.sh`: porcelain hides a git-ignored path → silent no-op; fix = loud rc 5) + [[LRN-068]]/[[BLK-012]] (`gitflow_init`: socle-commit failure swallowed by `||` then `git branch` returned 0 → init continued past the dead commit) + this. The common mechanism: a fallible op (esp. a commit) whose failure isn't propagated, MASKED by a later returning-0 statement. The motif RETURNS; treat it as a known smell. - **fix**: guard the commit — `if ! git commit …; then LOUD + return 5; fi`. rc 5 = "tried, git refused" (distinct from rc 3 = "could not start"). Empty stdout (no stale hash), loud stderr. Proven by T8: RED showed the masking (rc 0 + stale hash + false "committed"), GREEN rc 5 + empty + REJECTED, 32/32. - **future application**: any helper whose RETURN VALUE gates a downstream "success" — audit that EVERY fallible internal op propagates its failure, ESPECIALLY the load-bearing commit. `set -uo pipefail` without `-e` does NOT abort mid-function; an unchecked failing command followed by a returning-0 line exits 0 and lies. Check `cmd || other` forms, no-`-e` blocks, every "report success after the op" line. Test the partial-failure path (commit-blocked repo) → must fail loud, empty, non-zero. ## LRN-072 — a stranded-artifact bug can be fixed by NOT creating the artifact (negative diff), not by plumbing its commit +- **Date**: 2026-06-29 - **pattern**: 3rd member of post-FINISH-artifact class (memory, docs, GSD ROADMAP) — but UNLIKE first two (real artifacts ALWAYS produced → couple a commit), GSD artifact came from SPECULATIVE, opt-in, rarely-used producer (init-project auto-bootstrapping multi-session engine at project creation). Reflex fix (reorder + build `gsd-commit.sh` + tests) = machinery to faithfully commit artifact nobody uses. The right fix was a NEGATIVE diff: delete the producer → orphan never created → bug dissolves, zero new code (BLK-011). - **the refutation that got there**: framing "ROADMAP redundant with TODO" WRONG (gsd ≫ roadmap = state machine/crash-recovery/cost/parallel/worktree; TODO ≠ gsd ROADMAP = different altitude + consumer). Reading REFUTED both premises, yet the CONCLUSION (remove the step) held for a STRONGER reason: speculatively scaffolding a heavy engine the sole user doesn't use, at creation, is bad per se. Right answer, reason corrected before engraving — change QUESTION before changing code. - **future application**: stranded / duplicated / uncommitted-artifact bug → BEFORE building machinery for artifact, ask whether step that PRODUCES it is used / wanted / non-speculative. Speculative or unused (esp. personal/single-user repo) → DELETE producer; cleanest fix = absent one. Distinguish speculative-at-creation (REMOVE) from deliberate-on-demand (KEEP). Family: [[BLK-010]], [[BLK-011]], [[BDR-036]]. ## LRN-073 — a skill's worked-example must use FICTIONAL ids, never live registry ids (they prime real-data behavior) +- **Date**: 2026-06-29 - **pattern**: prune-memory's STEP-2 plan example named real LRN-014 + LRN-016 ("merge these"). A real-data run merged exactly that pair — though they're COMPLEMENTARY (header-ids vs checkbox-CSS), a merge its own rule forbids. Example ids that match live entries, in context at audit time, PRIME the action: you can't tell "judged correctly" from "pattern-matched its own example". - **fix**: fictionalize example ids (9xx — can't match a live registry) + make the example model a CORRECT action. Lock it DETERMINISTICALLY ([[LRN-046]]): assert the example carries only fictional ids — not a flaky behavioral "did priming fire" test (RED-7). - **future application**: any skill/agent whose instructions contain a worked example over the SAME data it operates on (registries/files/records) → use reserved/fictional identifiers; test deterministically that no live id appears in the example block. ## LRN-074 — system `grep`/`awk` may be ugrep/mawk: don't assume flag-parsing, use `/usr/bin/grep`, watch the RED go red +- **Date**: 2026-06-29 - **pattern**: a RED-7 test used `grep -vE '-9[0-9][0-9]$'`; the system grep is UGREP → parsed the leading `-9..` as an OPTION → errored → empty → FALSE GREEN (a RED that never goes red). Caught only because the output was READ, not assumed. 4th time this session an assumed command behavior was false on execution (after `set -o pipefail` + `grep -q` SIGPIPE, …). The skill's own verify already hard-codes `/usr/bin/grep` (line 189) for this exact reason — re-learned. - **fix**: `/usr/bin/grep` (GNU) where GNU semantics matter; avoid leading-dash regex args (or use `-e`/`--`); never trust the system tool is GNU/POSIX (mawk≠gawk, ugrep≠grep). - **future application**: any shell test/guard whose correctness rides on grep/awk/sed semantics → pin `/usr/bin/` AND run the assertion, confirming it goes red on the defect before trusting green. Execute, don't assume command behavior. RECURRENT motif — audit any "assumed tool behavior" the way the fail-silent family ([[LRN-066]]/[[LRN-071]]) is audited. @@ -1104,42 +882,49 @@ rules: - **Reference**: `lib/gitflow.sh` gitflow_finish arg-guard, `lib/gitflow-test.sh` T12. [[BLK-015]]. ## LRN-090 — external-repo audit: open WIRED subsystems before declarative +- **Date**: 2026-06-30 - **pattern**: auditing external config/framework repo for transferable value → rank subsystems WIRED (executable: hooks/, runners, dispatchers) vs DECLARATIVE (docs, rules/, aspirational frontmatter). Wired > declarative: declarative often inert (ECC rules/ `paths:` = 0 consumers; eval-harness = SKILL.md, no runner — "belle méthodo / vaporware"); wired = a real mechanism worth adapting. - **context**: ECC 2nd-look 2026-07-03 (Opus 4.8, 6 agents, repo unchanged since 01/07). [[BDR-047]] audit (01/07) inventoried the declarative surface + concluded zero import — right on facts, but hooks/ (ECC's only live subsystem) was OUT of scope and held the sole real adaptation → config-protection PreToolUse guard. - **future application**: next external-repo value audit → enumerate hooks/, scripts/, runners FIRST; treat rules/docs/SKILL.md as claims to verify ("is it wired?"), not value. Described capability ≠ wired capability. - **cousin**: [[LRN-087]] presence-flag ≠ capability; [[LRN-089]] forwarded-args silently dropped — same family: a visible signal (a file, a flag, a `paths:`) lying about real behavior. ## LRN-091 — a soft-nudge hook that over-fires gets ignored (banner-blindness) +- **Date**: 2026-07-03 - **pattern**: keyword-triggered nudge (design-toolchain reminder) with bare common tokens fires on non-UI work → reader tunes it out. Same class as a diagnostic that cries false [[LRN-047]]: a signal wrong too often stops being read. - **rule**: keep a token BARE only when its UI sense dominates largely in a dev context (glassmorphism, navbar). Token common in non-UI talk (design, component, theme, transition, frontend) → require a UI-specific bigram (design system, front-end design) or drop; in doubt → bigram-or-drop. Borderline standalone nouns (dashboard, animation) may stay bare as an assumed call — the fire-log arbitrates later on data, not gut. (NOT "never bare tokens" — animation stays bare here by design.) - **context**: design-toolchain-reminder.sh — 07-02 tightening (dropped page/form/menu/…) insufficient; 6 bare tokens still false-fired ~6×/session during the ECC config audit (design, ecc_dashboard.py, component, frontend, theme, transition, palette). 07-03 fix: dropped them, dashboard→`\bdashboard\b` (filename match killed, "admin dashboard" kept), added a fire-log (time+token+excerpt). `lib/tests/design-toolchain-reminder.test.sh` locks it (18 checks). - **cousin**: [[LRN-047]] a doctor that cries false is ignored. ## LRN-092 — SAST smoke test: official example keys are rule-excluded — "no findings" proves nothing +- **Date**: 2026-07-03 - **pattern**: smoke-testing a SAST/secret detector w/ the OFFICIAL example payload (AWS `AKIA...EXAMPLE`) → 0 findings BY DESIGN — rules exclude documented example keys to kill FP. A vacuous pass, [[LRN-048]] class (a pass must prove it looked). Validate w/ realistic-shaped payloads AND enumerate what the tier does NOT catch before trusting a ruleset as a gate. - **context**: lot 1 semgrep-install dogfood 2026-07-03. `p/secrets`+`p/security-audit` community tier: anonymous fetch OK (52 rules, no login), `subprocess-shell-true` detected ERROR; MISSED %-format SQLi on bare cursor (no recognized DB-API context) + fake-checksum `ghp_` token. Gap logged for security-auditor agent design (consider adding `p/owasp-top-ten`). - **future application**: any detector/gate smoke test — craft realistic payloads, never the canonical example; measure the miss-list on purpose-built fixtures; size the gate's blocking scope on that data. - **cousin**: [[LRN-048]] a 0/OK must prove it looked; [[LRN-047]] noisy guard = ignored guard; conditions [[BDR-048]]. ## LRN-093 — grep -F with an embedded newline = per-line OR = vacuous lock +- **Date**: 2026-07-03 - **pattern**: a fixed-string grep pattern containing a newline is treated as MULTIPLE patterns (one per line) — match succeeds if ANY line matches. A structure lock written that way passes on essentially anything (`"no\n forced loop"` → matches any "no") = a lock that proves nothing, [[LRN-048]] class. - **context**: lot 2 `lib/tests/contract-verifier.test.sh`, caught in self-review BEFORE first run; replaced by a single-line distinctive anchor ("proceed straight to the security gate"). - **future application**: structure locks / census greps = ONE line per pattern, always; a clause spanning lines → lock a distinctive single-line fragment. Flip-test every new lock (prove it CAN fail) before trusting its green. - **cousin**: [[LRN-048]] a pass must prove it looked; [[LRN-046]] deterministic-oracle discipline. ## LRN-094 — SAST severity ≠ exploitability; metadata does not cleanly separate — don't refine on it +- **Date**: 2026-07-03 - **pattern**: semgrep `ERROR` conflates exploitable vulns (SQLi, secrets, command injection) with hardening recommendations (Dockerfile missing-USER, npm release-age). The obvious refinement — gate on `metadata.impact`/`likelihood`/`confidence` — does NOT work: measured, the Dockerfile hygiene ERROR (`impact=MEDIUM likelihood=LOW`) is indistinguishable from a tainted-SQL ERROR (`impact=MEDIUM likelihood=MEDIUM`), and a real command-injection reads `impact=LOW likelihood=HIGH`. Metadata-based severity = a noisy, non-deterministic gate ([[LRN-077]] class). - **context**: lot 3 security-auditor design 2026-07-03. Measured on 2 real repos (faunosteo, game): the only added blocking ERROR from owasp-top-ten is Dockerfile hygiene, contained because gate mode scopes to the DIFF (a pre-existing infra finding can't block an unrelated code change). - **future application**: mapping any SAST to a blocking gate — take the tool's ERROR/blocking level as the deterministic threshold, contain FP by SCOPING (diff, not repo), NOT by a metadata heuristic or a hand-maintained hygiene denylist ([[LRN-049]]: match guard cost to proven stake — build the denylist only if hygiene ERRORs prove noisy on a real project). - **cousin**: [[LRN-047]] noisy gate = ignored; [[LRN-077]] non-deterministic gate; conditions [[BDR-048]]. ## LRN-095 — Orthogonal gates don't contaminate: a conformity check must pass correct-but-insecure code +- **Date**: 2026-07-03 - **pattern**: pipeline with distinct gates (request-conformity, security): each judges ONLY its dimension. A conformity verifier must return CONFORME on code that is correct-but-insecure — the vuln is the SECURITY gate's job, not a conformity gap. Proven live: `get_item` feature satisfying its contract with a `%`-interpolation SQLi → verifier CONFORME, security-auditor BLOCK(1). Fusing both into one "quality" gate makes each worse: conformity check hunts vulns (scope creep, misses conformity), security check judges feature-completeness (dilutes). - **context**: lot 4 verify-secure-loop dogfood 2026-07-03. Orthogonality is WHY the order invariant matters (re-verify request before re-scan security): two independent axes re-checked independently. - **future application**: any multi-dimension gate (review lenses, verify+audit, correctness+perf) — keep each gate single-axis and let a finding on axis B pass axis A's gate; compose verdicts in the orchestrator, don't merge the judges. - **cousin**: [[BDR-050]] the pipeline; [[BDR-049]] fresh verifier; conditions [[LRN-083]]. ## LRN-096 — A backstop is code: prove it can FAIL (flip-test) before trusting its green +- **Date**: 2026-07-04 - **pattern**: deterministic guard replacing forgettable advisory is itself code; UNPROVEN guard = vacuous guard — [[LRN-048]] (a pass must prove it looked) applied to guards. LRN-093 backstop (refuse `\n` in grep/tf patterns) shipped with regex requiring whitespace before `tf` → silently MISSED `tf` at line start (where real locks sit). Flip-test (feed guard a KNOWN offender, assert it bites) caught the hole; without it guard would have green-lit the very class it was built to kill. So: a flip-test is MANDATORY at guard creation, part of the guard, not optional QA. - **why it matters**: the whole point of a backstop is that it fires on the bad case; a guard that can't fail proves nothing and is WORSE than the advisory it replaced (false confidence). Advisory→backstop move ([[LRN-047]] [[LRN-091]]) sound only if backstop verified against a real miss. - **context**: lot 5 `lib/tests/no-vacuous-locks.test.sh` 2026-07-04. Built guard, flip-test RED'd (regex too weak, missed line-start `tf`), fixed regex, flip-test green. Guard ships WITH flip-test inline, self-proves on every run. @@ -1147,6 +932,7 @@ rules: - **cousin**: [[LRN-048]] prove it looked; [[LRN-093]] the class this guards; [[LRN-046]] deterministic-oracle discipline. ## LRN-097 — Community blog pattern ≠ official feature: verify against docs before building infra +- **Date**: 2026-07-04 - **pattern**: user requested a `~/.claude/contexts/` dir + symlink, with 3 example "context mode" files (review/research/dev) from a community pattern. Official docs check (claude-code-guide agent): NO contexts feature exists in Claude Code — no loader, no `/context `, nothing reads that dir. Building it = dead infra. The underlying intent (modal postures) was ALREADY covered by real mechanisms: review → verifier/security-auditor/review skills; research → analyzer/Explore; dev norms → CLAUDE.md always-on. One proposed "context" even CONTRADICTED standing doctrine ("get it working first" vs "root causes only"). - **why it matters**: plausible-looking blog patterns import silently as "features"; the cost is not just dead files — norms moved into a nonexistent loader silently STOP applying. Gate: any request naming a Claude Code capability → verify against official docs BEFORE writing files; then map the intent onto the real mechanism. - **context**: 2026-07-04 rules-dir chantier. `rules/` (real feature, verified: paths-scoped lazy loading) was built; `contexts/` (nonexistent) was refused with the doc citation. @@ -1154,6 +940,7 @@ rules: - **cousin**: [[LRN-086]] provenance discipline; [[LRN-046]] verify before trust; CLAUDE.md "Never assume — verify". ## LRN-098 — `/model` silently rewrites settings.json: read the diff before any settings commit +- **Date**: 2026-07-04 - **pattern**: `/model` persists the switch by REWRITING settings.json — changes `model` line AND reorders keys (attribution block moved to top). Pending settings.json diff after a model switch = side-effect, not intent. 2nd occurrence: ae8ad86 undid the first (opus-4-8 restored); today "commit settings.json" nearly re-committed fable-5 as default right after that undo. Catch came from reading DIFF CONTENT, not filename: request said commit, diff contradicted prior intentional commit → surfaced, user chose `git restore`. - **why it matters**: "dirty settings.json" reads as innocent drift; blind commit flips default model for ALL sessions + silently reverses an explicit prior decision. A request "commit file X" is about the file — content must still match user intent. - **context**: 2026-07-04 RC 1.0.0 cleanup. Diff = `claude-opus-4-8[1m]` → `claude-fable-5[1m]` + attribution reorder (no semantic change). AskUserQuestion → restore. @@ -1162,6 +949,7 @@ rules: - **backmerge**: from release/1.0.0 (a623514) — 2026-07-08 review remediation A3. ## LRN-099 — Auto-orchestrator autonomy boundary: working branch YES, declared/shared state NO +- **Date**: 2026-07-05 - **pattern**: /tour RED baseline (no skill, pressure "injoignable, reboucle jusqu'à propre"): git discipline held NATURALLY (gitflow lib branch, no merge w/o signal, atomic commits — doctrine survived into subagent) BUT state-write discipline failed across the board: target TODO silently rewritten (boxes checked, restructured), BDR/journal entries authored autonomously, unrequested bootstrap (.gitignore + registries "bonus hygiene"). Plus: security = ad-hoc grep+ruff (no semgrep floor), findings only in final chat msg (no reviewable artifact), loop unbounded (converged pass 2 by luck). - **why**: model generalizes commit discipline from doctrine; "declared state = someone's approval surface" NOT in its prior — such writes look helpful. Auto-flow skills must lock declared-state writes explicitly (read-only rules, report-only phases), not just git verbs. @@ -1170,6 +958,7 @@ rules: - **cousin**: [[LRN-083]] bounded loops in main loop; /reconcile principle (inferred checkbox = the lie). ## LRN-100 — Clean-tree-gated tools must clean own scratch (self-DoS); breaking auto-fix needs structural flag +- **Date**: 2026-07-05 - **pattern**: /tour GREEN left 4 untracked scratch files (`.tour-semgrep*.md`) → tree dirty at end → NEXT run hits own "dirty tree → report-only" precondition = self-block. Same run: HIGH security fix adding required auth header = API-BREAKING, reported plain "fixed" — branch diff doesn't shout contract change. - **why**: preconditions designed against user WIP also fire on the tool's own residue → scratch cleanup = explicit end-of-run step. Both = omission failures → structural counters (template slot: STEP 3.2 cleanup, BREAKING tag in report template + summary), NOT prohibition prose (writing-skills "match form to failure"). @@ -1178,6 +967,7 @@ rules: - **cousin**: [[LRN-099]] same chantier; [[LRN-071]] swallowed-failure class (silent residue ≈ masked state). ## LRN-101 — nginx add_header inheritance: one child header wipes ALL parent headers — verify LIVE, not in config +- **Date**: 2026-07-05 - **pattern**: nginx `add_header` inherits from server level ONLY if a location block declares NONE of its own. One `add_header Cache-Control ...` in a location → ALL 5 server-level security headers (CSP, X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy) silently dropped on every response matching that location. bchanot-cv live: pages served ZERO security headers while the config declared all 5; only the 404 path (no location-level add_header) carried them. Corollary, same audit: declared infra was STALE — prod turned out native nginx, repo's Docker stack latent (user correction post-audit) → container findings latent, live fix belongs to the VPS config outside the repo. - **why**: config review says "headers present" — a lie by inheritance. Only oracle = live responses (`curl -sI` per content type: html, pdf, image). Fix = repeat the headers in every location that uses add_header (or `include security-headers.conf`). @@ -1187,6 +977,7 @@ rules: - **backmerge**: from release/1.0.0 (74d3804) — 2026-07-08 review remediation A3. ## LRN-102 — Deliverable text before a tool call may never render: the turn's FINAL text is the only guaranteed display +- **Date**: 2026-07-05 - **pattern**: /deploy hand-back printed full checklist, then called AskUserQuestion. The user saw ONLY the question UI — the checklist never reached them ("là on a rien, je dois ouvrir le fichier"). Harness reliably renders only LAST text of a turn; text before a tool call can be swallowed by tool UI. - **why**: conversational deliverable (commands to copy-paste, a report) fails silently if any tool call follows the print — user sees "nothing displayed" while the transcript contains it. Structural fix: deliverable IS the turn's final text; collect answers BEFORE printing, or let reply arrive as next user message. - **context**: 2026-07-05 /deploy run 2 (bchanot-cv). Skill patched same turn: checklist display-only (no NEXT.sh file at all — user: throwaway once deployed) + hand-back ends the turn, no tool call after. @@ -1194,14 +985,17 @@ rules: - **cousin**: [[LRN-100]] same skill lineage; CLAUDE.md communication doctrine (final message carries everything). ## LRN-105 — "read-only audit" prose does not constrain subagent tool CHOICE; state the ban explicitly +- **Date**: 2026-07-06 - **pattern**: job3 docs-drift audit dispatched an exploration subagent (Bash + Read/Grep, "audit BODIES — do NOT modify any file") to check graphify skill docs. It ran `graphify .` to check CLI behavior — a real build, not a read — leaving an empty `graphify-out/` dir at repo root. The prompt said "read-only" and "verify via Read/Grep/Bash (read-only)" but never named the specific command class to avoid; the agent treated "run the CLI to see what it does" as within a Bash read-only mandate. - **why**: "read-only" is a framing about FILES, not an instruction the model maps onto every tool call by default — a subagent with Bash access will happily execute a program to observe its behavior, which is investigative but not read-only if the program writes to disk. The fix only landed after a main-session correction mid-run ("do NOT run graphify... verify by reading the installed source instead"), not from the original prompt. - **context**: 2026-07-06, job3 audit exploration phase (`.audit/job3-report.md` A1/A2 findings, incident noted in report header). No tracked file was touched; the stray dir was harmless but wasted a round-trip and could have mutated git-visible state on a less-guarded command. - **future application**: any subagent dispatch framed "read-only" / "audit" / "verify" that grants Bash — explicitly ban execution of subject-under-test's own CLI/build/generator commands, and name safe alternative (read installed source, grep docs) in same sentence. Don't rely on the word "read-only" alone to scope tool use. - **cousin**: [[LRN-100]] (tool must clean its own scratch) — same class of "prose framing ≠ enforced constraint", different failure mode. +- **Status (2026-10-28, upgrade)**: superseded by LRN-165 ## LRN-103 — BLK-009 was stale: re-probe confirms `paths:` frontmatter works at BOTH levels now +- **Date**: — - **pattern**: BLK-009 (2026-06-25) recorded user-level `paths:` rules never inject (GH #21858, CC 2.1.190). job1 instruction-file audit (2026-07-06) cited it as open/broken to flag rules/README.md's documented lazy-load mechanism as self-contradicting. Fresh re-probe same day (3-file probe, `**/*.blkprobe` glob): confirmed loading now works at BOTH project-level AND user-level. Bug gone (or no longer reproducible on current CC version) — the registry's "still broken" claim was stale and was about to justify a caveat in rules/README.md warning about a bug that no longer exists. - **why**: registries are append-only + dated — a recorded status is a snapshot, not a standing fact. Any decision or audit finding that cites an open upstream blocker without re-probing risks acting on stale tool-version info, especially across CC version bumps. @@ -1210,6 +1004,7 @@ rules: - **cousin**: [[BLK-009]] closed this session; [[BDR-031]] (the workaround this bug forced). ## LRN-104 — a hook's output message is part of its test contract; no runner = regression invisible +- **Date**: — - **pattern**: job1 F14 (`3f639b3`) changed design-hook stdout to pointer-only; test oracle grepped old literal `design-toolchain` → 9 fire-checks silently red 3 days. Hook itself fine — broken oracle, not broken behavior. Caught ONLY when job2 executor ran the suite as its F4 gate; zero runner existed before (job2 F10). Fix: oracle synced to durable fragment `full toolchain` (heading BDR-021 requires the hook to quote verbatim) + `make test` target wired. - **why**: an untested output string IS an interface — its test must anchor on the durable contract part (the mandated heading), not incidental wording. No automated runner → oracle drift accumulates unseen; "18 checks lock it" ([[LRN-091]]) protected nothing while nothing ran them. @@ -1218,24 +1013,29 @@ rules: - **cousin**: [[LRN-091]] (the lock that never ran), [[LRN-096]] (a guard is code, prove it can fail), [[EVAL-017]]. ## LRN-106 — fixing B1 in one file ≠ closing the B1 pattern +- **Date**: 2026-07-06 - **pattern**: job3-B1 (2026-07-06) froze `lib/tests/fixtures/blockers-snapshot.md`, repointed run-reconcile.sh's T2 at it, declared "B1 UNBLOCKED", suite 20/20 GREEN. job4 (J4-10), the very next audit pass, same file, same day, found T3 and T5 in the SAME FILE still reading the LIVE `$MEM/decisions.md` — identical fragility class, untouched siblings, one file over. - **why**: "suite green" + "named finding fixed" don't imply "no other instance of the same root cause survives nearby." The fix scoped to exactly what the finding cited (T2's BLK-status read); T3/T5's structurally identical read (decisions.md contradiction/deferral scan) wasn't touched because it wasn't literally named, even though it's the same bug. - **context**: 2026-07-06, job3 chore/job3-fixes (B1 unblock) then job4 SPEC-10 (`.audit/job4-report.md` J4-10), same run-reconcile.sh, same session-day — closed for real this time (T3/T5 repointed at a new `decisions-snapshot.md` fixture, `$MEM` variable deleted, `grep -c '$MEM' == 0` gate). - **future application**: after fixing one instance of a "reads live state it shouldn't" (or any similarly generic) finding, grep the WHOLE FILE (and ideally the whole surface class) for the same pattern before declaring the class closed — not just the line/test the finding cited. - **cousin**: [[LRN-077]] (pin grep, don't trust one instance), [[BDR-041]] (reconcile design: verify don't believe). +- **Status (2026-10-28, upgrade)**: superseded by LRN-164 ## LRN-107 — read-only subagent mandates must ban copying secret VALUES, not just mutations +- **Date**: — - **pattern**: job6 (2026-07-07), an explorer subagent under explicit no-execute/read-only mandate (LRN-105 class) copied the plaintext `MAGIC_API_KEY` value into its own scratch file while investigating the magic MCP config. Harness flagged it; main session redacted (1 occurrence, clean post-scan). The mandate said "don't mutate anything" — it never said "don't copy a secret's value into a NEW file you create", so a read-only agent still leaked a secret copy. - **why**: "read-only" naturally reads as "doesn't change existing state" — copying a value into a fresh scratch file isn't a mutation of anything that existed, so it doesn't trip that mental model, but it creates a brand new place the secret now lives (BDR-026's exact class: secrets have copies beyond the canonical store — tool configs, transcripts, caches, and now subagent scratch files too). - **context**: `.audit/job6-report.md` "Incident (contained)" section; explorer-C.md redacted post-incident; caught before job6's execution phase, contained to scratchpad only. - **future application**: any read-only/no-execute subagent mandate that touches config or env files must explicitly ban copying a secret's VALUE into agent output/scratch, not just ban editing/deleting. Phrase the mandate as "reference by name/location, never paste the value" — when auditing MCP/env config, prefer `jq 'del(.. | .env?)'`-style filtering (already BDR-026 practice) over raw `cat`. - **cousin**: [[BDR-026]] (secrets have copies, protect/audit them all), [[LRN-105]] (explorer no-execute mandate, the sibling rule this extends). +- **Status (2026-10-28, upgrade)**: superseded by LRN-165 --- ## LRN-108 — `claude mcp add --env KEY=value` writes the VALUE literally; use `${VAR}` unless you mean to +- **Date**: — - **pattern**: job7 (2026-07-07), root-cause of the recurring MAGIC_API_KEY leak: `claude mcp add magic --env API_KEY="$MAGIC_API_KEY"` (bash-expanded before the CLI ever sees it) writes the resolved plaintext string into `~/.claude.json`/`.mcp.json` — there is no `mcp add` flag that stores a reference instead. Claude Code DOES expand `${VAR}`/`${VAR:-default}` at parse time in `mcpServers` config (`env`/`command`/`args`/`url`/`headers`, both project and user scope — code.claude.com/docs/en/mcp.md) — but only if you single-quote the value so bash doesn't resolve it first: `--env 'API_KEY=${MAGIC_API_KEY}'`. Single vs. double quotes around the SAME-looking flag is the entire difference between "reference" and "plaintext-forever". - **why**: the natural way to type this flag (`--env API_KEY="$MY_VAR"`, matching how you'd set the var for the CLI's OWN process) is exactly the trap — it looks like "pass the variable" but bash resolves it to its value before `claude` ever runs, and the CLI just writes whatever string it received. Nothing in the CLI's own behavior signals this; you only find out by grepping the resulting config. @@ -1244,36 +1044,43 @@ rules: - **cousin**: [[BDR-026]] (canonical vault + copies), [[BDR-057]] (secrets-by-reference decision this trap motivated), [[LRN-107]] (same job family, don't-copy-the-value discipline). ## LRN-109 — `skills` CLI (vercel-labs/skills) fetches only `skillPath`, not sibling refs/scripts/templates +- **Date**: 2026-07-07 - **context**: job8 audit flagged darwin-skill NOT-CLEAN — SKILL.md references `references/*.md`, `scripts/*.mjs`, `templates/*.html`, all absent on disk. Traced to `~/.agents/.skill-lock.json`: `skillPath: "SKILL.md"` — installer fetched that ONE file, never the sibling dirs the skill text points to. Upstream repo (public clone, verified) had them all at the exact commit already recorded (`skillFolderHash` matches) — not drift, an installer-scope gap. - **future application**: any skill installed via `skills` CLI whose SKILL.md references relative paths needs a post-install check those paths exist on disk — `skillFolderHash` only hashes what WAS fetched, says nothing about what's missing. If absent: clone source repo at the recorded hash, copy full tree in, keep `.git` detached (cheap real pin, beats trusting the CLI's opaque hash alone). - **cousin**: [[BDR-058]] (this job's fix), darwin-skill's OVERSCOPED git-commit finding (job8 report — 3rd-party code, not patched, accepted risk under human-checkpoint gating, twin of [[LRN-105]]'s no-execute mandate for OUR read-only audits). ## LRN-110 — magic MCP `component_builder`'s local callback server = unauthenticated prompt-injection channel +- **Date**: 2026-07-07 - **context**: job8 audit read `dist/utils/callback-server.js:36` (+ `create-ui.js:35-38`) in installed `@21st-dev/magic` package. `21st_magic_component_builder` opens a plain HTTP server on `127.0.0.1:9221+`, `Access-Control-Allow-Origin: *`, no token/origin check, staying open up to 10 minutes per call. Any POST body to `/data` injected VERBATIM into tool result the model consumes — any local process or open browser tab on the machine can win the race against legitimate browser hand-back. - **future application**: this is in the third-party package's code, not our config — don't try to patch a vendored/npx-installed dependency. The only real lever is on OUR side of the boundary: never allowlist a tool with this shape, keep it `ask`-gated so a human sees every invocation (see [[BDR-059]]). Applies to any MCP tool whose implementation opens a listener to receive async results, not just this one — check the listener's auth/origin scoping when auditing MCP server code, the tool's *description* text tells you nothing about it. - **cousin**: [[BDR-059]] (the settings fix), [[LRN-111]] (why the allowlist stays empty), job8 report §2 surface 1 finding A#0. Magic MCP retired 2026-09-22 ([[BDR-093]]). ## LRN-111 — empty allowlist is a valid, deliberate posture when real usage is zero, not a leftover gap +- **Date**: 2026-07-07 - **context**: job8 census (grepping real `"name":"mcp__…"` tool_use blocks across `~/.claude/projects`, not text mentions) found ~910 mentions of `mcp__magic__*` but ZERO real invocations, ever. `permissions.allow`/`permissions.ask` had no `mcp__*` entries at all before this job — job6 flagged that as "ZERO scoping", easy to misread as an oversight to fix by adding an allowlist. - **future application**: before treating "no entry for tool X" as a gap needing an allowlist, check real usage first (grep tool_use blocks, not prose mentions). If usage is zero, pre-authorizing costs nothing to skip and buys nothing to add — the honest fix is making the ask-gate EXPLICIT (so it can't regress silently), not granting allow access nobody needs yet. Only add allow entries when real, measured, recurring usage justifies removing the friction. - **cousin**: [[BDR-059]], [[LRN-110]], [[LRN-088]] (same family: measure before assuming an absence is a defect). ## LRN-112 — nested subagent dispatch is supported (CC ≥ v2.1.172), not a flatten-to-1 no-op +- **Date**: 2026-07-08 - **context**: the whole job1-9 audit series ran on the premise *"Claude Code aplatit à 1 niveau → un design supposant 2 niveaux de sous-agents est cassé silencieusement."* job9 corrected it via `claude-code-guide` (official docs `code.claude.com/docs/en/agent-sdk/subagents.md`): a running subagent CAN spawn a further subagent IF `Agent` is in its `tools:` (omit it / add to `disallowedTools` to prevent nesting); hard cap **5 levels** ("a subagent 5 levels below main can't spawn further"); nesting **stabilized in v2.1.172** ("let subagents spawn their own subagents") — earlier versions did not support it at all. Live env confirmed **v2.1.203** (user). `claude --version` was unavailable in-sandbox so the report bracketed but could not pin it; the user pinned it. - **future application**: NEVER classify a subagent-dispatches-subagent design as "BROKEN" without checking the CC version. On ≥2.1.172 it works within the 5-level cap; on <2.1.172 it silently no-ops. The actionable finding is a VERSION-FLOOR ([[BDR-060]]) or a version-robust re-architecture (bundle→L1, [[BDR-061]]) — not "it's broken." When an agent must NOT nest, enforce it structurally: drop `Agent` from its `tools:` (done for seo/geo analyzers). Re-audit any prior job1-9 "nested = broken" finding through this lens. - **cousin**: [[BDR-060]] (version floor), [[BDR-061]] (path-b bundle pattern), [[LRN-057]] (subagent invocation idioms). ## LRN-113 — Partial-pattern-fix is the job1-9 series' recurring defect: grep the whole surface + guard it +- **Date**: 2026-07-08 - **pattern**: fix one cited instance of banned pattern, leave twins. Review found 4: trailer stripped from commit-changer only (A1, twins in bugfixer/feater/hotfixer); YAML quoted elsewhere but seo/security-auditor left broken (A4); attribution scrubbed on 3 skills but geo-analyzer missed (A5); gitleaks added to the hook generator but the installed hook not regenerated (A2). - **why it recurs**: the fixer greps for the reported line, fixes it, stops — never enumerates the pattern across the full surface. An adversarial review catches the twins later; nothing catches them at commit time. - **fix**: every pattern-fix ends with (1) whole-surface grep proving zero residue, (2) deterministic make-test guard that REDs if any occurrence returns. Shipped `lib/tests/run-review-guards.sh` — G1 trailer, G2 false attribution, G3 strict-YAML, G4 reconcile hermeticity, G5 hook-drift; teeth-verified (planted violation REDs). Check that would have caught A1/A4/A5/A2 at make-test time instead of review. - **future application**: any "fix pattern X" task → grep agents/ lib/ hooks/ templates/ skills/, add/extend review-guard with teeth. - **cousin**: [[LRN-114]] (hook-drift class), [[LRN-047]] (silent degradation → measure/guard). +- **Status (2026-10-28, upgrade)**: superseded by LRN-164 ## LRN-114 — Editing a hook generator does not touch the installed hook: reinstall + drift-guard +- **Date**: 2026-07-08 - **pattern**: job7 added gitleaks scan to `_gitflow_emit_pre_commit` (the GENERATOR), but installed `.githooks/pre-commit` is only (re)written by `gitflow init`/`install-hook`. job7 never re-installed → the repo's active hook stayed the pre-job7 version (620071b) for 8 days; `git commit` ran no secret scan while the team believed it did. - **why undetected**: T10 (drift test) compares only the hook's allow/block VERDICT, not content; T16 emits a FRESH hook in a throwaway repo, validating the generator, never the installed file. Both green while installed hook was stale. - **fix**: after editing any template-generated artifact, regenerate installed copy (`gitflow.sh install-hook`) AND add content-drift gate — `run-review-guards.sh` G5 diffs installed `.githooks/pre-commit` against `emit-hook`. @@ -1281,26 +1088,32 @@ rules: - **cousin**: [[LRN-113]] (partial-fix + guard), [[LRN-039]] (installers drift hand-curated config). ## LRN-115 — Analyzer Edit/Write grants are not dead capability: they write the report (false-positive) +- **Date**: 2026-07-08 - **pattern**: a contract audit flagged seo/geo/validator-analyzer holding `Edit`/`Write` while instructed "do NOT apply any Edit/Write" as a defense-in-depth defect. Verified FALSE: those grants write the agent's own REPORT (`.claude/audits/VALIDATE.md`/`SEO.md`/`GEO.md`). The "never edit" rule targets CODE files (the fix-bundle is applied by the dispatcher) and is instruction-level — identical in the patron. Removing Write would break report generation. - **why it matters**: don't "harden" a report-only agent by stripping Write — it needs it for its report. The code/report distinction is instruction-enforced, not tool-enforced, by design. - **future application**: before flagging a tool-grant as dead, check whether the agent uses it for its own output artifact (report), not the forbidden target (code). - **cousin**: [[BDR-061]] (analyzer bundle→L1 contract), [[LRN-113]]. ## LRN-116 — A resolved blocker's FIX can be missing from develop even when the entry backfills cleanly +- **Date**: 2026-07-08 - **pattern**: backfilling release/1.0.0 memory into develop, BLK-016 (rtk PATH-dead) was marked "resolved" via fix e58037c. Checked before backfilling: e58037c (the `~/.cargo/bin`→`~/.local/bin` bridge in install-plugins.sh) was NOT on develop — develop still installed rtk to a cargo bin dir the tool shell can't see → rtk compression was LIVE-broken on develop (~460K tokens/30d). The registry entry looked safe to copy; the underlying fix wasn't there. - **why it matters**: append-only registry backfill is "safe" only for the TEXT; a "resolved" status is a claim about CODE state that must be verified on the target branch, else you assert a resolution that isn't true. - **fix**: ported e58037c to develop (13-line idempotent bridge), THEN backfilled BLK-016 resolved. General: before backmerging a resolved blocker, grep the target for the fix's code signature. - **future application**: gitflow divergence review — enumerate release-only COMMITS that touch code, not just memory; a feature can be parallel-merged while its RC-branch fix is orphaned. - **cousin**: [[LRN-036]] (PATH profile drift), [[LRN-047]] (silent degradation). +- **Status (2026-10-28, upgrade)**: superseded by LRN-167 ## LRN-117 — A release/develop fork silently orphans functional CODE on develop, not just memory +- **Date**: 2026-07-08 - **pattern**: cutting release/1.0.0 and continuing on develop, the RC-branch bug fixes (find-skills drop `095d881`, make-update TTY guard `a1093ca`, rtk update-path version-guard `4c5e862`, rtk install bridge `e58037c`, SC1091 lint `e65796f`) landed ONLY on release. They were live-broken on develop for the whole fork duration (rtk compression dead, `make update` dies non-interactively). The review's memory back-merge caught the registry gaps and one code fix (rtk bridge); a full back-merge found ~5 more functional commits. - **why it hides**: registry-sequence gaps (missing LRN/BLK/EVAL ids) are easy to detect; orphaned CODE has no sequence to check. A feature can be parallel-merged to both branches while an RC-branch fix commit is never back-merged, and nothing flags it. - **fix**: at release-finish / in /reconcile, list `develop..release/*` commits touching functional files (exclude merges, `.claude/**`, version.txt/CHANGELOG) and present them for back-merge review. Advisory, NOT a hard make-test gate — cherry-picks land with new SHAs so the source commit stays in the range; automatic "already-ported?" equivalence is unreliable and would false-positive. Backlogged. - **future application**: any long-lived fork (release/*, long feature) — audit CODE divergence, not just declared/registry state ([[LRN-034]] narrated ≠ ground truth, applied to branches). - **cousin**: [[LRN-116]] (a resolved blocker's fix can be missing from develop), [[BDR-054]] (supersession-trace discipline). +- **Status (2026-10-28, upgrade)**: superseded by LRN-167 ## LRN-118 — Gitflow-conformity audit: "commits-code" vs "applies-but-defers-commit" is the line that sorts real findings from false positives +- **Date**: — - **pattern**: audited 52 units (33 skills + 19 agents) for gitflow conformity. Raw git-signal grep over-flags: `git add -A`, `gitflow finish`, `--no-verify` mostly appear inside PROHIBITION tables ("never …"), not usages — reading context killed every one (harden/web-validate `--no-verify` = bans; capitalize `git add -A` = ban; tour `gitflow finish` ×3 = red-flags). The decisive discriminator was NOT "does it write code?" but "does it autonomously `git commit`/`push`?": seo/geo/harden/web-validate/code-clean/refactor/doc all EDIT code/public-doc yet defer the commit to the human (or have NO `git commit` path at all) → safe by construction, gitflow layer N/A. Only 2 units both wrote AND committed without a branch precondition: commit-change (commits code, no aiguillage) and client-handover (autonomous `git push`). 0 MERGES-ALONE, 0 BYPASSES-HOOK. - **why it matters**: a conformity audit that classifies on "writes code" drowns in false positives; classify on "reaches an autonomous commit/push" and the surface collapses to the few units that can actually corrupt a branch. Thin-dispatcher skills (20-line SKILL.md → agent + commit lib) must be judged as skill+agent+lib triples — the discipline lives in the agent/lib (e.g. /doc's gitflow layer is in doc-syncer + doc-commit.sh, not SKILL.md). - **the net**: empirically the per-repo pre-commit hook BLOCKS a non-`.claude/` code commit on main/develop (exit 1), exempts `.claude/**`, allows working branches; `--no-verify` bypasses it client-side → Gitea server-side branch protection is the real backstop. So the 2 findings fail LOUD (hook), never corrupt develop — remediation = make them branch cleanly first (aiguillage / GO-gated push), not incident-urgent. @@ -1309,18 +1122,21 @@ rules: - **cousin**: [[LRN-117]] (orphaned CODE has no sequence to check), [[LRN-034]] (narrated ≠ ground truth), [[BDR-061]] (report-only agent tool-grants). ## LRN-119 — Fail-open engine contract for optional external data (real-if-connected, else graceful) +- **Date**: — - **pattern**: `lib/seo-data/fetch.sh` = one entrypoint; every subcmd ALWAYS emits JSON on stdout, exit 0 on ok/degraded, exit 2 on bad-usage, NEVER empty stdout, NEVER prints a secret. Third-party imports (google-auth, requests) function-local (lazy) so stdlib-only paths — mock (`SEO_DATA_MOCK_DIR`), degrade (no key/no account/revoked token), offline tests — run with no venv. Missing creds → `{"status":"degraded","reason":...}` and the caller (`/seo` analyzer) falls back to anonymous PageSpeed; audit NEVER fails on absent data. Both Python `_cli` wrapped try/except: SystemExit→bad_usage JSON+reraise, Exception→degraded JSON (corrupt store never leaks stack/path). 3rd status value `error` on exit-2 only. - **why it matters**: an optional-data integration must be invisible when unconfigured. Fail-CLOSED (crash/empty/nonzero) breaks every audit for users who never connect GSC. Fail-open + lazy-import keeps the 49 tests network-free and makes degrade a first-class tested branch, not an afterthought. - **future application**: any "use real data if credentials present, else degrade" seam — put the contract in the shell entrypoint (always-JSON / exit-code discipline), lazy-import the SDK, make degrade a returned status not an exception, test degrade+mock stdlib-only, redact secrets at the boundary (list omits token, `exec 2>/dev/null` unless debug). - **cousin**: [[BDR-063]] (the token store this fronts), [[LRN-120]] (SDD base gotcha, same build). ## LRN-120 — SDD final-review base = `git merge-base`, NOT the ledger's recorded BASE +- **Date**: — - **pattern**: subagent-driven-development ledger recorded `BASE: 24b47ce` — but that was IMPLEMENTATION start (after spec+plan commits), not the branch point from develop. `git merge-base develop HEAD` = `d3e644d` (real fork). Final whole-branch review diffed against recorded BASE = 881 ins / 59 del; against true merge-base = 2163 ins / 7 del — the recorded-base diff MISLEADING (netting against a divergent line → phantom deletions). Per-task reviews unaffected (each used the correct prior feature commit). - **why it matters**: the final review is the last gate before merge; a wrong base hides real changes or invents fake ones. The ledger BASE is a task resume-map, not a merge-delta anchor. - **future application**: for ANY whole-branch/final review, derive base from `git merge-base HEAD`, never a stored/remembered SHA. Sanity-check: does `git log BASE..HEAD` list ONLY this branch's commits, nothing foreign? Diff-stats differ between candidate bases → recorded one is stale, trust merge-base. - **cousin**: [[LRN-119]] (same GSC+CrUX build); SDD skill's own "never HEAD~1" warning (same base-selection bug class). ## LRN-121 — Shell allowlist validation: `grep -Eq` is fragile; use a whole-string POSIX `case` +- **Date**: — - **pattern**: guarding user-supplied label to shell-safe ASCII with `printf '%s' "$v" | grep -Eq '^[A-Za-z0-9._-]+$'` failed 3 adversarial gate passes: (1) command-injection framing (label interpolated into agent-composed Bash line); (2) parser differential — guard pre-scanned argv for literal `--label` while downstream `argparse` ALSO accepts `--label=v` and abbreviations (`--labe`, `allow_abbrev=True`), those forms reached parser unchecked; (3) `grep -q` matches PER LINE, label with embedded newline (`ok\nrm -rf`) passes on its FIRST line. Fix = replace the whole mechanism, don't patch again: `_label_safe() ( LC_ALL=C; case "$1" in ''|[!A-Za-z0-9]*|*[!A-Za-z0-9._-]*) exit 1;; esac )` — POSIX `case`, whole-string, C-locale subshell. No grep (no per-line), no regex, no second grammar to differ from; a newline is just a non-allowed byte caught by `*[!...]*`; `LC_ALL=C` stops UTF-8 collation widening `[A-Za-z0-9]` to homoglyphs (U+FF11, Kelvin U+212A). - **why it matters**: three distinct bypasses of the SAME guard = the approach was wrong, not each patch. `grep`'s line-orientation + locale-sensitive ranges, plus argv-prescan-vs-real-parser grammar drift, are the three classic ways an allowlist "passes" a string it shouldn't. Whole-string `case` in C locale closes all three at once. These were defense-in-depth (downstream used `"$2"`/`"$@"`/JSON-key, never `sh -c`/`eval` → not exploitable in the real exec chain) — but the backstop still took a categorical rewrite, and 3 security-gate BLOCKs to get there. - **future application**: validate shell input WHOLE-STRING (`case` or bash `[[ =~ ]]`), never `grep -q` (per-line). Set `LC_ALL=C` for byte-wise ranges. Argv pre-scan guard must be STRICTER than downstream parser (reject `=`-joined/abbrev) or validate post-parse against the value parser settled on. When a fix is bypassed twice → STOP patching, replace the mechanism (re-plan, not whack-a-mole). @@ -1329,6 +1145,7 @@ rules: --- ## LRN-122 — git mv + recreate source path in same commit = rename detection dead +- **Date**: — - **pattern**: rename file + create NEW file at old path in ONE commit → git never pairs the rename (source path never vanishes — index sees modify(old)+add(new)). `git log --follow` chain lost; deterministic, persists forever. Fix: TWO commits — pure rename first (paired at R~98%), recreation second. Found live: Task-2 implementer hit the plan's own "2 hunks" STOP gate, diagnosed root cause, escalated instead of patching around it. - **why**: contract criterion (history preserved) outranks plan packaging ("atomic commit"). Commit-level atomicity ≠ deploy-level atomicity — deployed symlink already fixed by running link.sh, independent of commit split. @@ -1338,6 +1155,7 @@ rules: --- ## LRN-123 — "resolves inside repo" symlink check green-lights stale link once old path re-occupied +- **Date**: — - **pattern**: doctor's check_symlink asserted only `readlink -f` lands inside `$REPO` — safe while ONE candidate file existed. Rename freed old path for a NEW file → stale post-pull link (`~/.claude/CLAUDE.md` → `$REPO/CLAUDE.md`) resolves to project file (inside repo) → check PASS, global doctrine silently absent every session. Fix: assert EXACT readlink target (`$REPO/CLAUDE.global.md`), warn + remedy cmd (`run: bash link.sh`). Caught by final whole-branch review (fresh most-capable model), not by any earlier gate. - **why**: containment predicates (inside-dir, prefix-match) silently weaken the moment layout gains a second valid-looking target; exactness costs nothing. @@ -1347,6 +1165,7 @@ rules: --- ## LRN-124 — derived scan artifacts don't belong in git; a tooling hint saying "safe to commit" manufactures the leak +- **Date**: — - **pattern**: gitleaks reports committed to repo (17bdd08) even with `--redact` = a MAP — secret type + file + line for anyone with repo access. Root cause traced: `make scan-secrets` echoed "already redacted — safe to inspect/commit" → the hint was obeyed. Fix: `git rm --cached` (gitignore has no effect on tracked files), reword hint to "gitignored — keep local, do NOT commit". Companion: user added `.audit/` gitignore rule (5842119) for the untracked report/patch siblings. - **why**: redaction removes VALUES, not INTELLIGENCE. And tool output is instruction — a hint that says "safe to commit" will eventually be obeyed by a human or an agent. @@ -1354,6 +1173,7 @@ rules: - **cousin**: [[BDR-057]] (secrets by reference, redact at capture), [[BDR-065]] (transient planning artifacts — same "process artifacts ≠ repo content" family), [[LRN-103]] (re-probe before acting). ## LRN-125 — don't make an agent dual-use across model tiers; route the audit consumer to a big-model agent, not the sonnet executor +- **Date**: — - **pattern**: splitting `code-cleaner` into a sonnet PHASE-2 executor broke its OTHER consumers (onboard STEP 6, tour Phase B) which dispatched it read-only AUDIT-only. Reflex "keep it dual-use (audit-only OR execute)" would have run an AUDIT on the sonnet-pinned executor = silent violation of the audit=big-model principle. Fix: reroute the audit consumers to a big-model agent (general-purpose/analyzer, inherits session), never the sonnet executor. - **why**: a dual-use agent inherits ONE pinned model. If its two uses sit on different tiers (audit=big, execution=sonnet), the pin silently mis-tiers one of them. hotfixer dual-use is fine because BOTH its uses are execution (same tier); code-cleaner's would have straddled tiers. @@ -1361,24 +1181,28 @@ rules: - **cousin**: [[BDR-066]] (model routing: reflection/audit big, execution sonnet), [[LRN-113]] (consumer-staleness sweep on a pattern fix). ## LRN-126 — splitting a monolith agent severs every IMPLICIT data path; forward each consumed field through the handoff contract +- **Date**: — - **pattern**: wave-4 split (client-handover-writer monolith → reflection parent + sonnet doc-writer child) silently dropped 2 inputs extracted STEPs consumed. `DEPLOY_HINTS` (detected in parent STEP 2, consumed by child STEP 14) + `--skip-seo` flag (parsed from `$ARGUMENTS`, gated child STEP 13) worked in the monolith by shared scope; after the split they were dead — never added to the PACKAGE. Child rendered a §8 without platform tailoring; `--skip-seo` became a silent no-op. Caught only by the opus whole-branch review, not the census. - **why**: monolith: `$ARGUMENTS`, detected vars, STEP-N side-outputs share one scope, later STEPs read them free. Split turns each free read into data path that MUST cross parent→child contract explicitly; every implicit read is a severed wire unless forwarded. - **future application**: splitting an agent: enumerate EVERY field child reads (grep child for `PACKAGE.`, bare var names, `$ARGUMENTS` flags), diff against what parent SETS before dispatch. Any child-consumed field the parent never populates = severed path = renders a hole or a silent no-op. A census that checks shape (model pin, gate-free) will NOT catch this — needs a data-flow read. - **cousin**: [[LRN-125]] (route consumer to right tier on a split), [[BDR-066]] (reflection/execution split), [[LRN-113]] (sweep ALL consumers). Distinct: 113/125 = WHICH agent/tier a consumer routes to; this = WHICH fields must cross the contract. ## LRN-127 — SDD implementers must not run destructive git ops on files outside their task scope +- **Date**: — - **pattern**: a wave-4 fix-subagent ran `git checkout -- settings.json`, believing the model-value diff was a "test side-effect." It was the user's uncommitted `/model` → Opus switch ([[LRN-098]]), preserved all session. The checkout DISCARDED it — settings.json reverted to committed `claude-fable-5[1m]`. Implementer had no task-reason to touch settings.json; it acted on a file outside its diff. - **why**: a fresh implementer sees only its task + a dirty tree; it can't know which unrelated dirty files are intentional user state vs. cruft. Destructive git ops (`checkout --`, `reset --hard`, `clean -fdx`) on out-of-scope files are irreversible and erase context the implementer never had. - **future application**: dispatch briefs for SDD implementers / fix-subagents MUST bar destructive git ops outside the named task files. If the tree is dirty with unrelated changes, leave them — flag to controller, never revert. Controller owns cross-file git state; the executor touches only its own paths. Pairs with [[LRN-125]]/[[LRN-126]] as the "executor stays in its lane" family. ## LRN-128 — a version RESET (backward bump) is editorial reflection, not the forward-only release-executor +- **Date**: — - **pattern**: first public release cut as v1.0.0 from internal 4.x lineage = backward version.txt (4.0.0→1.0.0) + CHANGELOG restructure (new public `[1.0.0]` on top, old 1.0-4.0 lineage under `## Pre-release (internal history)` banner) + tag swap (delete v4.0.0, tag v1.0.0). Sonnet `release-executor` (release-candidate skill's mechanical prep span) assumes FORWARD semver bump — its prep = `[Unreleased]`→`[X.Y.Z]` move + version increment. Cannot derive a backward reset, the CHANGELOG restructure, or the existing-`[1.0.0]`-collision handling. - **why**: a reset is a JUDGMENT act (what's public vs pre-release, how to frame the launch, what to do with the old lineage) = reflection tier, not the executor's mechanical forward move. - **future application**: version RESET or any non-standard release → do PREP MANUALLY inline (big model), use `gitflow.sh` only for branch mechanics (start/finish), KEEP skill's human gates (when-to-release, push). Don't dispatch the forward-only executor for it. [[BDR-067]] [[BDR-066]] ## LRN-129 — `git cherry` (patch-id) proves a stale/divergent branch has nothing orphaned before you delete it +- **Date**: — - **pattern**: a stale pushed `release/1.0.0` (abandoned July-4 prep) sat 227 commits behind develop. Before deleting it, `git cherry -v develop release/1.0.0` → `+` = unique by patch-id, `-` = equivalent patch already in develop. Content-checked each `+` (rtk PATH fix, drop-AI-attribution settings, find-skills drop, BLK-016/LRN-098/101, EVAL-015, features) → all present in develop → safe to delete, nothing orphaned. - **why**: `git rev-list develop..branch` counts by SHA — a feature merged into BOTH branches shows as "unique" (distinct merge commit) though its CONTENT is in develop. `git cherry` uses patch-id, so `-` = "same change already here". The `+` set still needs a CONTENT check (patch-id misses re-applied/squashed changes). @@ -1398,11 +1222,13 @@ rules: - **pattern**: statistic reaches a client only with ` — — measured: — `. `measured:` field catches the error. - **context**: "VSI (Visual Stability Index) — new 2026 Core Web Vital" lived in seo-analyzer as threshold, stated as fact. It does NOT exist — absent from the CrUX API metric list AND web.dev; 10 SEO blogs cross-cited it into apparent consensus, several falsely claiming CrUX already collected it. EVERY stat in agents/resources/ was real but grafted onto wrong subject: Aggarwal 40% = ALL methods (pinned on "add stats"); AccuraCast 58.9% = Person-schema PREVALENCE (pinned on QAPage lift, meaning inverted — FAQPage was 1.8%); LLMrefs 3x = brand-mentions-vs-backlinks (pinned on freshness decay). - **future**: failure mode is plausible RECOMBINATION — what a model half-remembering a search produces. Old rule "cross-check via WebSearch" LAUNDERS blog consensus instead of catching it. An API's metric list (e.g. developer.chrome.com/docs/crux) is decisive: a metric the API can't return is one you can't score. See [[LRN-132]] (same family, subagent summaries). +- **Status (2026-10-28, upgrade)**: superseded by LRN-168 ## LRN-132 — a subagent summary is a claim, not a fact — verify before planning on it — 2026-07-17 - **pattern**: relaying a subagent's characterisation without checking it propagates plausible-but-false. Treat every relayed finding as a claim to verify against a primary source or a live test. - **context**: 7 disproven in one seo/geo session — "Off-page has ZERO data" (brand mentions ARE gathered, STEP 6); "the stats drive axis weights" (weight tables carry no citations); "GSC Links API is available" (endpoint doesn't exist); "a SPA-severely-limited §0 flag compensates" (never existed); "X/Twitter returns 403" (returns 200, live-tested); Common Crawl "nearest free source" (17.3 GB dead end); the whole opening inventory that founded the 20-point plan. - **future**: I reproduced the SAME error 3× while WRITING the fixes (X/Twitter 403 in W3, the two above in I1/I6). Contact with the REAL corrected it every time — the sitemap, the repo, the curl, the primary doc — never re-reading the spec. Measure-first before building. Corroborates [[LRN-074]] (watch the RED go red). +- **Status (2026-10-28, upgrade)**: superseded by LRN-168 ## LRN-133 — an omission must stay legible, never silent — 2026-07-17 - **pattern**: when a tool cannot measure something, it says so IN its output — a caller must never read absence as "fine". @@ -1423,6 +1249,7 @@ rules: ~/.claude/settings.json is a SYMLINK to the repo settings.json; Claude Code hot-reloads settings on change → the config-protection PreToolUse hook's active/inactive state tracks the CURRENT branch's settings.json. On feature/drop-config-protection (hook deregistered) a protected edit passed silently, sentinel unconsumed; after gitflow-switch to a branch off develop (hook still registered) the SAME class of edit was blocked. Apply: a change that removes a settings-registered hook is live only on that branch until merged; use the one-shot sentinel for protected edits on any branch that still registers it. ([[BDR-074]] context.) ## LRN-137 — mode-based re-tiering beats file splits for mixed-tier agents +- **Date**: — - **pattern**: three planned agent splits (doc-syncer, handover-doc-writer, seo/geo analyzers) shipped as MODES + per-dispatch `model=` instead of new files; only plugin-probe justified a real new file (genuinely new role, no shared body). - **why**: a file split severs implicit data paths (LRN-126), relocates body-text test locks (seo-data fetch-wiring), breaks name/dispatch-string census locks, duplicates templates. A mode split keeps ALL locks and text in place; the dispatcher's gate sits BETWEEN mode dispatches; call-site `model=` precedence over the frontmatter pin is spike-proven (sonnet-pinned verifier ran haiku on override). - **fail-safe pin rule**: keep the HIGHEST tier as the frontmatter pin and override DOWN at call sites — a forgotten override then over-tiers (costs money) instead of silently downgrading judgment (costs correctness). @@ -1457,43 +1284,54 @@ Future application: any skill/plugin adoption — skills-external/, /plugin-chec ## LRN-142 — structure locks are fixed-string: reflowing a doctrine paragraph reds them (2026-08-24) Context: contract-gates ([[BDR-083]]). Editing lib/verify-secure-loop.md rewrapped 5 locked phrases across line breaks ("Max 3 conformity iterations", "Max 3 security iterations", "re-verify the REQUEST first", "always re-checked BEFORE security", "one verifier dispatch + one security dispatch") → loops-light.test.sh 30 pass / 5 fail, though ZERO doctrine was dropped. Locks did their job: they cannot distinguish "clause deleted" from "clause rewrapped", and that conservative bias is correct — the alternative (fuzzy matching) would miss real deletions. Rule: when editing a doctrine file under structure locks, grep the test's lock strings FIRST, then re-flow AROUND them — each locked phrase stays on one unbroken line. Fix the DOC, not the lock, unless the doctrine genuinely changed. Under locks today: verify-secure-loop.md, contract-interview.md, verifier / security-auditor / plan-challenger agents, seo+geo (71 locks). +- **Status (2026-10-28, upgrade)**: superseded by LRN-166 ## LRN-143 — pipe to head masks grep exit; `|| fallback` never fires +- **Date**: 2026-08-26 - **Context**: darwin 2026-08-26 — plugin-probe FRAMEWORK-DEPS (`grep … | head || echo none`) emitted silent-empty on no-match; same bug in run's own probe test. - **Pattern**: pipeline rc = LAST command's (head = 0 always). `|| fallback` after pipe = dead code. Bounded output → drop head; else `set -o pipefail` or capture + test. - **Future**: any skill/agent bash probe with a `||` fallback: check what the pipeline rc actually is first. ## LRN-144 — census locks grep EXACT single-line phrases; prose rewrap breaks them +- **Date**: — - **Context**: darwin 2026-08-26 — hotfix RULES rewrap split "No verifier is dispatched at hotfix weight"; loops-light.test.sh lock RED; make test caught post-edit. - **Pattern**: lib/tests/*.test.sh lock sentences verbatim, single-line. Rewording/rewrapping skill+agent md near locked phrases silently breaks census. - **Future**: before editing skill/agent prose, grep lib/tests/ for locks in the touched region; run make test BEFORE dispatching judges, not after. +- **Status (2026-10-28, upgrade)**: superseded by LRN-166 ## LRN-145 — hooks reach the terminal only via terminalSequence JSON field +- **Date**: — - **Context**: 2026-09-01 — attention bell for VS Code Remote-SSH (CLI on remote Linux). Hook subprocess has no controlling TTY; /dev/tty unreliable. Docs: terminalSequence = supported side-effect field, fires even on events that discard output. - **Pattern**: Notification hook → stdout JSON `{suppressOutput:true, terminalSequence:""}`. VS Code terminal ignores OSC 777/9 natively (claude-code #28338); client-side ext wenbopan.vscode-terminal-osc-notifier converts to native toast over Remote-SSH; beep needs accessibility.signals.terminalBell sound:on. permission_prompt fires ~6s late, idle_prompt ~60s. - **Future**: any hook ringing/notifying the terminal (bell, toast, title) — terminalSequence, never /dev/tty. Input-needed matcher set: permission_prompt|idle_prompt|agent_needs_input|elicitation_dialog|elicitation_url_dialog. ## LRN-146 — Notification event alone misses end-of-turn; Stop is the missing event +- **Date**: — - **Context**: 2026-09-03 — attention signal verified end-to-end after [[BLK-020]]. Matcher `permission_prompt|idle_prompt|agent_needs_input|elicitation_*` covers input-needed cases ONLY. "Claude finished speaking" has no notification_type — nearest was `idle_prompt`, ~60s late. Gap invisible until explicitly enumerated by user. - **Pattern**: wire SAME hook script on TWO events — `Notification` (matcher = input-needed set) + `Stop` (fires once per turn end, supports terminalSequence, no matcher). Script branches on `.hook_event_name` when `.message`/`.notification_type` absent: Stop → "Claude has finished responding", else default. Read stdin ONCE into var, jq the var (stdin not re-readable). - **Verified**: turn-end bip+toast OK, AskUserQuestion selector bip+toast OK. `permission_prompt` NOT exercisable under `defaultMode: auto` — ask-rules (`python3 -c *`, `curl`…) auto-approved, no prompt raised. Hooks hot-reloaded by file watcher, no restart. - **Future**: enumerate the events a signal must cover BEFORE wiring, one per user-visible moment. Notification ≠ lifecycle-complete. SubagentStop exists too for agent completion. ## LRN-147 — VS Code restores terminals BEFORE ext activation → toast dies every restart +- **Date**: — - **Context**: 2026-09-03, second hit same day. Bell OK, toast gone, after user re-attached session from a restored terminal. Probe on that pty: OSC 777 unique + OSC 777 repeated + OSC 9 → all three silent, while BEL rang. Same pty, bell works ⇒ bytes arrive, ext just not hooked to that terminal. - **Pattern**: `wenbopan.vscode-terminal-osc-notifier` instruments a terminal only if it exists AFTER ext activation. `terminal.integrated.enablePersistentSessions` (default true) restores terminals at window startup, i.e. BEFORE lazy ext activation → every restored terminal is permanently deaf to OSC. Recurs at each VS Code restart, silently, bell still ringing so it reads as "half broken". - **Fix**: client setting `"terminal.integrated.enablePersistentSessions": false` → no terminal pre-exists activation. Fallback without it: after VS Code start, open a FRESH terminal then `dtach -a ~/.dtach/` (dtach broadcasts, old client can stay or be closed, session never lost). - **Diagnostic shortcut**: bell rings + toast dead on the SAME pty = terminal-instrumentation fault, not audio, not hook, not server. Bell dead + toast alive = audio fault ([[BLK-020]] fault B). The two channels split the search space; check which one survives before anything else. - **Future**: any client-side terminal-parsing ext over Remote-SSH inherits this. Verify instrumentation on the ACTUAL attached pty after every restart, never assume yesterday's terminal. +- **Status (2026-10-28, upgrade)**: superseded by LRN-163 ## LRN-148 — terminal instrumentation is per-terminal + unpredictable; pre-flight test before attaching +- **Date**: — - **Refines**: [[LRN-147]] blamed restored-terminals-born-before-activation. Too narrow — counter-example same day: two terminals SAME VS Code window, pts/3 (born 01:58:33) instrumented, pts/7 (born 01:59:29, LATER) deaf. Ext is GLOBAL (marketplace: Enable/Disable pause parsing extension-wide, no per-terminal setting), shells identical on every server-side measurable: `VSCODE_INJECTION=1`, TERM, TERM_PROGRAM, same `--init-file` shell-integration path, ~2-3s between shell start and dtach. Trigger NOT identified. - **Pattern**: treat instrumentation as a per-terminal property that can silently fail for unknown reasons. Cheap pre-flight before committing a long-lived session to a terminal: `printf '\a\a\033]777;notify;NEUF;test\033\\'` typed IN that terminal. Toast → instrumented, attach. Bell only → deaf terminal, open another. Costs 5s, replaces an hour of pty archaeology. - **Recovery**: deaf terminal never repairs. Open fresh terminal, pre-flight it, `dtach -a ~/.dtach/`. dtach broadcasts, so old client may stay attached; session never at risk. - **Diagnostic split (holds)**: bell alive + toast dead = terminal instrumentation. Toast alive + bell dead = client audio ([[BLK-020]]). Neither = bytes never arrive. - **Future**: do NOT assert the born-before-activation cause as established — it fits the first incident, not the second. Unknown trigger is the honest state. +- **Status (2026-10-28, upgrade)**: superseded by LRN-163 ## LRN-149 — Stop hook payload carries background_tasks; use it to skip premature signals +- **Date**: — - **Context**: 2026-09-03. User: "notif à la création d'un sous-agent alors qu'il faudrait pas". Instrumented hook, ran probe subagents: NEITHER subagent creation NOR completion calls the hook. Only event = `Stop`, fired when the turn ends right after spawning. Signal was real but LIED ("Finished responding" while work continued). - **Pattern**: dump the real payload (`printf '%s' "$payload" >> file.jsonl`) instead of trusting docs — docs list Stop fields without `background_tasks`, the wire has it: `[{"id","type":"subagent","status":"running","description","agent_type"}]`. Rule: on Stop, `(.background_tasks // []) | length` > 0 → exit 0 silent. Next turn end signals for real. Interaction events (permission/question) always signal, background or not. - **Fail-open**: field absent (older client) → still signal. Missed notification worse than extra one. @@ -1666,232 +1504,288 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s - **Reference**: contract `2026-09-25-default-profile-full-1254` criterion 12; verifier + executor reports 2026-09-25. Links [[LRN-074]] [[BDR-101]]. ## LRN-172 — TF-IDF cosine on a 2-doc corpus is identically 0: similarity self-tests need N ≥ 4, a same-corpus positive control and a sensitivity re-run +- **Date**: 2026-09-27 - **Context**: A3 executor wrote a "distinct pair passes" fixture as a bare 2-doc corpus, documented the 0.00 as "the point being proven". Fresh verifier proved a near-duplicate pair also scores 0.00 at N=2: idf = log(N/df) = 0 for shared terms, unique terms never meet. Executor self-report "all markers printed" was true; the test was vacuous anyway. - **Fix shape**: one N=4 corpus: near-dup control 0.90 → FAIL, distinct pair 0.00 → silent, then swap one doc for a near-copy → 0.62 WARN appears. Marker printed only when all three hold. - **Apply**: any fixture for a corpus-normalised statistic asserts both directions in one corpus; "passes on a trivial corpus" proves nothing; markers prove the oracle, not the intent → keep the blind verifier ([[BDR-102]] [[EVAL-032]]). ## LRN-173 — contract oracles written from memory failed twice: run the CHECK on the precedent files first, census greps via `git grep`, `EVIDENCE: pending` mandatory +- **Date**: 2026-09-27 - **Context**: same run, two orchestrator oracle bugs. (1) "≤ 80 chars" over the whole file: rules/web-building.md line 2 (`paths:` frontmatter) is already 110 chars, so the criterion contradicted the precedent it named; executor returned NEED-DECISION instead of bending. (2) emil-citers census with `grep -rl` hit gitignored `install-*.log` at the repo root; `git grep -l` (tracked only) is the right census tool. (3) gates.sh `run` errors `runnable but has no EVIDENCE: line` unless each criterion carries `EVIDENCE: pending`. - **Apply**: before shipping a CHECK, run it against the files it claims to mirror; census oracles = `git grep`; contract skeleton carries `EVIDENCE: pending` per criterion (check /feat's template writes it). Oracle fixes are orchestrator-owned, never a re-dispatch ([[BDR-102]]). ## LRN-174 — a coverage census greps plugin data files too; a registry sample is not the catalog +- **Date**: 2026-09-28 - **Context**: I told the user Astro View Transitions had zero local mentions. ui-ux-pro-max's `data/stacks/astro.csv` rows 28-31 carry ClientRouter, `transition:name`, no-JS fallback; `motion.csv` carries GSAP pin/scrub, SplitText, parallax. My grep covered SKILL.md prose and archetypes, not the plugin's CSV search DB. Same day: the ui-skills registry showed 11 MengTo skills; the repo tree has 88 web-design skills, and the substantive ones were outside the sample. - **Apply**: census = `grep -rl` over the plugin cache including data dirs, then say "row in a search DB" vs "workflow"; evaluating an upstream = `git/trees?recursive=1` first, sample never. Correct the user the moment the miss is found ([[BDR-104]]). ## LRN-175 — the skill listing has a char budget; pruning under it buys routing, not context +- **Date**: 2026-09-28 - **Context**: 150 skills, 53.5k chars of descriptions, but the harness listed ~19k with a description and 78 name-only (profile, seo, tour, all ui-ux-pro-max, 14/15 superpowers, brightdata, synced). Budget ≈1 % of context (`SLASH_COMMAND_TOOL_CHAR_BUDGET`, community-documented), least-invoked skills lose theirs first. doctor.sh said 34 skills / 3.4k t: `find -maxdepth 2` without `-L` skipped every symlinked skill, `grep '^description:' | head -1` counted 0 for block scalars. - **Apply**: removing skills below the cap frees no context (the cap refills); the gain is descriptions back for kept skills + no accidental 50-100 KB broken body load (autoplan = 25k t to fail). Real context levers = session-start injections (superpowers 3.6 KB) and name-only lines. Measure with the census parser through symlinks ([[BDR-105]]). ## LRN-176 — a multi-line CHECK is silently truncated by gates.sh +- **Date**: 2026-09-28 - **Context**: four `CHECK: python3 - <<'PY' … PY` oracles parsed as one line each; the ledger validated (RUNNABLE 13/18), GATE 0 ran `python3 -` on an empty heredoc → rc 0, no marker → NOT-MET ×4 while every executor had self-checked green. Cause: `_set_attr` takes the rest of the `CHECK:` line only; the body lines are criterion prose. - **Apply**: one line per CHECK; anything longer lives in `.oracles/c.py` next to the contract (committed with it) and the CHECK calls the file. Follow-up: gates.sh could refuse a CHECK containing `<<`. Sibling of [[LRN-173]] (run the CHECK on precedent files first). ## LRN-177 — the gstack helper-tree class: one lib, no SKILL.md exposed, dst never a symlink +- **Date**: 2026-09-28 - **Context**: make-pdf MAKE_PDF_NOT_AVAILABLE, diagram BUNDLE_MISSING, careful/guard/freeze hooks exit 127, cso and plan-*-review unable to read `sections/` — all one class: skills hardcode `~/.claude/skills/gstack/`, link.sh (and two copies in install-plugins.sh / update-all.sh) linked only `bin` and `browse/dist`. Traps found by the challengers: gstack `./setup` plants `~/.claude/skills/gstack -> submodule` when absent (a helper writing into dst then nests links inside the submodule); `browser-skills/`, `openclaw/`, `node_modules/` are non-skill dirs holding nested SKILL.md (a whole-dir link would double-list skills); `profile.sh apply` only enables, `set`/`reset` park. - **Apply**: `lib/gstack-links.sh` is the single writer (skill dirs → children minus SKILL.md; non-skill dirs skipped when they hold a SKILL.md; `.git*`/`node_modules` by name; dst symlink removed, dst inside src refused); after a profile edit run `set full`, never `apply`; a gstack skill "failing" → check the census oracle first ([[BDR-105]]). ## LRN-178 — before a new top-level `source`, grep the fixture `cp` lists +- **Date**: 2026-09-28 - **Context**: twice in one day. E1b's `source gstack-removed.sh` in profile.sh/toggle-external.sh needed a `cp` line in three suites (profile-default, profile-set-managed, toggle-external-repo-resolution) — caught by the confirmation challenger, fixed in scope. My 21st helper plan would have added a second top-level `source` to toggle-external.sh with no fixture update → four suites red under `set -euo pipefail`; two challengers flagged it as BLOCKER, the helper was dropped. - **Apply**: `grep -n "cp .*lib/" lib/tests/*.sh` before adding a `source` to a lib; either widen every fixture copy in the same change or source lazily inside the one branch that needs it. Prefer the inline predicate when only one caller needs the new semantics ([[BDR-105]]). ## LRN-179 — skill `effort:` shifts the main loop for the rest of the turn, interactive only +- **Date**: 2026-09-28 - **Context**: effort-tiering spike 2026-09-28, Claude Code 2.1.283, Fable 5.1. Probes = `$CLAUDE_EFFORT` in Bash + transcript `effort` field per request. User-typed `/probe-low` → whole turn `low`. Skill-tool load in interactive session → `max` then `xhigh`, last loaded wins, both directions; first request after the switch read 206,996 cached tokens, wrote 1,164 (cache kept). Three `-p` runs: neither `effort:` nor `model:` skill frontmatter applied via Skill tool. Agent pin honoured (impeccable `medium`), unpinned built-in on sonnet inherited `xhigh`. Docs agent claimed "ultrathink keyword does not exist": wrong, docs = in-context nudge, API effort unchanged. Harness claims get verified against the harness ([[LRN-046]]). - **Apply**: main-loop effort per phase = `Skill(effort-)` on the main loop, never inside a dispatched agent; headless runs stay at session level; keep `CLAUDE_CODE_EFFORT_LEVEL` unset (beats every frontmatter). Spec `docs/superpowers/specs/2026-09-28-effort-tiering-design.md`. ## LRN-180 — Skill-tool effort override needs a paired tool call; a lone Skill call is a no-op (2.1.283) +- **Date**: 2026-09-28 - **Context**: effort-tiering smoke. Six lone `Skill(effort-*)` / probe loads left `$CLAUDE_EFFORT` unchanged; every load issued in the same assistant message as another tool call applied, and the paired Bash already saw the new level. Re-loading an already-loaded shifter re-applies (text deduped: "already loaded above"). Final review: `brainstorming` / `writing-plans` loaded alone by ship-feature and init-project → their vendored xhigh pin inert. Amends [[LRN-179]]. - **Apply**: `Skill(effort-)` always travels with the step's first tool call, shift first; pair a downward shift with a pinned executor or a Read/Bash, never with a built-in judgment dispatch; before any built-in judgment dispatch, pair the own-level shift with it; skills Claude loads alone do not apply their pin → re-assert with a paired shift at the resumed planning step ([[BDR-107]]). ## LRN-181 — Stacked skills share one effort level; a lone load applies none +- **Date**: 2026-09-29 - **Context**: design toolchain loads 5-8 skills in one build. Skill `effort:` frontmatter = last loaded wins, both directions ([[LRN-179]]). Two levels inside the stack → effort depends on load order, invisible. Plus [[LRN-180]]: a Skill call Claude issues alone is a no-op. - **Apply**: one level per stack (`lib/effort-pins.txt` design section, census `stack_levels` lock, site-motion frontmatter matches); doctrine "load the stack paired with the first Read of the target file"; new vendored design skill → copy the stack level. [[BDR-108]] ## LRN-182 — Effort baselines are generation-bound; model aliases move silently +- **Date**: 2026-09-29 - **Context**: transcripts of the last weeks show `sonnet` → claude-sonnet-5 (3069 msgs) then claude-sonnet-5-5 (recent), `opus` → opus-5 then opus-5-5, `fable` → fable-5 then fable-5-1. API reference: Sonnet 5.5 recalibrated effort levels ("start at medium for agentic coding"). [[EVAL-036]] A/B ran on one generation. - **Apply**: after an alias moves (new model in a tier) re-run `python3 lib/effort-audit.py` and re-read the pins; write the generation next to any effort figure; keep aliases (latest = cheapest or same price, never pin a version for a measurement). [[BDR-108]] ## LRN-183 — npm CLI with a vendored binary: probe it, `command -v` proves only the shim +- **Date**: 2026-09-30 - **Context**: `@higgsfield/cli` ships `bin/*.js` + `postinstall: node install.js` that downloads `vendor/hf`. npm 11.19 prints "install scripts not yet covered by allowScripts" and may hold the script back (`ignore-scripts`, `allow-scripts` policy), at first install and at any `npm install -g` update. Shim then exits 1 "binary not found". First plan gated on `command -v higgsfield`: installer said "already installed", doctor passed, toggle blamed the session. Three challenge lenses flagged it. - **Apply**: presence check = a real subcommand (` version`), silent, bounded, used in install gate, after every update, doctor, toggle hints; remedy line names `npm install -g --allow-scripts= `. [[BDR-109]] ## LRN-184 — Pack membership on an unpinned upstream: allowlist, never "all except X" +- **Date**: 2026-09-30 - **Context**: first `higgsfield_skills()` globbed `skills-external/higgsfield-*` minus `higgsfield-websites`. Upstream tracks main: a renamed `higgsfield-website` or a new deploy skill would be linked by the next `enable higgsfield`, which the routing line runs on every media ask. Breaks "websites on named ask only" and the house rule allowlist over denylist. - **Apply**: `HIGGSFIELD_MEDIA_SKILLS` array; unlisted synced skills reported by `pack_hints`, never linked; hints run on the already-enabled path too, else drift is silent in the steady state (final review finding). Same shape for any future pack tracked at main. [[BDR-109]] ## LRN-185 — `[ -t 1 ]` is dead under `exec > >(tee)`: interactive offers test stdin alone +- **Date**: 2026-09-30 - **Context**: install-plugins.sh:22 `exec > >(tee -a "$LOG_FILE") 2>&1`. ctx7 (Step 6) and 21st (Step 8.7) login offers required `[ -t 0 ] && [ -t 1 ]` → never shown in a normal run since they were written; install logs always took the "not signed in" branch. Found by the read-before analyzer. update-all.sh:75 already tested stdin alone. - **Apply**: in a script that redirects stdout to a pipe, gate prompts on `[ -t 0 ]`; lock it (`INSTALL_WIRING`: no `-t 1`, ≥3 `[ -t 0 ]`, positive control). [[BDR-109]] ## LRN-186 — `GIT_TERMINAL_PROMPT=0` alone does not stop a credential prompt +- **Date**: 2026-09-30 - **Context**: confirmation challenger: git asks GIT_ASKPASS → core.askPass → SSH_ASKPASS → terminal; the env var disables only the last. VS Code terminals export `GIT_ASKPASS=…/askpass.sh` → clone of a deleted/private GitHub repo opens an input box, installer hangs. Tried live against a missing repo: `GIT_TERMINAL_PROMPT=0 GIT_ASKPASS='' SSH_ASKPASS='' git -c credential.helper= -c core.askPass= clone … /dev/null` keeps the race. - **Apply**: producer out of the pipeline. Tests: `grep -q PAT < <(cmd)`. Prod: call inside the condition `if grep -q PAT <<<"$(cmd 2>&1)"` (a bare `out=$(cmd)` aborts under `set -e` when the function runs bare). `printf '%s' "$v" | grep -q` safe (builtin, one write). Same class: `| head -1`, awk `{print; exit}`. Not decidable by text census → structural fix, no `grep -q` lint rule. [[BDR-110]] ## LRN-190 — Oracle hygiene: wrapped lines, baselines, no rm -rf via variable +- **Date**: 2026-10-06 - **Context**: GATE 0 criterion 4 NOT-MET while code correct: executor wrapped `grep -q … \` + `<<<"$(…)"` at 80 cols (my own style rule), single-line regex missed it. Criterion 7 `shellcheck` bare would fail on pre-existing info notes outside Health Stack scope. Criterion 2 CHECK held `rm -rf "$d"` (destructive-tools rule), executor's copy refused by permission system. - **Apply**: join continuations first (`sed -e ':a' -e 'N' -e '$!ba' -e 's/\\\n[[:space:]]*/ /g'`); lint criteria compare counts against base ref (`git show base:file | shellcheck -`); planted fixtures cleaned with `rm -f file; rmdir dir`. Oracle edits after a red floor logged in CLARIFICATIONS as "oracle maintenance", criterion text never loosened. Extends [[LRN-188]]. ## LRN-191 — `cmd | grep -q` under pipefail reintroduced one commit after BDR-110 banned it +- **Date**: 2026-10-06 - **Context**: feater wrote T18j as `git log develop --format=%s | grep -q …` in a `set -uo pipefail` suite. Green alone ×3, red once under load (3 suites + agents in parallel): `grep -q` exits early → SIGPIPE on `git log` → rc 141 → `&&` chain fails. Demo: `seq 1 200000 | grep -q 1` fails 300/300 under pipefail, `grep -q 1 < <(seq …)` 0/300. - **Apply**: [[BDR-110]] form `grep -q PAT < <(cmd)` in tests, `<<<"$(cmd)"` in prod. Census can't catch it by text (BDR-110 chose no rule) → executor brief + verifier lens must name it: "no multi-line producer piped into `grep -q`". A flake seen ONCE under load is a bug, not noise: reproduce the mechanism before calling it flaky. Single-write `printf '%s' "$v" | grep -q` is safe. ## LRN-192 — Turning auto-push off re-arms `git branch -d`'s upstream check (LRN-161 inverted) +- **Date**: 2026-10-06 - **Context**: [[LRN-161]]: auto-push kept upstream in sync → `-d` a no-op guard. Manual-push mode: upstream lags → `-d` REFUSES a branch merged into HEAD ("not yet merged to origin/
") → `finish` merges then rc 5 false "unmerged". First fix `--unset-upstream` then `-d` regressed T22j (hotfix merged into main only, HEAD=develop → `-d` refuses). - **Apply**: after the explicit ancestor gate, checkout the base that CONTAINS the branch (`merge-base --is-ancestor br develop` ? develop : main), `--unset-upstream`, then `-d`. Any change to push/upstream config → re-read every `-d`, `--ff-only`, `@{u}` site AND the tests that assume upstream in sync (T22j class). Tests: gitflow-test T18k, T22j. ## LRN-193 — A revised plan gets a fresh challenger, not a re-read: r2 found 3 BLOCKERs inside r1's fixes +- **Date**: 2026-10-06 - **Context**: manual-push-mode plan. r1 (3 lenses) → 2 MAJOR, I rewrote 5 checklist items. Confirmation pass (1 fresh correctness challenger on the REVISED file) → FATAL(4): my `--unset-upstream` fix broke T22j; my T18l fixture never set develop's upstream (`push` without `-u`, init creates develop untracked); my T18n/T18l order made offline silence vacuous. All three were in text I had just written and re-read. - **Apply**: `challenge-plan.md` "re-challenge once if materially changed" is load-bearing, never skip it to save a dispatch. Brief the confirmation challenger on the NEW mechanics explicitly (state machine of new tests, fixture preconditions, ordering). Fixes to tests need the same fixture trace as the code (`-u`, upstream, what an earlier test leaves behind). ## LRN-194 — Permission globs: trailing ` *` matches end-of-string; a denied token poisons every command that names it +- **Date**: 2026-10-07 - **Context**: push-guard deny widening. Planned `Bash(git *config *gitflow.* *)` to deny writes (key + value) and spare the bare read for run C. Evidence: `git config --local core.hooksPath` (no value) is denied by `Bash(git config --local core.hooksPath *)` → ` *` also matches end. Second effect: once `Bash(*GIT_CONFIG_COUNT*)` style rules landed (settings.json symlinked = live), a contract CHECK, a grep and a commit message naming the tokens would all be denied — including the oracle meant to verify the rules. - **Apply**: (a) an infix/suffix glob cannot carve out a read of a denied key → give consumers a sanctioned reader (lib verb) instead; (b) a leading-`*` deny on a token makes the token unspeakable in command text → assertions about it live in test FILES (`make test`), never in CHECK commands, grep one-liners or commit subjects; (c) simplify: `Bash(git *config *gitflow.*)` already covers value writes, `--unset`, `--bool` forms. Links [[BDR-112]], [[BDR-100]]. ## LRN-195 — BSD sed: `N` on the last line quits without printing → the `:a;N;$!ba` fold returns EMPTY on single-line input +- **Date**: 2026-10-07 - **Context**: push-guard plan folded `\`-newline with `sed -e ':a' -e 'N' -e '$!ba' -e 's/\\\n[[:space:]]*/ /g'` (the [[LRN-190]] idiom, written on GNU). `/usr/bin/sed` on macOS is BSD: `printf 'git push' | sed …` prints NOTHING. Every single-line command would have read as empty → guard dead in production, while a 2-line test passed. Caught by the confirmation challenger, not by tests. - **Apply**: fold in bash (`one=${cmd//$'\\\n'/ }; one=${one//$'\n'/ }`) or `sed -e ':a' -e '$!N' -e '$!ba'`. Add a single-line positive control to any multi-line normaliser test. [[BDR-110]] census can't catch it (structural, not textual). Links [[LRN-190]], [[BDR-112]]. ## LRN-196 — A fail-closed Claude Code hook: trap must `exit 0`, cap attacker-sized loops, read git's rc not its value +- **Date**: 2026-10-07 - **Context**: push-guard hardening (security gate, 3 MEDIUM). (1) EXIT trap printed the static deny but kept the non-zero rc → Claude Code parses hook JSON only on exit 0 → deny ignored = allow. (2) Each literal `cd`/`-C` token cost a subshell + 3 git execs: 600 tokens = 12 s > 10 s hook timeout → timeout = non-blocking = allow. (3) `git config --bool --default true` returns empty on git absent / old git / unreadable dir → read as "auto" → allow. - **Apply**: `trap '… ; exit 0' EXIT`; deny path `out=$(jq …) || out=$STATIC; printf '%s' "$out"`; dedup (`sort -u`) + hard cap on command-controlled token counts, deny above the cap BEFORE any fork; distinguish `git config` rc 0/1/other (value / unset / failure → deny); record "decided" only after ≥1 clean evaluation. Lock each with a test (shim PATH without a tool, 25-token flood, chmod 000 dir with SKIP path). Measure the flood after the fix (20 000 tokens → 0.15 s). Links [[BDR-112]], [[BDR-087]], [[LRN-160]]. ## LRN-197 — A skill's own `git push` after a lib finish or a hook-pushed commit is redundant since BDR-095: delete it, don't gate it +- **Date**: 2026-10-07 - **Context**: `/close` STEP 5C ran `gitflow finish` then `git push origin develop` (added 2026-07-16); the lib push landed 2026-09-22 and 5C was never revisited. `/client-handover` asked "Push to origin now?" after commit-change, whose commits the post-commit hook had already pushed. Both runs' first plan GATED the push on the mode; the simplicity lens found both pushes redundant. - **Apply**: before gating an action, ask whether it still does anything. Grep every `git push` in skills/agents after any change to hooks/lib push behaviour (BDR-100 surface rule); replace a redundant push + its question by a FACT read afterwards (`git rev-list --count origin/
..
`) and a user hint. Links [[BDR-113]], [[BDR-095]], [[LRN-113]]. ## LRN-198 — Text read from git and pasted into a later Bash call is an injection sink: allowlist before interpolating +- **Date**: 2026-10-07 - **Context**: C2 replaced one Bash block (`CURRENT_BRANCH=$(git branch --show-current); git push origin "$CURRENT_BRANCH"`, quoted variable, safe) by three separate calls where the branch name is pasted as text into `git rev-list --count origin/
..
` and into `! git push -u origin
`. `git check-ref-format --branch 'x$(id)y'` rc 0: a hostile branch (PR checkout, crafted remote) runs its payload. Security gate BLOCK(1). - **Apply**: any name an agent READS (branch, tag, path from repo state) and later WRITES into command text must pass an allowlist first (`^[A-Za-z0-9._/][A-Za-z0-9._/-]*$`; leading `-` excluded = option injection); on mismatch interpolate nothing and say so. Prefer a quoted shell variable inside ONE call when the flow allows; when prose branching forces multi-call, the allowlist replaces the quotes. `` from user args: same class, lower trust gap. Links [[BDR-113]], [[LRN-196]]. ## LRN-199 — Agent-level branching is prose on a printed word: shell state dies between Bash calls, and a text guard denies the whole call +- **Date**: 2026-10-07 - **Context**: plan wrote `mode=$(gitflow.sh push-mode)` then `[ "$mode" = auto ] && git push origin develop`. Two failures: (a) separate calls → `$mode` empty → silent skip, rc 1 misread as "push FAILED"; (b) one call → push-guard's STRICT regex matches `&& git push origin` in the TEXT and denies the WHOLE call, so even `finish` never runs. Three lenses hit it independently. - **Apply**: a skill reads a word from a command's visible stdout, then branches in PROSE ("printed `auto` → run X as its own call; anything else → never issue X"). Never a shell variable across calls, never a conditional that contains a guarded token. Any text-only PreToolUse guard turns `cmd-you-wanted-to-avoid` inside a conditional into a denial of the surrounding command. Links [[BDR-112]], [[BDR-113]], [[LRN-191]]. ## LRN-200 — `install-hook` and `global-hooks` write git config as a side effect; only `emit-hook > file` regenerates hooks config-free +- **Date**: 2026-10-07 - **Context**: D1 planned `install-hook` (= write hooks + a LOCAL hooks-path entry this repo must not gain: it runs on the global hooks) then `global-hooks ` ("returns before any write because the global value already matches"). The confirmation challenger read `~/.gitconfig`: rewritten 2 min earlier by the user's dotfiles installer (`@USER@` placeholders, no hooks path) → `global-hooks` WOULD have written the global config through a lib call, and `md5 .git/config` could not see it. User confirmed (own machine setup) and restored from the installer's backup; commits waited. - **Apply**: regenerate generated hooks with `bash lib/gitflow.sh emit-hook > /` (no config read/write, mode preserved); never `install-hook`/`global-hooks` from a flow. Evidence = md5 of `.git/config` AND a Read of `~/.gitconfig` before/after. Before any commit, check `git var GIT_COMMITTER_IDENT` is not a placeholder: an external installer can rewrite dotfiles mid-session. Links [[BDR-114]], [[LRN-114]], [[BLK-027]]. ## LRN-201 — A flood cap must run before ANY per-token fork; a reorder reopened the timeout fail-open and only a timed 2 000-token test catches it +- **Date**: 2026-10-07 - **Context**: run B put the 20-token cap before resolution (20k tokens 0.15 s). D2 added `classify_tok` (one subshell + sed per token) and the executor ran it BEFORE the cap: 1,600 tokens = 13 s > the 10 s hook timeout = allow. Verifier CONFORME (suite max 21 tokens), security re-scan BLOCK(1). Fix: `arg_tokens | sort -u | grep -c .` then `> 20` deny, then classification on ≤20 survivors; T58 = 2,000 tokens, deny, `$SECONDS` < 5. - **Apply**: in any guard, order = count → cap → everything else; a cap without a timed flood test in the suite is a comment, not a guard. Re-measure the flood after every change to the token pipeline (security gate did: 0.13 s at 20k). Links [[BDR-114]], [[LRN-196]], [[LRN-104]]. ## LRN-202 — Reading a stderr-then-stdout verb from a hook: `out=$(cmd 2>&1)`, last line = word, prefix line = reason; no temp file; lib path absolute before any cd +- **Date**: 2026-10-07 - **Context**: unpushed-guard plan used `2>"${TMPDIR:-/tmp}/x.$$"` + cat + rm: fail-OPEN when TMPDIR is full (`|| mode=auto`), predictable path, symlink-followable on shared /tmp, leaked on kill; `mode=$(cmd 2>&1 >/dev/null)` captures ONLY stderr. push-guard's `mktemp` variant added `set -u` trap hazards. The verb writes its stderr line BEFORE its stdout word in one process, so `${out##*$'\n'}` is the word and the `gitflow.sh push-mode:` line is the reason (select by prefix, not `head -1`: a bash startup warning could precede it). Resolve the lib path to an absolute one BEFORE the hook's `cd "$cwd"` (a relative invocation otherwise resolves into the target repo). - **Apply**: hooks never touch temp files for a one-line capture; anything but the expected word is treated as the fail-closed state, never as the default. Links [[BDR-114]], [[LRN-196]], [[LRN-199]]. ## LRN-203 — Mod hooks: model ALIAS set by a hook resolves through stale table (`sonnet` → `claude-sonnet-5`, 404); write full ids; oracle = transcript fields, not `CLAUDE_EFFORT` +- **Date**: 2026-10-08 - **Context**: model-router spike 2026-10-08, CLI 2.1.294. `agent.spawn` or `tool.call Agent` param rewrite with alias `sonnet` → API got `claude-sonnet-5`, HTTP 404 model_not_found. Same alias passed by the model in the Agent tool param → `claude-sonnet-5-5`, fine. Full id `claude-sonnet-5-5` from hook → fine, every step answered by 5-5. Agent tool schema enum refuses full ids, so full ids reach API only via hooks. Effort rewrite at `turn.step` proven by transcript record field `effort` (high → medium); `CLAUDE_EFFORT` env + `perTurnEffort` stay at turn setting, blind to per-request rewrite. - **Apply**: any mod that sets a model carries its own alias → full-id table (one place to bump per tier release). Verify routing with transcript `message.model` + record `effort`, never env vars. Links [[BDR-108]] (aliases as pins: still right at the Agent-tool call site, wrong inside hooks), [[BLK-029]]. ## LRN-204 — Main-loop model switch mid-turn works, costs one cold-cache step on the full context per switch INTO a model; return free (per-model cache, 1 h TTL) +- **Date**: 2026-10-08 - **Context**: spike 2026-10-08, fable → `claude-sonnet-5-5`/low for 3 steps on ~260k context, then back. Conversation intact (tools, results, thinking blocks from another model in history: no error). First sonnet step cache_read 0 (full 260k billed), next steps 237k cached; return to fable step read 263k cached. - **Apply**: switch the main loop only for spans long enough to amortize one uncached read of the whole context (many mechanical steps), never per tool call; short mechanical work → small-context haiku sub-agent. Haiku 4.5 window 200k: a long main loop cannot go to haiku at all. Flag off by default in model-router. Links [[LRN-203]], [[BDR-107]]. ## LRN-205 — A hook answering `tool.call` in place of a built-in tool must return that tool's OUTPUT schema shape; a string result is refused and the tool runs anyway +- **Date**: 2026-10-08 - **Context**: model-router Skill bridge, plan r1: `{ result: '' }` for `Skill(effort-*)`. Challenger: Skill has output schema `{ success, commandName, status?, … }` (claude-code-tools index.d.ts ~5139); core validates a hook's answer against it (claude-code index.d.ts ~12641), wrong shape = hook skipped = skill loads = the exact doublon the bridge exists to remove. Fix: `{ result: { success: true, commandName: e.skill, status: 'inline' }, context: ['…'] }`; text for the model goes in `context`, never in `result`. - **Apply**: before answering any `tool.call` without `next`, grep the tool's RESULT type in claude-code-tools and mirror it; put model-facing prose in `context`. Links [[BDR-115]], [[LRN-203]]. ## LRN-206 — `claude plugin test` kit facts (2.1.294): nothing fires at load, inputs are the FULL event, a bottom hook is mandatory under every `next`, `turn.step` streams +- **Date**: 2026-10-08 - **Context**: model-router tests. Kit `$` is `EngineCall = (e: Args)`: `command.run` needs `origin` + `presentation`, `prompt.submit` needs `wait` + `origin`, `agent.spawn` needs `tool_use_id, description, provider, parentModel, background, fork`; the test file is type-checked with the hooks (tsc include). `session.start` does NOT fire at load → every test boots with a bottom `on('session.start')` + `$.session.start({ cwd, surface: null, isInteractive: false })`. A hook calling `next` hits the kit's bottom which throws unless the test registered one (`on('agent.spawn', ($, e) => ({ model: e.model, agentId: 'a1' }))`). `$.turn.step` returns a stream: drain with `for await` then await `.result` (awaiting `.result` alone runs no hook). No fs/network/process: defaults path only. Assert on the ONE line that carries the value (a `show()` listing every phase always contains every id and level). - **Apply**: write the boot helper first, type every input from the declarations, never relax a test to dodge a type. Links [[BDR-115]]. ## LRN-207 — Model availability = typed API errors (`classic.StopFailure` rate_limit|overloaded|billing_error|model_not_found) + `PostModelSwitch auto`; never the turn-end reason, never `rateLimits`; sticky state and breaker target = two fields +- **Date**: 2026-10-09 - **Context**: model-router W1-C. `turn.complete reason: error` covers context-limit and network errors → a breaker fed by it marked fable down 15 min on a context overflow (challenge r1). `rateLimits` kinds are account windows (five_hour, seven_day, spend_limit), not per model. A per-step "engine fallback detection" (`e.model` ≠ `$.session.model()`) re-marked the session model at EVERY step → backoff climbed to the 5 h cap in one turn (confirmation r2). One field used both as sticky cur and as breaker target contradicted itself (reset at turn end vs kept). - **Apply**: feed a breaker only from typed error kinds that name unavailability; mark per EPISODE (idempotent while down), backoff 15→300 min, `model_not_found` until reload; a user `/model` clears, `/clear` keeps (account-wide). Keep `turnModel` (sticky, reset per turn) and `lastPlan` (breaker target, kept) separate; unrouted steps pass `e.model` verbatim so the engine's own fallback is respected. Links [[BDR-115]], [[LRN-204]]. ## LRN-208 — Security-auditor brief = scope only; iteration history and claimed closures violate the blind-scan contract +- **Date**: 2026-10-09 - **Context**: W1-C gate 2026-10-09. I sent "previous PASS with 6 MEDIUM, closed: …" in the brief. Auditor: "The auditor contract says that is never sent and must be ignored … Please do not send it next time" (it scanned blind anyway). Same rule as the verifier (lib/verify-secure-loop.md: fresh, no history). - **Apply**: SCOPE + a neutral CONTEXT of what the code does; never prior verdicts, closures or accepted residuals. Residuals live in TODO, the auditor rediscovers them (that is the point). Links [[LRN-083]]. ## LRN-209 — Scope the test run to the diff; one full `make test` before the merge; `make test` now names the red suite; GNU make rc 2 on a failed recipe +- **Date**: 2026-10-09 - **Context**: 2026-10-09 the pre-merge check took 454 s = full `make test` (48 suites) + a per-suite re-run to NAME the red one (aggregate rc, permanent env red design-tool-gate). Three more full passes earlier that day for mods/-only diffs. Hotfix efdd491: the recipe prints `FAIL ` + `all suites green` / ` suite(s) red: …`. My oracle expected rc 1; GNU make returns 2 when a recipe line fails. - **Apply**: a diff confined to one component runs that component's suite + the doctrine census; the full suite runs ONCE before `gitflow finish`; read the FAIL lines, never re-run per suite. Oracles on `make` test `[ $rc -ne 0 ]`, not `-eq 1`. Links [[LRN-173]]. ## LRN-210 — One coverage clause per contract criterion; a compound "covered by kit tests" criterion yields ECARTS forever with zero defects +- **Date**: 2026-10-10 - **Context**: W2-A contract criterion 3 bundled ~12 clauses under one "Covered by kit tests". Three fresh verifiers: ECARTS(3), (1), (1), each a NEW untested guard, code judged correct 3×. Cap hit, diagnosis at max, user accepted. 4 feater rounds added 30 tests (58 → 88), every one mutation-proven. - **Apply**: split coverage criteria: one clause = one criterion with its own test name; or make the oracle a mutation script (`CHECK:` flips the guard, expects a red test). Verifier reads clauses literally: write only what one test can prove. Links [[LRN-209]], [[EVAL-042]]. ## LRN-211 — Typed-slash routing: name-bound marker + idle fallback; run slot separate from turn routes; engine records are the live oracle +- **Date**: 2026-10-10 - **Context**: mod needs "user typed /feat" from `skill.prompt`, which carries no origin. `prompt.submit` sees the raw `/name` first (composer|sdk|bridge): store the NAME (not a boolean; a bare flag leaked to the next preload), pending slot when mid-turn, consume only on the matching `skill.prompt`; fallback = no live/spawning loop AND allowed origin. Sticky run route in the SAME slot as turn routes was wiped by the first `route()` call (confirmation BLOCKER) → separate `runMain`, best-tier rows only (work/cheap rows leak low effort across turns). Live facts read from `~/.claude/projects//.jsonl` (+ `subagents/agent-*.jsonl`): `effort` + `message.model` per step. Typed `/status` → main low; analyzer step 0 opus/xhigh with frontmatter high (spawn bookkeeping precedes step 0; row beats frontmatter). - **Apply**: hook-side user-intent markers: bind to a name, add a pending slot for mid-turn, keep an ordering-independent fallback. Two lifetimes = two slots, never one slot with a source tag. Verify engine behaviour in the transcript jsonl, not in `$.ui.log`. Links [[BDR-115]], [[LRN-206]]. ## LRN-212 — The engine hot-reloads a mod's hooks module from the working tree: unverified code runs live during its own feature run; dialogs answered there are facts; the kit never touches the disk +- **Date**: 2026-10-11 - **Context**: W3-A, 2026-10-10. Mid-run, `routing.json` gained decisions nobody expected (verifier → judge, feater → judge). First read: a kit test wrote the real file. Truth (feater, transcript timestamps = file mtimes to the second): the engine had reloaded `register.ts` from the working tree through the `skills/model-router` link, the live mod opened the T2 dialog on MY verifier/feater spawns, the user answered them in the terminal. The kit cannot write: an unmocked `fs.write` is refused ("no implementation"), a throwing mock lands on the same refusal; the real file's sha was stable across 10+ suite runs. - **Apply**: while a mod is under development in this repo, its working-tree code is LIVE in every session (no `/reload-plugins` needed): expect its side effects (dialogs, writes) during the gates; tell the user what dialogs will pop and what to answer; reset the data file deliberately at the gate. Blame the kit last: check mtimes against the transcript before assuming a test leak. Live answers = criterion evidence (record them `[gated]`). Links [[BDR-116]], [[LRN-206]], [[LRN-211]]. ## LRN-213 — grep-based dead-function census misses constructed-name callers +- **Date**: 2026-10-12 - **Context**: code-clean 2026-10-12. `detect_gstack` / `detect_plugin_dev` (lib/detect-plugins.sh) had zero literal callers → flagged dead. Real caller: hooks/session-start.sh:80 `if "detect_$plugin"` over a name list. Deleting them = silent hook break on every session start. - **Apply**: before calling a function dead, grep its PREFIX in a quoted-expansion form (`"prefix_$`, `prefix_${`, `eval`, `declare -f`) and any name-list loop. Constructed dispatch = exclude + note in the plan so challengers do not re-raise. Links [[LRN-214]]. ## LRN-214 — shellcheck directive after the first command scopes to that command only; file-wide disable goes BEFORE `set -u` +- **Date**: 2026-10-12 - **Context**: code-clean r1 placed `# shellcheck disable=SC2015` after `set -u` in seo-data.test.sh → two lenses proved via stdin that 26 of 27 sites stay red. Precedent in repo: lib/tests/effort-routing.test.sh:8 (before any command) silences file-wide. - **Apply**: file-level directive = between the shebang and the first command. Prove with `shellcheck` exit 0 on the edited file, not by reading. Links [[LRN-213]], [[LRN-215]]. ## LRN-215 — helper extracted from a `set -e` function must be called as a plain statement; `helper || …` / `if helper` switches errexit OFF inside it +- **Date**: 2026-10-12 - **Context**: code-clean B5/B7/B9 split enable_tool / enable_skill / cmd_show out of `set -euo pipefail` scripts. r2 executor rule said `|| return $?`; confirmation lens: that form disables errexit inside the helper, so a failed `mv` (toggle-external.sh:273) would print `ok …` rc 0 instead of aborting — a path no golden capture sees. Plain call keeps `return 1` → errexit in caller → exit 1 as today. - **Apply**: split rule for -e scripts: plain calls only, never `||`, `&&`, `if`, `!` around an extracted helper. Golden capture (stdout + stderr + rc + fixture tree) before/after for every moved arm when the suite discards output. Links [[LRN-214]], [[EVAL-046]]. ## LRN-216 — Capping a main-loop model switch = cap the COLD READ (context − target's warm prefix), never the context size; the warm record must be written on EVERY main step +- **Date**: 2026-10-13 - **Context**: model-router downgrade cap 2026-10-13. r1 compared context size to cap → after N coding turns sonnet warm, fable cold; context crosses cap → next coding turn starts on fable (cold) and cheap re-down refused = worst outcome. r2 fixed measure, but wrote `served` only on routed steps → unrouted steps on session model invisible → return to fable refused above 200k (confirmation pass BLOCKER). Per-model prefix cache (LRN-204): cost of switch INTO M = tokens − tokens at M's last step if within TTL, else all; context smaller than record = history rewritten (compaction) = cold. - **Apply**: any "switch model when cheap" logic: (1) keep `{at, tokens}` per model id, written at every step of the loop whatever the routing; (2) cost = delta vs that record within TTL, whole context otherwise or when record > current; (3) unknown size = blocked; (4) no special-case "return to session model" bypass, the measure covers it. A guess-sourced route ranks vs the SESSION model, not the current one, or a breaker fallback walks down to the cheapest tier. Links [[BDR-116]], [[LRN-204]], [[EVAL-047]]. ## LRN-217 — In an `agent.spawn` hook, "no explicit `model` and no routing row" does NOT mean "inherits the parent": the agent's frontmatter `model:` is invisible to the hook; only an allowlist of types known to inherit is safe, and `agent.offer.source` tells a built-in from a shadowing definition +- **Date**: 2026-10-13 - **Context**: model-router residuals 2026-10-13, plan r1 pinned every unrowed, model-less spawn to the session model during a demoted turn. Two lenses BLOCKER: engine 2.1.296 builds the spawn input as `model: e.model` (Agent tool param only); frontmatter model never reaches `agent.spawn` nor `agent.offer`; `route === undefined` also covers frozen forks/workflows (hook model ignored) and project-source skips; nested spawns carry the SUB-AGENT's `parentModel`; `turnModel` is set on upgrades too. A repo/user `general-purpose.md` can shadow the built-in with its own `model:` → `offers.get(type) === 'built-in'` is the discriminator. - **Apply**: before rewriting a spawn's model, prove the agent would inherit: allowlist of built-in types with no frontmatter (`general-purpose`), source `built-in`, not fork/workflow, `parentAgentId` undefined, and the parent really sits below the baseline. Record what the hook cannot see as a `shortcut:` at the allowlist. Links [[BDR-116]], [[BDR-115]], [[LRN-203]]. ## LRN-218 — `$.model.complete` as availability probe: credits-exhausted model NEVER settles (timeout = only failure signal); answer is an object; probe the decided target only, after the decision +- **Date**: 2026-10-15 - **Context**: model-router bugfix 2026-10-14/15, live scratch mod (`claude -p --plugin-dir`). `complete({model:'claude-opus-5-5', prompt:'ok', maxTokens:1})` resolved 1308 ms with OBJECT `{ isAnswered, text, usage }` (d.ts says string; maxTokens not honored, 43 output tokens). Same call on `claude-fable-5-1` without credits: no settle, no rejection after 900 s (client retries the 429). Plan r1 probed in a loop before deciding → BLOCKERs: unbounded spin on explicit alias, cur probed. - **Apply**: availability check via `complete()` = race vs own timeout, treat timeout + rejection as down, any resolved shape as up; never read `isAnswered:false` as failure (unobserved). Decide first, probe only the move target, once, skip cur and held ids, one re-decision without probe. No hook signal on the probe (Esc must not mark model down); probe sleep counts against 10 s `turn.step` budget. Links [[BLK-030]], [[LRN-207]]. ## LRN-219 — Scanner regex over untrusted trees: bound every repeat, cap every comment blanker, lock with a timing test on an adversarial file +- **Date**: 2026-10-19 - **Context**: guardrails split 2026-10-19. Challenge + 3 review rounds found quadratic COMMENT / env regexes, unbounded `[^>]*` and `\S+`. Fixes: DATA_ATTR `[\w-]{0,60}`, SCRIPT_SRC `[^>]{1,300}`, TRACE_MARKERS `[^)\n]{0,200}`, SQL_COMMENT `/\*[\s\S]{0,4000}?\*/`, MARKUP_COMMENT tempered ``. Residual ~1.4 s on adversarial 200k file, accepted. - **Apply**: whole-file regex = bounded repeats, tempered dot for nested delimiters, timing lock in the suite (`guardrails-scan.test.sh`), files > 1 MB listed by path (`Project.large`), `.map` head 4 KB only. Links [[BDR-122]]. ## LRN-220 — Live probe verdicts fail closed by construction: every negative branch needs its own fixture route, a 3xx reaching a verdict = dropped redirect = SKIPPED, a depth or size limit hit = SKIPPED never CLOSED +- **Date**: 2026-10-19 - **Context**: same run. GATE 1 verifier: `fields` probe had OPEN + SKIPPED assertions, no CLOSED route. Opus review: three false verdicts (embedded `sourceMappingURL` string → OPEN; off-host map redirect dropped by `_SameHost` → 302 → CLOSED; sensitive key below depth 4 → CLOSED). Each = a code path no fixture route exercised. - **Apply**: per probe, fixture routes for OPEN, CLOSED, unobservable (SKIPPED), dropped redirect, truncated, oversize; anchor marker comments at line start and take the last; walk bounded bodies fully (iterative). Links [[BDR-122]], [[LRN-219]]. ## LRN-221 — Floor-guard suppressions: remove, never waive; contract oracles assert intent, not syntax +- **Date**: 2026-10-19 - **Context**: GATE 1 counted 6 floor findings: `# noqa: E402` ×2 (import after `sys.path.insert`), a `# shellcheck disable=SC2016` copied from another suite (dead: deleting it raised nothing), 3 plan quotes of the same lines. `importlib.import_module` after the insert needs no noqa. Then criterion 16's CHECK grepped `^import scanner` and went red on the legit fix. - **Apply**: a suppression = first try the construct that needs none; test a copied `disable` by deleting it; a CHECK greps the symbol or behaviour (`scanner.Catalogue` loaded), never one spelling of the code. Links [[BDR-102]]. ## LRN-222 — Map an error to a verdict on a typed exception or carried constant, never on `str(err)` +- **Date**: 2026-10-21 - **Context**: guardrails residuals plan r2 detected budget exhaustion by `BUDGET_EXHAUSTED in str(err)`; `URLError` renders as `` and wraps the reason object, so the match never fired and the verdict stayed SKIPPED instead of ERROR. Challenger (correctness lens) caught it as BLOCKER before the contract. Fix: `_BudgetExhausted(URLError)` subclass carrying the constant, mapper uses `isinstance`, regression test raises the real type. - **Apply**: err→verdict code matches on type or an attribute the raiser sets; the test raises the real exception class through the real call path, never a hand-built message. Links [[LRN-220]], [[BLK-033]]. ## LRN-223 — Regex timing lock is vacuous when the input matches early: non-matching worst-path input, assert `is None`, ≥ 2x margin +- **Date**: 2026-10-21 - **Context**: plan r1 timing cases (LRN-219 lock, 1.0 s / 80 KB) fed inputs the bounded regex matched at the start, so they ran fast by construction and proved nothing (challenger BLOCKER, robustness lens). r3: inputs built to force the longest non-matching scan, cases assert `is None` and the elapsed time; SHELL_DB case at 0.65 s was too close to the lock → 1800 units (~29 KB) for margin. - **Apply**: one timing case per bounded regex, input that does NOT match and exercises the widest quantifier; assert the non-match too, else a regex that matches everything passes the lock; keep elapsed ≤ half the lock. Links [[LRN-219]], [[BLK-033]]. ## LRN-224 — Best-tier agent row floors on tier's 2nd alias: inTier writes head-or-above only +- **Date**: 2026-10-21 - **Context**: feat A (routing policy BLK-032) moved verifier + security-auditor to new `audit` phase (best = fable>opus>sonnet). Plan r1 set frontmatter `model: fable` (census rule floor = tier head) and claimed "Fable down → falls to opus". False: `inTier` (register.ts) writes a model only if it is the head or ranks above it, else logs "tier … down, frontmatter model kept" → fable frontmatter = gates spawn on dead Fable every credit outage (BLK-030/031). Lower tiers never hit it (head sonnet/opus always has a higher alias). Caught by correctness + robustness lenses r1, not by plan author. - **Apply**: an agent on a best-tier row keeps opus frontmatter; router lifts to Fable when up. Census `tier_floor` (effort-routing.test.sh) locks 2nd alias for best. Residual: spawn path unprobed → first gate of an outage window still dies once, retry lands on floor (register.test.ts audit-row case b). Links [[BLK-030]], [[BLK-032]], [[LRN-204]]. ## LRN-225 — Gate on the tool's own exit-code contract, never on its prose; control through the gate's own helper on a clean/dirty pair +- **Date**: 2026-10-22 - **Context**: BLK-034. `grep -qi warning` on `claude plugin validate` output broke when CLI 2.1.306 added an advisory section; first plan (sed range delete between two markers) was fail-open: closing marker printed only when findings > 0, else range ran to EOF and hid `✔ Validation passed with warnings`. - **Pattern**: (1) a CLI with `--strict` / `--json` / rc semantics → gate on rc, prose only in the ko message. (2) Positive control runs the SAME helper the gate uses (a copy of the invocation stays green when the gate drifts). (3) Pair of fixtures differing only in the guarded cause (warnfix vs cleanfix): parse error (`error: unknown option`, rc 1 on both) or scrape added back turns the pair red; a lone "rc must be 1" accepts any failure. (4) Inline sample strings test the author's literal, not the code: a check that cannot fail is not a check. (5) `WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT` stays script-level: `local` WORK + EXIT trap → `unbound variable` under `set -u`, dir leaks. - **Apply**: any suite wrapping a third-party CLI verdict (plugin validate, linters, validators). Links [[BLK-034]], [[LRN-223]]. ## LRN-226 — Cap one axis of a layered route at the writer, not at the reader +- **Date**: 2026-10-23 - **Context**: feat C model-router (BLK-032). r1 capped prompt routes inside `wantedModel` (drop model when above session). Challenge r1: capped `turnMain` still won slot order → hid held best-tier `runMain` (keyword reply in /feat run → opus); cap read `sessionModel`, '' after /reload-plugins → fail-open lift to fable. - **Pattern**: writer emits effort-only route (`{effort}`, no tier/model, same as `belowRun`); existing per-axis rule (model-less slot skipped for model axis) falls through to run slot or keeps cur. No baseline read, no new predicate, dead floor-model branch removed. - **Apply**: when a source must stop driving one axis, strip that axis where the route is written; check every lower-priority slot it used to shadow; a reader-side cap needs the baseline to be known at decision time, prove it or don't use it. Links [[BDR-123]], [[BDR-115]], [[EVAL-048]]. ## LRN-227 — Root-commit author ≠ name the user remembers; identity list must cover every root email +- **Date**: 2026-10-23 - **Context**: BDR-124 verify. User expected lima `root n.turpault 2009`; real root = t.surrel 2009-02-25 (not shallow). Own repo root = `git@bchanot.fr`, absent from user.email + claude.identity → false foreign banner. - **Apply**: check origin claims against `git log --max-parents=0`, never memory. Every email ever used as root author → `git config --global --add claude.identity `. Links [[BDR-124]]. @@ -1913,17 +1807,29 @@ Rule: when editing a doctrine file under structure locks, grep the test's lock s - **Apply**: launch `void (async () => { await $.clock.sleep(300); … $.ui.ask … })()` before returning the deny; hold any shared dialog slot synchronously before return, free it in the continuation's `finally`. `$.command.run({ command: 'model', args })` from the continuation re-enters as PreModelSwitch source `command` + command.run origin plugin: gate both. Links [[BDR-127]]. ## LRN-232 — Path rules load inside sub-agents; a load proof prompt must name the Read tool call +- **Date**: 2026-10-27 - **Context**: phase 0 proof 2026-10-26. `InstructionsLoaded` hook fields: `session_id`, `agent_id` (sub-agents only), `agent_type`, `cwd`, `file_path`, `memory_type`, `load_reason`, `globs`, `trigger_file_path`. General-purpose sub-agent Reading `rules/a11y.md` → `.claude/rules/rules-maintenance.md` logged, `load_reason: path_glob_match`, `agent_id` set. First headless probe `claude -p "read these 4 files"` → 0 log lines: model answered from memory, never called Read. Re-run "Use the Read tool, one call per file" → 4 lines. - **Apply**: per-repo split pass may move sub-agent-needed sections; verify per repo: `jq -c 'select(.memory_type=="Project" and (.file_path|contains("/.claude/rules/")))' ~/.claude/logs/instructions-loaded.jsonl | tail`. Any "does X load / fire" proof prompt names the tool and the call count; 0 lines first means "did the model act", not "the feature is off". A `paths:` rule loads on Read, not on Write of a new file. Links [[BDR-128]], [[BDR-125]]. ## LRN-233 — Bash under pipefail: `head` after a producer, blanked PATH, unchecked temp-file rewrite +- **Date**: 2026-10-27 - **Context**: `lib/project-rules.sh` 2026-10-26, caught by plan challenger r2 + opus review after 2 sonnet reviews. (1) `compgen -G '**/*' | head -3` → producer SIGPIPE on > pipe buffer of hits, pipeline rc 141 under `pipefail`. (2) `PATH=/nonexistent bash hook.sh` → rc 127: blank PATH applies to the lookup of `bash` itself. (3) `tmp=$(mktemp); f > "$tmp" && cat "$tmp" > src` unchecked → `TMPDIR=/nonexistent` gives rc 0, "moved" printed, src unchanged (I/O failure path untested by 5 reviewers). (4) `compgen -G`: no brace expansion; dotglob matches dotfiles the engine skips; globstar never descends a symlink met under `**` (`top/link/**` finds, `top/**` misses). - **Apply**: a bounded reader after a producer is awk, reads to the end: `awk 'NR <= 3 { print } END { exit NR == 0 }'`. `"$BASH"` when PATH is blanked in a test. `tmp=$(mktemp) || return 2`; rewrite as `if ! { f > "$tmp" && cat "$tmp" > src; }; then rm -f "$tmp" "$out"; return 2; fi` (SC2015 forbids `a && b || c`). Plan Review Focus: one failure-path test per file-rewriting function (`TMPDIR=/nonexistent`, `chmod a-w`; root ignores chmod). One glob per extension; test names say what they prove (a guard the final `exit 0` swallows is unobservable). Links [[BDR-128]], [[LRN-096]]. ## LRN-234 — Glob order follows LC_COLLATE; gate a new-case fix on the case, prove the old contract by differential +- **Date**: 2026-10-27 - **Context**: feat rules-h3-extract 2026-10-27. Confirmation challenger ran the planned suite under en_US.UTF-8: `printf '%s ' *` gave `sub2.md sub.md `, want `sub.md sub2.md ` (punctuation ignored in UTF-8 collation; C order differs). `make test` (Makefile) pins no `LC_ALL`. Same pass: `###` separator re-emission written as `RLENGTH - 1 < lvl` also fired for `##` ended by an H1 → 5 of 2,162 `##` extracts on this repo's md files changed vs develop, against the immutable REQUEST "`##` behaviour unchanged"; the suite (T7-T13) stayed green either way. - **Apply**: a test never asserts a glob listing order: count (`printf '%s\n' * | wc -l`), name files, or pin `LC_ALL=C` in the recipe. A fix for a new case is gated on that case (`lvl == 3 && …`) so the existing contract stays byte-identical, and the proof is an old-vs-new differential on real inputs (every `##` of every tracked md), not the suite alone. Also: a `# shellcheck disable` in a diff trips the floor guard unless the contract authorizes it; build the offending literal instead (`printf '\140\140\140'` for backticks). Links [[LRN-233]], [[BDR-128]], [[LRN-096]]. ## LRN-235 — bash `!` blind to a failed redirect on a compound command; assert guards on their stderr line, anchored +- **Date**: 2026-10-27 - **Context**: feat extract-hardening 2026-10-27. Plan r1 wrote `if ! { printf …; body; } > "$out"; then … return 2`. Two challengers + own probe on bash 5.3.9: redirect fails → bash returns 1 BEFORE applying `!`, `if` sees false, source rewritten, rc 0 = the bug unchanged. `! { echo a; } > bad; echo $?` → 1. shellcheck clean, floor guard blind. LRN-233 form works only because its redirects sit INSIDE the group. Same pass: `grep -c 'cannot create'` on captured stderr = 2 on GNU coreutils (mkdir prints `mkdir: cannot create directory …`), 1 on uutils (this host) → host-dependent test. mkdir rc check + write rc check give same rc and same fs state; only the stderr line tells them apart. - **Apply**: a redirected group is checked as `{ a && b; } > f || { cleanup; echo … >&2; return 2; }` (chain inside with `&&`, else the last command masks printf). Never `if ! { … } > f`. A guard whose only observable is a message gets a test on that message, `grep -c '^project-rules: …'` anchored on the lib's own prefix, never a bare word a system tool may also print. A fixture escape (`../x` from the fixture root, `ln -s /nonexistent`) runs from a subdir of the fixture and links inside it. Links [[LRN-233]], [[LRN-096]], [[BDR-128]]. + +## LRN-236 — uutils mkdir 0.10 is not atomic: lock with bash noclobber (O_EXCL), token unlock (2026-10-28) +- **Context**: memory v2 lock proof 2026-10-27. 5 concurrent `memory.sh add` lost 2-4 entries, silently. `/usr/bin/mkdir` = uutils coreutils 0.10.0: two concurrent `mkdir x` both rc 0 (`for i in $(seq 20); do (mkdir y && echo won) & done` → 2 wins). Lock-by-mkdir unsafe on this host. +- **Apply**: atomic create lock = bash noclobber: `(set -C; printf '%s\n' "$token" > "$lock") 2>/dev/null` (open O_EXCL by bash itself, no external tool, portable to macOS). Unlock only on token match; steal through a second noclobber guard. Race test with ≥5 writers is the flip test (red with mkdir). Never `rm -rf` a lock dir through a variable. [[BDR-129]], [[BDR-110]]. + +## LRN-237 — A migration oracle sharing the transform reader proves nothing: own range per reader, assert on the entry, prove with the user invocation (2026-10-28) +- **Context**: memory v2 `upgrade` verdict oracle, 2026-10-28. Oracle compared each blocker's open/closed verdict, legacy reader before vs strict reader after. Four review rounds each found a range leak the oracle shared: `###` entry invisible to v1 reader counted closed → `resolved` written on an open blocker; `## BLK-003` range swallowed a following `### BLK-001`; a `### ` heading quoted in a fence ended the range; status lines inside a fence read. Tests stayed green because they checked the reconcile enumerator, blind to `###`. Separately: template path derived after `-C` cd → upgrade rc 2 only when the lib is called by relative path; implementers always used absolute paths. +- **Apply**: an oracle sharing the transform's reader proves nothing: give each reader its own entry range (end at next heading of any level, fence-aware, skip fenced status). Assert on the entry itself, not via an enumerator. Prove a CLI on real data copies with the invocation users type (relative path + `-C`). Resolve a lib's own dir at source time (`cd -P` before any `cd`). [[BDR-129]], [[LRN-096]]. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index bbf810f..ce2c10b 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -28,7 +28,10 @@ Shared rules for every phase: - [ ] `extract` rewrite failure mid-`cat` (ENOSPC/EIO after the truncation of `$src`): keep `$tmp` and name it on stderr instead of `rm -f` (today "$src not rewritten" can be false, the two copies gone; onboarder S1 rollback covers the split path, not direct lib use). - [ ] shortcut `_rules_out_path_ok`: the `..` check is lexical, a symlinked parent component (`.claude` or `.claude/rules` pointing elsewhere) is not resolved; upgrade = `cd -P` on the parent dir, compare with `$PWD` (no portable `realpath -m`). -- [ ] **Phase 4a, memory v2 write side: shell, no mod** (shrunk 2026-10-25: the measured recall channels never read Meta; the measured status bug is a reconcile parser bug) +- [x] **Phase 4a, memory v2 write side: shell, no mod** (shrunk 2026-10-25: the measured recall channels never read Meta; the measured status bug is a reconcile parser bug) + - Done 2026-10-28 on feature/memory-v2-write (a423594..aab9e4d, registries v2 9698473): BDR-129, LRN-236, LRN-237, EVAL-052. memory suite 202/0, make test green. + - [ ] Phase 4a per-repo pass: `bash ~/.claude/lib/memory.sh -C upgrade` on a clean `.claude/memory`, one `chore/memory-v2` branch per repo, user approval each, commit via `/commit-change` when headings were rewritten (memory-commit rc 6 by design). Ready (proven on copies 2026-10-28): config, faunosteo, game-deploy ×2, integration_alphalink, robin_petier, zenquality, angelscar356, bchanot-cv, for_you, gitea-deploy, nuit-folle. Refused, user decision first: game (`## BDR-027/061 ADDENDUM` headings, duplicate BLK-008/014), trucks_at_work (bullet-list `## Index` holding BLK-001's closure). + - [ ] Phase 4a parked minors (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. - 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 --title --body-file [--status --supersedes]` allocates next ID from headings (never the Index) under `flock` (concurrent conversations, phase 5), appends the entry; `status ` appends a dated status line (append-only); `journal ""`; `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. diff --git a/.claude/tasks/contracts/2026-10-27-memory-v2-write-2030.md b/.claude/tasks/contracts/2026-10-27-memory-v2-write-2030.md new file mode 100644 index 0000000..bc1e0b3 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-27-memory-v2-write-2030.md @@ -0,0 +1,40 @@ +# CONTRACT — memory-v2-write (phase 4a) +- date: 2026-10-27 | flow: ship-feature | branch: feature/memory-v2-write (off develop ae9a7e3) +- status: active + +## REQUEST (verbatim — IMMUTABLE) +Phase 4a of the context mod queue (BDR-125), TODO.md "Phase 4a, memory v2 write side: shell, no mod": `lib/memory.sh` as the single registry writer, like gitflow.sh (`add --title --body-file [--status --supersedes]` allocating the next ID from headings under flock, `status ` appending a dated status line, `journal ""`, `index` printed on demand from headings, `check [--staged]` validator in add/check + make test, not in the pre-commit); one shared status parser (own-header `[tag]` first, then last status-bearing line wins) fixing the BLK-032..034 false-open in reconcile with a regression test; the four generated `## Index` blocks removed in one /prune-memory curation and the Index steps dropped from capitalize, ship-feature, commit-changer, prune-memory § D; a per-file v2 marker so the 8 v1 projects keep working and doctor warns "registry v1"; citers patched (capitalize, close, prune-memory, CAPITALIZE steps of feat/bugfix/hotfix/ship-feature/commit-change, lib/capitalize-commit.md, lib/analyze-before-plan.md, lib/reconcile.sh, templates/memory, onboard/init-project, doctrine-citers census, CLAUDE.global.md Memory registries). Dropped: Meta line, backfill, scope/critical labels, triggers field, English validator. Proof: writer round-trip, flock race test, status parser on the three false-open BLKs + fixtures, v1 project untouched, make test green. + +(user: "ok tu peux passer a la suite", 2026-10-27, after the phase 0b and extract-hardening merges.) + +## CLARIFICATIONS +(pass A: scope gaps surfaced by the read-before, settled at the STEP 1 brainstorm — see [gated] rows below) + +Q: files outside the seed FILE SCOPE that the approved plan (STEP 3 gate 2026-10-28, plan r3 Tasks 2/3/5/6) requires? / A: agents/analyzer.md (Task 5 citer), lib/tests/run-deterministic.sh (Task 3 chokepoint test), skills/reconcile/SKILL.md (Task 2 parser doc + test count), skills/prune-memory/tests/fixtures/red6-check/ added and red6-orphan/ deleted (Task 6: RED-6 asserted "no false ORPHAN INDEX", a check that only exists with an Index; § D removal makes it obsolete, red6-check replaces it as the flip test) [gated 2026-10-28, plan approval] +Q: EVAL Index "Action" column at upgrade? / A: the 2026-10-27 gate dropped the column on the premise the body carries **Action**; where the body has no status word, the Index action is materialized as a body status line (verifier gap 2026-10-28, EVAL-005/028/040) [gated 2026-10-27, refined 2026-10-28] + +## ACCEPTANCE CRITERIA +1. `lib/memory.sh [-C dir] add --title --body-file [--status ] [--supersedes ]` appends one entry `## -NNN — [<status>] (<date>)` + body at the end of the registry, NNN = max heading ID + 1, under a lock; prints the new ID on stdout; rc 2 with a named reason on a bad kind, a missing body file, a duplicate ID after allocation, or a validator failure (nothing written). +2. `memory.sh status <ID> <new>` appends a dated status line to that entry (inserted before the next heading, after the body), never rewrites an existing line; rc 2 when the ID does not exist. +3. `memory.sh journal "<line>"` appends the line under today's `## YYYY-MM-DD` heading, creating the heading at the end of journal.md when absent. +4. `memory.sh index [<registry>]` prints a markdown table (ID | Date | Title | Status) derived from headings and the status parser only; no `## Index` block is read. +5. `memory.sh check [--staged]` validates: heading shape, ID uniqueness, v2 marker present, no `## Index` block in a v2 file; `--staged` also refuses a removed line inside an existing entry. It runs inside `add` and in `make test`; the generated pre-commit hook is untouched. +6. One shared status parser (lib function used by memory.sh and lib/reconcile.sh): candidates are the entry's own header `[tag]` and labelled status lines only (never a free word in prose); the last candidate in document order wins. `reconcile_blk_open` on a fixture holding BLK-032..034 as written today returns none of them; the existing run-reconcile T1/T2 stay green. +7. The four `## Index` blocks of this repo's registries are removed in one deterministic step; every status or supersession that lived only in an Index row is first materialized as a status line in the entry body (oracle: parser(body) == former Index status for every such row); heading count unchanged. +8. Per-file v2 marker: every registry of this repo and the four registry templates `templates/memory/{decisions,learnings,blockers,evals}.md` carry it (journal is not a registry: no marker); a file without it is v1: the writer still appends, `check` reports it, and the per-project session banner warns `registry v1`. +9. Citers patched in the same branch: capitalize, close, prune-memory (§ D removed, STEP 3 status carrier = `memory.sh status`, STEP 4 verify = `memory.sh check`), CAPITALIZE steps of feat/bugfix/hotfix/ship-feature/commit-change, init-project, lib/capitalize-commit.md (rc 5 documented), lib/analyze-before-plan.md, lib/reconcile.sh, templates/memory, onboard; doctrine-citers census green. +10. CLAUDE.global.md "Memory registries": writes go only through `lib/memory.sh`; the "Registries load every session" premise replaced; the heading and the bold label `Always English, always caveman` kept (census); file line count not above today's 333. +11. Dropped, must NOT appear: Meta line, 434-entry backfill, scope/critical labels, triggers field, English validator. +12. Proof: writer round-trip test, concurrent-add race test (two adds, distinct IDs), status parser on BLK-032..034 fixtures, every other project's `.claude/memory/` untouched (no diff outside this repo), `make test` all green, shellcheck clean, every new lib line ≤ 80 chars, functions ≤ 25 logic lines / ≤ 5 locals / ≤ 5 params. + CHECK: make test 2>&1 | tail -1 + EXPECT: all suites green + EVIDENCE: MET exit=0 marker-found :: all suites green + +13. [gated 2026-10-28] `memory.sh upgrade` migrates every measured v1 dialect (hyphen, pipe, `###` headings, title-suffix status, `date: · status:`, `**Statut** :`, no frontmatter) to v2: headings normalized to `## ID — title (date)`, frontmatter added, open/closed verdict of every entry identical before and after (oracle), idempotent; proven on copies of the 13 other projects. Applying it to those repos is a later per-repo pass, not this branch. + +## FILE SCOPE +lib/memory.sh (new), lib/tests/memory.test.sh (new), lib/tests/fixtures/* (new fixtures), lib/reconcile.sh, lib/tests/run-reconcile.sh, lib/memory-commit.sh, lib/capitalize-commit.md, lib/analyze-before-plan.md, skills/capitalize/SKILL.md, skills/close/SKILL.md, skills/prune-memory/SKILL.md (+ tests/run-deterministic.sh, test-prompts.json), skills/feat/SKILL.md, skills/bugfix/SKILL.md, skills/hotfix/SKILL.md, skills/ship-feature/SKILL.md, skills/commit-change/SKILL.md, agents/commit-changer.md, skills/init-project/SKILL.md, agents/onboarder.md, skills/onboard/SKILL.md, templates/memory/*.md, hooks/session-start.sh, CLAUDE.global.md (Memory registries), Makefile (suite glob already covers lib/tests/*.test.sh), .claude/memory/{decisions,learnings,blockers,evals}.md (Index removal + marker), mods/model-router/routing.json (only if a new row is needed), docs (CHANGELOG at STEP 8). + +## PROOF — criterion 13 (controller, 2026-10-28, after 28c5a42) +Fresh scratchpad copies of the 14 project memory dirs, `bash lib/memory.sh -C <copy> upgrade` (relative lib path), then `check`, then a second upgrade (cksum): 13 rc 0 + check 0 + idempotent (config 2, robin_petier 6, zenquality 15, angelscar356 32, bchanot-cv 3 added status lines; others 0); game rc 2 (`## BDR-027 ADDENDUM`, `## BDR-061 ADDENDUM` headings, duplicate BLK IDs: plan Deviation 6, user decision at the per-repo pass); `git -C <orig> status --short .claude/memory` empty on all 14. The first run of this proof (before 28c5a42) found the template path resolved after the `-C` cd (rc 2 on config, faunosteo, for_you, trucks_at_work): fixed in 28c5a42, test T15-relpath. +PROOF update (after aab9e4d, final code review): trucks_at_work is now REFUSED (bullet-list `## Index` in decisions/learnings/blockers, facts would be lost; user decision at the per-repo pass, like game). Date counts corrected: the earlier zenquality 59 / angelscar356 106 were duplicates (`- **Date** :` spacing dialect, 65 and 106 such lines); now 0 and 1. 12/14 migrate, 2 refused untouched. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 4551ebd..b2ad7e5 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -30,7 +30,7 @@ claude-config/ ├── mods/ # Claude Code mods (function-hooks plugins), loaded through the skills/<name> symlink ├── skills-external/ # Vendored skill packs: gstack submodule, design skills, superpowers, agent-skills, MengTo scroll skills, 21st and Higgsfield packs (machine-owned copies gitignored) ├── templates/ # Per-project templates (CLAUDE.md, settings, memory registries, path-rule skeletons, deploy runbook, gitignore) -└── lib/ # Shared libs: gitflow, profiles, vendoring, route doctrine, gates, archetypes, project-rule oracle, tests +└── lib/ # Shared libs: gitflow, memory registry writer, profiles, vendoring, route doctrine, gates, archetypes, project-rule oracle, tests ``` ## Architecture principles diff --git a/CHANGELOG.md b/CHANGELOG.md index b391e4b..6dd2c41 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,8 +19,13 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project - **/explain-diff skill**: turns a change (commit, range, branch, merge, PR, staged or uncommitted work) into one self-contained HTML page saved outside the repo, under `~/Documents/explanations/<project>/YYYY-MM-DD-<slug>.html`. The page has a background, an intuition built on toy data with HTML diagrams, a code walkthrough grouped by concern and a 5-question interactive quiz. Adapted from Geoffrey Litt's explain-diff gist. A bundled template (light and dark, works offline) and a checker (`scripts/check_explanation.py`: file name, location, sections, quiz, code escaping, no ASCII art, no em-dash) hold every page to the same floor. Routing row `reflect`; profiles full, max and dev. - **Project path rules (CLAUDE.md split)**: `lib/project-rules.sh` (`check`, `matches`, `sections`, `extract`, `emit`, optional `-C <dir>`) is the glob oracle for `.claude/rules/<name>.md` rules, one-line `paths:` frontmatter, loaded on Read of a matching file; suite `lib/tests/project-rules.test.sh`. `/onboard split` classifies an existing project CLAUDE.md section by section behind a gate and moves the path-bound ones into rules on a `chore/claude-md-split` branch. `extract` also moves a `###` subsection (heading passed as `'### <title>'`; a bare heading stays `##`), which ends at the next heading of level 3 or less outside a fence, and `sections --depth 3` lists each `##` section's subsections with their sizes, so `/onboard split` can move a path-bound subsection out of an always-on parent (one `### <title>` row; a row's parent is never itself a move row). `extract` refuses an absolute `<out>`, one with a `..` part, or one that already exists (a dangling symlink included), with rc 2 and the reason on stderr, and leaves the source CLAUDE.md untouched when the rule directory or file cannot be written. `/onboard` and `/init-project` emit `docker`, `testing` and `ci` rules from `templates/project-rules/` when their globs match. This repo's CLAUDE.md now keeps its header, Health Stack and a pointer; four sections load as path rules. - **InstructionsLoaded logger**: `hooks/instructions-loaded.sh`, wired in `settings.json`, appends one JSON line per instruction file loaded to `~/.claude/logs/instructions-loaded.jsonl` (rotated above 5 MB), the proof that a path rule loaded. +- **Memory registries v2, single writer**: `lib/memory.sh` is the one writer and reader of the `.claude/memory/` registries (every verb takes an optional leading `-C <dir>`): `add <kind> --title … --body-file … [--status …] [--supersedes <ID>]` appends an entry with the next ID from the headings and prints only the new ID; `status <ID> <text>` appends a dated `**Status (<date>)**:` line; `journal <line>` appends under today's `## YYYY-MM-DD`; `index [<kind>]` prints ID, date, title and status from headings and bodies; `check [--staged]` verifies heading shape, unique IDs, no Index and no open fence (a v1 file is named, never failed); `upgrade` migrates v1 to v2 (Index-only dates and statuses become body lines, `format: 2` added, `## Index` removed, every v1 heading dialect becomes `## ID — title (date)`), after an oracle on IDs, check and blocker verdicts, else rc 2 with the file untouched (a duplicate ID or a non-table Index is refused). Writes run under a lock in the git common dir, on a verified backup restored on failure or signal. `templates/memory/` ships v2 templates; the session banner adds `registry v1: N file(s) (memory.sh check)` while a project registry is v1. Suite `lib/tests/memory.test.sh`. ### Changed +- Registries are written only through `lib/memory.sh`, never by Edit (`CLAUDE.global.md`, Memory registries); every CAPITALIZE step (`/feat`, `/bugfix`, `/hotfix`, `/ship-feature`, `/capitalize`, `/init-project`, `/onboard`, `commit-changer`) writes through `lib/capitalize-commit.md` § WRITE. +- `lib/memory-commit.sh commit` runs `memory.sh check --staged` first: a staged v2 registry that removes or rewrites a line inside an entry, gains a duplicate ID, a bad heading or an open fence, or is deleted or downgraded is unstaged and refused with rc 6; v1 registries are skipped. +- `/prune-memory` drops its Index drift category (§ D): status fixes go through `memory.sh status`, merges through `memory.sh add --supersedes`, STEP 4 verifies with `memory.sh check` (`CHECK: OK`, was `INDEX SANITY: OK`). +- `lib/reconcile.sh` reads blocker status through the parser shared with `lib/memory.sh`: on v2, a heading `[tag]` or a labelled status line, last candidate wins, resolved/superseded/deprecated closes the entry; the lexical reader is kept for v1. This repo's registries are upgraded to v2. - impeccable is the Build path for all UI: it replaces `frontend-design` on the design gate's `# GATE-BLOCK:` list and leads the Build line of the design doctrine. `frontend-design` stays installed as the light path for a one-off visual. Detector rule count corrected 45 to 61 (BDR-119). - model-router `verbose: true` logs transitions only: one line when main changes model or effort (`model-router: main: fable/high → fable/xhigh (plan: route tool)`), one hand-off line per dispatch and one per later effort move of an agent, each with its cause; the per-step, "answered by", spawn, route-tool and skill-path lines are gone. An agent answering on a model other than the planned one is said once. A non-boolean `verbose` falls back to `false`, said once. - `verifier` and `security-auditor` run on a new `audit` phase (best/xhigh: Fable, Opus when Fable is down). Their frontmatter floor is `model: opus` (the verifier was `sonnet`): a fable floor would spawn the gates on a dead model during a credit outage. `judge` (big/xhigh, opus) keeps plan-challenger, analyzer and plugin-advisor. The `about` lines of `judge` and `verify` no longer claim audits or security review. The census `lib/tests/effort-routing.test.sh` floors a best-tier agent row on the tier's second alias (opus). @@ -41,6 +46,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project - The five `effort-low` … `effort-max` skills, `lib/effort-pins.txt`, `lib/effort-pins.sh` and `lib/model-check.sh`, with their tests and the effort-pin re-apply steps of `install-plugins.sh` and `update-all.sh`. The model-router rows replace them. A typed `/effort-<level>` no longer exists: use `ultrathink` or `/route effort=max`. Breaking: the next release is 3.0.0. ### Fixed +- `/reconcile` no longer reports a v2 blocker as open because a status word appears in its title or prose (BLK-032..034). - model-router probes the model main is about to run on, moved to or kept (the session's own model included), before routing main to it: with a model out of usage credits, every new session and hold lapse used to route main there, or keep it there, and lose the turn to a 429. That model is tried once with a small completion bounded to 8 s; a timeout or error marks it down (reason `probe`) and the decision is taken again once. A model that answered is not probed again until marked down (kept across `/clear`). `"probe": false` in `~/.claude/model-router.json` turns it off; `/route show` prints `probe:`. When a lower model stands in for its tier's held head, the phase's own effort goes one notch up (reflect xhigh, plan max, orchestrate high on Opus); explicit and floor efforts are never raised. Tests: `mods/model-router/hooks/register.test.ts`. - model-router residuals of waves 1-4 (2026-10-11): the kill switch fails closed (a `~/.claude/model-router.json` present but unreadable at first load, or an `enabled` that is not a boolean, turns the router off and says so; `/route reload` answers `config unreadable; previous config kept` instead of `config reloaded`); a prompt rule whose pattern nests quantifiers (`(a+)+$`) is dropped; a config file that is not a regular file reads as failed; every log of a caught error prints its kind and code only, never the message (a JSON parse error quotes the file); rejected table keys are masked in logs and model alias keys must be short printable names; `__proto__`, `constructor` and `prototype` are never read or written as keys; the agent offers map is capped like the descriptions; a `models` alias added without a `fallback` list is ranked at the end of the default chain (the upgrade gates now apply to it); a dated or variant id maps to its table id only at a `-` boundary (`claude-sonnet-5-50` no longer reads as sonnet); the status refresh and the main-decision log on the step path can no longer unroute a step; the route tool's failure answer says the route may be partly applied. `lib/tests/mods.test.sh` proves `claude plugin test` exists from its usage line (an unknown subcommand exits 0), `doctor.sh` bounds `claude plugin list --json` to 60 s, `update-all.sh` skips `@skills-dir` mods. Kit 428 → 431. - model-router residuals of the confirmation waves: a failed `/route forget` or `/route ask` write logs its cause and answers a generic text; forget answers clean every file-sourced name, phase and key; a restore names a frontmatter file only for a valid skill name and refuses a `__proto__` row; `/route forget` never restores `changed.phases`; the dialog's Change offers and writes shipped phases only (a machine-only phase never reaches routing.json, and an alias no shipped phase uses says so); a failure after the user answered keeps the key asked instead of asking again at every use. diff --git a/CLAUDE.global.md b/CLAUDE.global.md index 6f3e5e3..b181f52 100644 --- a/CLAUDE.global.md +++ b/CLAUDE.global.md @@ -107,8 +107,8 @@ code" wins. Repo-specific instructions override both. ## Memory registries (`.claude/memory/`) Five registries persist across sessions; capitalize during and after work. -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`. | File | ID | Purpose | |---|---|---| @@ -124,8 +124,8 @@ log → journal; whether the output actually worked → evals. **Always English, always caveman**: drop articles and filler, fragments OK, short synonyms; technical terms, code blocks, quoted errors, IDs and dates -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. Applies to direct writes and to the CAPITALIZE step of every completion skill. Prompts to the user may mirror their language; the entry is English. Legacy entries: compress on demand via `/prune-memory`. diff --git a/MIGRATION.md b/MIGRATION.md index 1c4f8ce..fe285b2 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -60,8 +60,8 @@ for reg in decisions learnings blockers journal evals; do fi done -# 5. If LESSONS.legacy.md had useful entries, convert them manually into -# .claude/memory/learnings.md (LRN-XXX format) then delete LESSONS.legacy.md +# 5. If LESSONS.legacy.md had useful entries, convert each one with +# `bash ~/.claude/lib/memory.sh add learning --title … --body-file …`, then delete LESSONS.legacy.md # 6. Update .gitignore - see "Gitignore patch" section below # (`bash ~/.claude/lib/gitflow.sh reconcile` appends only the missing @@ -197,3 +197,9 @@ make doctor - **Git hooks in every repo**: `link.sh` sets git's global `core.hooksPath` to `~/.claude/githooks`. Every repo on the machine now gets the gitflow pre-commit guard and pushes each commit as it lands. For a foreign clone: `git config gitflow.protect false` and `git config gitflow.autopush false`. - **Default profile**: a machine with no profile selected now runs `full`. Check with `make profile-current`. Nine gstack skills (`ship`, `land-and-deploy`, `setup-deploy`, `autoplan`, `context-save`, `learn`, `careful`, `guard`, `design-shotgun`) left every profile and are denylisted. - **Higgsfield**: installed, off by default. Nothing to do until you enable it. + +## Memory registries v2 (2026-10-28) + +A v2 registry is the same `.claude/memory/<name>.md` file, versioned and pushed with the code, with `format: 2` in its frontmatter and no `## Index`. The session banner line `registry v1: N file(s) (memory.sh check)` flags a project still on v1. v1 stays readable and writable (lenient), and the `check --staged` chokepoint skips it. + +To migrate, run `bash ~/.claude/lib/memory.sh -C <project> upgrade` on a clean `.claude/memory`, then commit through `/commit-change` when headings were rewritten (memory-commit refuses heading rewrites by design). `upgrade` refuses a registry with duplicate IDs or a non-table Index and leaves the file untouched: a human renumbers or converts first. diff --git a/agents/analyzer.md b/agents/analyzer.md index 5b94959..1d805fd 100644 --- a/agents/analyzer.md +++ b/agents/analyzer.md @@ -96,7 +96,7 @@ A surfaced ID left undisposed is the gap this closes. You judge bearing; the mai plan decides what to DO. Read-only here too: reading registries is within Read/Grep; the "Do not modify files" rule -still forbids any write — Index backfill or new entries are never your job. Empty or absent +still forbids any write — new entries or status lines are never your job (writes go through lib/memory.sh). Empty or absent registries → omit the section (no-op). Tracing what a destructive tool would do (a mirror, a sync with delete, a recursive rm, a deploy script) is done by reading it, never by running it, diff --git a/agents/commit-changer.md b/agents/commit-changer.md index e193191..8e39d22 100644 --- a/agents/commit-changer.md +++ b/agents/commit-changer.md @@ -217,10 +217,7 @@ Otherwise: hash and substitute `(ref step <n>)` → `(ref commit <hash>)` in every entry before writing. An entry that names no step (e.g. a pure LRN pattern) needs no ref. -2. Append the resolved entries to their target registry file(s) - (`.claude/memory/decisions.md`, `blockers.md`, `learnings.md`) and - update each file's `## Index` table. Add a one-line summary of the - commit batch to today's heading in `.claude/memory/journal.md`. +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). 3. **Language rule**: written entries are ALWAYS in English and caveman, regardless of the language used in the dispatcher's approval exchange (CLAUDE.md "Memory registries", Always English, always caveman). diff --git a/agents/onboarder.md b/agents/onboarder.md index bcedd11..10e0405 100644 --- a/agents/onboarder.md +++ b/agents/onboarder.md @@ -123,7 +123,7 @@ ls ${PROJECT_ROOT}/.claude/tasks/TODO.md ${PROJECT_ROOT}/.claude/memory/ 2>/dev/ # TODO <!-- Claude writes tasks here before implementing. Format: - [ ] task --> ``` -- **.claude/memory/ missing** → `mkdir -p ${PROJECT_ROOT}/.claude/memory`, then for each of the 5 registries (`decisions.md`, `learnings.md`, `blockers.md`, `journal.md`, `evals.md`): if the file does not exist in `${PROJECT_ROOT}/.claude/memory/`, copy from `~/.claude/templates/memory/<name>.md` (YAML schema + empty index + inline template comment). If a registry file already exists → skip (do NOT overwrite). +- **.claude/memory/ missing** → `mkdir -p ${PROJECT_ROOT}/.claude/memory`, then for each of the 5 registries (`decisions.md`, `learnings.md`, `blockers.md`, `journal.md`, `evals.md`): if the file does not exist in `${PROJECT_ROOT}/.claude/memory/`, copy from `~/.claude/templates/memory/<name>.md` (YAML schema with `format: 2` + inline template comment; no Index, entries go through `lib/memory.sh`). If a registry file already exists → skip (do NOT overwrite). - **.claude/audits/ missing** → `mkdir -p ${PROJECT_ROOT}/.claude/audits` (empty — populated later by `/onboard` audit phase). **Do NOT overwrite existing content.** diff --git a/hooks/session-start.sh b/hooks/session-start.sh index bcc75bc..6a2a340 100644 --- a/hooks/session-start.sh +++ b/hooks/session-start.sh @@ -266,6 +266,19 @@ if [ -n "$REPO_DIR" ] && [ -f "$REPO_DIR/CLAUDE.global.md" ]; then fi unset _claude_lines fi +# 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 + # Version check: compare local vs remote (non-blocking) _remote_ver="" if [ -n "$REPO_DIR" ] && [ -d "$REPO_DIR/.git" ] && [ -z "${SESSION_START_OFFLINE:-}" ]; then diff --git a/lib/analyze-before-plan.md b/lib/analyze-before-plan.md index 6a7eca0..391851b 100644 --- a/lib/analyze-before-plan.md +++ b/lib/analyze-before-plan.md @@ -39,8 +39,7 @@ blocker already solved. no-match) → no-op naturally; only the ABSENT / no-file case needed the guard. The REGEX is the filter, not the file list: the glob also reads journal.md (date-keyed `## YYYY-MM-DD`) and any non-entry file, which contribute zero matches — no need to - exclude them. 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. + exclude them. 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. 3. SELECT — IDs whose title bears on $REQUEST. Judge on titles (one dense line each), not on bodies. Over-inclusion is SAFE: an entry that proves non-binding costs one bare ref @@ -97,9 +96,8 @@ is not the current flow having TREATED it as a constraint. Re-surfacing is the f ## HARD RULE — read-only -Touches nothing. No write, no Index update, no memory mutation. Symmetric to -capitalize-commit's surgical scope (there: stage ONLY memory; here: stage NOTHING). Index -backfill, if ever wanted, is `/prune-memory` passe D — never this snippet. +Touches nothing. No write, no memory mutation. Symmetric to +capitalize-commit's surgical scope (there: stage ONLY memory; here: stage NOTHING). Registry writes go through `lib/memory.sh`, never this snippet. ## ORDERING (orchestrators only) diff --git a/lib/capitalize-commit.md b/lib/capitalize-commit.md index c433631..b555d46 100644 --- a/lib/capitalize-commit.md +++ b/lib/capitalize-commit.md @@ -1,13 +1,13 @@ # CAPITALIZE-COMMIT — couple the memory commit to the dev flow -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 memory, surgically, so the flow never leaves an uncommitted `.claude/memory` behind and never embarks dangling code. This is the TAIL of capitalize, not a replacement: the SCAN + APPROVAL GATE that -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. ## WHEN TO RUN @@ -29,6 +29,26 @@ If a flow should stay fully silent on a trivial run, that is the FLOW's gate policy (e.g. hotfix skipping the journal line), not this snippet's concern — tune it there. +## 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. + ## DO 1. Compose the message from the IDs just written + the flow, matching repo style @@ -48,6 +68,16 @@ tune it there. - rc 3 → unsafe git state (detached / merge in progress); memory stays in the working tree for a manual commit — surface the helper's stderr. + - 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. `<mem_hash>` is the MEMORY commit (the one that ADDS the entries). It is NOT the code-commit hash that capitalize anchored INSIDE the entries diff --git a/lib/memory-commit.sh b/lib/memory-commit.sh index 1f55f59..32c1845 100755 --- a/lib/memory-commit.sh +++ b/lib/memory-commit.sh @@ -7,7 +7,9 @@ # happens to be dirty or staged is NEVER embarked. # # Usage (CLI): -# memory-commit.sh commit "<message>" # surgical commit; exit 0 ok/no-op, 3 unsafe state +# memory-commit.sh commit "<message>" +# # surgical commit; exit 0 ok/no-op, 3 unsafe state, +# # 5 commit rejected, 6 check refused # # Output contract for `commit`: diagnostics go to stderr; on a real commit the # short hash of the MEMORY commit is the ONLY thing on stdout (empty on no-op or @@ -18,6 +20,7 @@ set -uo pipefail MC_PATHS=(".claude/memory" ".claude/tasks") +MC_MEMORY_SH="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)/memory.sh" _in_git_repo() { git rev-parse --git-dir >/dev/null 2>&1; } @@ -68,6 +71,17 @@ commit_memory() { # then commit ONLY those paths. The pathspec on `git commit` makes it a partial # commit: other staged files (dangling code) are not recorded. git add -- "${changed[@]}" + # 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 if git diff --cached --quiet -- "${changed[@]}"; then echo "memory-commit: only ignored/no-op changes — no-op" >&2 return 0 diff --git a/lib/memory.sh b/lib/memory.sh new file mode 100755 index 0000000..d0024c2 --- /dev/null +++ b/lib/memory.sh @@ -0,0 +1,797 @@ +#!/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; a missing +# frontmatter comes from the template, ` - ` / ` | date | ` +# / `###` headings take the `## ID — title (date)` shape; +# a blocker whose open / closed verdict (reconcile's v1 +# reader) would move gets a `Status (…, upgrade)` line; the +# oracle (IDs, check, verdicts) runs first, else rc 2 +# <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). + +# absolute before any `-C` cd: a relative $0 no longer resolves after it +_MEM_LIB_DIR="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +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 (w == "") return "" + if (p == "EVAL") return st == "" ? c : "" + 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 + [[ "$1" =~ ^[A-Z]+-[0-9][0-9][0-9]+$ ]] \ + || { echo "memory: not an entry ID: $1" >&2; return 2; } + 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 + [ -w "$(dirname "$lock")" ] \ + || { echo "memory: cannot create lock: $lock" >&2; return 2; } + 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"; 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}" + [ $# -le 1 ] && [ "${dir#-}" = "$dir" ] || { echo "usage: memory.sh" \ + "check [--staged] [dir]" >&2; return 2; } + [ -n "$staged" ] || [ -d "$dir" ] \ + || { echo "memory: no memory dir: $dir" >&2; return 2; } + 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) { skip = 0; if ($0 == "") next } + else if ($0 ~ /^#/ || $0 == "---") skip = 0 + else next } + !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_heading_ids() { # <file> <PREFIX> → the entry IDs, any heading level + "$MEM_GREP" -oE "^#+ *$2-[0-9]+" "$1" | sed 's/^#* *//' +} + +_MEM_LEGACY_RE='status|RESOLVED|REVERTED|upstream|resolved|[^a-z]open' +memory_legacy_status() { # <file> <ID> [<end>] → the v1 lexical status line + # (reconcile reads it on a v1 blockers file; `upgrade` proves its verdicts + # against it). Default range: `## ID` to the next `## BLK-`, reconcile's + # own. With <end> (ERE) the range is fence-aware: it stops at the next + # heading matching <end> outside a ``` fence, and that header is not read. + local end="${3:-}" + if [ -z "$end" ]; then + sed -n "/^## ${2} /,/^## BLK-/p" "$1" \ + | "$MEM_GREP" -v '^## BLK-' \ + | "$MEM_GREP" -iE "$_MEM_LEGACY_RE" \ + | tail -1 + return + fi + RE="$_MEM_LEGACY_RE" END_RE="$end" awk -v id="$2" ' + /^```/ { fence = !fence; next } + !fence && $0 ~ ENVIRON["END_RE"] { on = 0 } + !fence && $0 ~ "^## " id " " { on = 1; next } + on && !fence && tolower($0) ~ tolower(ENVIRON["RE"]) { last = $0 } + END { if (last != "") print last }' "$1" +} + +_mem_legacy_open() { # <old file> <ID> → rc 0 when reconcile's v1 reader + local st # lists the blocker open (its status is not RESOLVED); + # upgrade reads the entry's own range, up to a heading of any level + st=$(memory_legacy_status "$1" "$2" '^##* *BLK-[0-9]') + case "$st" in *RESOLVED*|*resolved*) return 1 ;; esac +} + +_mem_index_stated() { # <old> <PREFIX> → IDs whose Index status upgrade + # writes into the body (mem_want): a fact the v1 reader never saw + awk -F'\t' -v p="$2" -v MEMW="$_MEM_WORDS" "$_MEM_AWK"' + FILENAME == ARGV[1] { col[$1] = $3; next } + { split($0, a, / \| /); id = a[1]; sub(/^\| /, "", id); s = a[4] + sub(/ \|$/, "", s) + if (id in col && mem_want(p, col[id], s) != "") print id }' \ + <(_mem_index_table "$1") <(_mem_index_rows "$1" "$2") +} + +_mem_verdict_diff() { # <old> <new> → "ID<TAB>word" per blocker whose open / + local id was now ix # closed verdict moved (word = the old verdict) + ix=$(_mem_index_stated "$1" BLK) + for id in $(_mem_heading_ids "$2" BLK); do + printf '%s\n' "$ix" | "$MEM_GREP" -qx "$id" && continue + # the v1 reader enumerates `## ID` headings only: no verdict to keep + "$MEM_GREP" -qE "^## $id( |$)" "$1" || continue + _mem_legacy_open "$1" "$id" && was=open || was=resolved + memory_closed "$(memory_status_word "$(memory_entry_status "$2" "$id")")" \ + && now=resolved || now=open + [ "$was" = "$now" ] || printf '%s\t%s\n' "$id" "$was" + done +} + +_mem_upgrade_repair() { # <old> <new> <PREFIX> → no blocker loses its closure + # v1 closed, strict reader open (a dialect it cannot read): a status line + # restores it. v1 open, strict closed is the BLK-032..034 fix (prose words + # read as status by the v1 reader): kept, named + local id word + [ "$3" = BLK ] || return 0 + while IFS=$'\t' read -r id word; do + if [ "$word" = open ]; then + echo "memory: $id: v1 reader open, strict reader closed (kept)" >&2 + continue + fi + _mem_insert "$2" "$id" "- **Status ($(_mem_date), upgrade)**: $word" \ + || return 2 + done < <(_mem_verdict_diff "$1" "$2") +} + +_mem_upgrade_oracle() { # <old> <new> <PREFIX> → rc 2 on a lost fact + local o n + [ "$(_mem_heading_ids "$1" "$3")" = "$(_mem_heading_ids "$2" "$3")" ] \ + || { echo "memory: upgrade changed the entry IDs: $1" >&2; return 2; } + memory_check_file "$2" "$3" "" "$1" || 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 != "" && p != "BLK" && s != want) + bad = bad " " id ":" s "!=" want } + END { if (bad != "") { print "memory: upgrade lost:" bad; exit 2 } }' \ + <(_mem_index_table "$1") <(printf '%s\n' "$o") \ + <(printf '%s\n' "$n") >&2 || return 2 + o=$(_mem_verdict_diff "$1" "$2" | awk -F'\t' '$2 == "resolved" \ + { printf "%s ", $1 }') + [ -z "$o" ] || { echo "memory: upgrade moved a verdict: $o" >&2; return 2; } +} + +_mem_upgrade_front() { # <file> → the file; one lacking a frontmatter gets + local t first # the template's (format: 2 is added with the rest) + IFS= read -r first < "$1" + if [ "$first" != --- ]; then + t="$_MEM_LIB_DIR/../templates/memory/${1##*/}" + [ -f "$t" ] || { echo "memory: no template for $1" >&2; return 2; } + awk 'NR > 1 && /^---$/ { print; print ""; exit } + $0 != "format: 2"' "$t" + fi + cat "$1" +} + +_mem_upgrade_headings() { # <file> <PREFIX> → entry headings in the v2 shape + # `## ID — title` stays byte-identical; ` - ` and ` | date | ` separators + # and any other level are rewritten, the title text and the ID kept; a + # heading that would still not be v2 (`### ID amendment`) is left as is + awk -v p="$2" ' + /^```/ { fence = !fence } + fence || !match($0, "^#+ *" p "-[0-9]+") { print; next } + { lead = substr($0, 1, RLENGTH); rest = substr($0, RLENGTH + 1) + if (lead ~ /^## / && rest ~ /^ — ./) { print; next } + sub(/^#+ */, "", lead); d = "" + if (rest ~ /^ [|] /) { rest = substr(rest, 4) + if (match(rest, "^[0-9][0-9/-]* [|] ")) { + d = substr(rest, 1, RLENGTH - 3); rest = substr(rest, RLENGTH + 1) } + rest = " — " rest (d != "" ? " (" d ")" : "") } + else if (rest ~ /^ - /) rest = " — " substr(rest, 4) + cand = "## " lead rest + print (cand ~ "^## " p "-[0-9][0-9][0-9]+ — ." ? cand : $0) }' "$1" +} + +_mem_upgrade_build() { # <file> <PREFIX> <out> → the v2 text, blocker + local front src rows rc=0 # verdicts kept + front=$(mktemp); src=$(mktemp); rows=$(mktemp) + [ -n "$front" ] && [ -n "$src" ] && [ -n "$rows" ] \ + || { rm -f "$front" "$src" "$rows"; echo "memory: no temp file" >&2 + return 2; } + { _mem_upgrade_front "$1" > "$front" \ + && _mem_upgrade_headings "$front" "$2" > "$src" \ + && _mem_index_table "$src" > "$rows" \ + && _mem_upgrade_text "$rows" "$src" "$2" > "$3" \ + && _mem_upgrade_repair "$1" "$3" "$2"; } || rc=2 + rm -f "$front" "$src" "$rows" + return "$rc" +} + +_mem_index_only_table() { # <file> → rc 1 when ## Index holds a non-table + awk '$0 == "## Index" { on = 1; next } # line outside a comment + !on { next } + cm { if (/-->/) cm = 0; next } + /^<!--/ { if ($0 !~ /-->/) cm = 1; next } + /^\|/ { tbl = 1; next } + /^#/ || /^---$/ || (tbl && /^$/) { exit } + /^$/ { next } + { bad = 1; exit } + END { exit bad }' "$1" +} + +_mem_upgrade_ready() { # <file> → rc 0 upgradable, 1 already v2, 2 refused + memory_is_v2 "$1" && { echo "memory: $1 already v2" >&2; return 1; } + _mem_index_only_table "$1" || { echo "memory: $1: ## Index is not a" \ + "table, not upgraded" >&2; return 2; } + _mem_prefix "$1" > /dev/null +} + +_mem_upgrade_file() { # <file> → rc 0 upgraded or already v2, rc 2 refused + local p new rc=0 + _mem_upgrade_ready "$1"; rc=$? + [ "$rc" = 1 ] && return 0 + [ "$rc" = 0 ] || return 2 + p=$(_mem_prefix "$1") || return 2 + new=$(mktemp) || { echo "memory: no temp file" >&2; return 2; } + { _mem_upgrade_build "$1" "$p" "$new" \ + && _mem_upgrade_oracle "$1" "$new" "$p" \ + && cat "$new" > "$1"; } || rc=2 + rm -f "$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 diff --git a/lib/reconcile.sh b/lib/reconcile.sh index a809ce4..c39f3c9 100644 --- a/lib/reconcile.sh +++ b/lib/reconcile.sh @@ -10,6 +10,7 @@ # nor believes a `[x]`/`[ ]` checkbox; it enumerates registry entries from the BODY # `## ID —` headings and decides "done/stale" from git/fs only. It practices what it # 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. # # HONEST LIMITS (graven, do not over-read): # - Deferral detection is LEXICAL (reconcile_deferrals): it catches deferrals MARKED @@ -28,6 +29,9 @@ set -uo pipefail RECONCILE_GREP="${RECONCILE_GREP:-/usr/bin/grep}" # LRN-074: pin grep, never assume GNU flags +# the status parser and classifier are shared with lib/memory.sh (BDR-125 4a) +# shellcheck source=/dev/null +. "$(dirname "${BASH_SOURCE[0]}")/memory.sh" # markers that LEXICALLY signal a deferral/follow-up (honest limit: marked-only) RECONCILE_DEFER_RE='[Dd]efer|[Ff]ollow-?up|[Oo]ut.of.scope|OUT-OF-SCOPE|[Rr]econsider|[Rr]evisit|2e passage|won.t.do|optional\)|one-line ticket' @@ -55,26 +59,30 @@ reconcile_oracle_msg_committed() { # $1 repo, $2 grep → rc 0 if a comm } reconcile_oracle_path_present() { [ -e "${1:?}" ]; } # $1 path → rc 0 if it still exists on disk -# --- registry status: LAST status-bearing line wins (the BLK-008 trap A fell into) --- -# $1 blockers file, $2 id. Echoes the current status line (compound/UPDATE/FINAL aware). +# --- 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 (memory_legacy_status): its dialects (title suffix `— RESOLVED`, +# `date: … · status:`, `**Statut** :`) carry status where the strict parser +# cannot see it. reconcile_blk_current_status() { - # 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 (e.g. BLK-005 "...upstream rename") - # → cross-entry bleed. The entry's own header carries no status, so dropping it is safe. - sed -n "/^## ${2} /,/^## BLK-/p" "$1" \ - | "$RECONCILE_GREP" -v '^## BLK-' \ - | "$RECONCILE_GREP" -iE 'status|RESOLVED|REVERTED|upstream|resolved|[^a-z]open' \ - | tail -1 + if memory_is_v2 "$1"; then memory_entry_status "$1" "$2"; return; fi + MEM_GREP="$RECONCILE_GREP" memory_legacy_status "$1" "$2" } -# blockers whose CURRENT status is not resolved → emits "id<TAB>status" +# 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 + 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") - case "$st" in - *RESOLVED*|*resolved*) : ;; - *) printf '%s\t%s\n' "$id" "$st" ;; - esac + 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 } diff --git a/lib/tests/fixtures/blockers-v1-dialects.md b/lib/tests/fixtures/blockers-v1-dialects.md new file mode 100644 index 0000000..5d45d67 --- /dev/null +++ b/lib/tests/fixtures/blockers-v1-dialects.md @@ -0,0 +1,14 @@ +# 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. + +## BLK-004 - lib-shaped v1 add, resolved +- **Status**: resolved +- **Cause**: `TypeError: x is undefined` diff --git a/lib/tests/fixtures/blockers-v2-status.md b/lib/tests/fixtures/blockers-v2-status.md new file mode 100644 index 0000000..632f424 --- /dev/null +++ b/lib/tests/fixtures/blockers-v2-status.md @@ -0,0 +1,56 @@ +--- +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 diff --git a/lib/tests/memory.test.sh b/lib/tests/memory.test.sh new file mode 100755 index 0000000..08b62af --- /dev/null +++ b/lib/tests/memory.test.sh @@ -0,0 +1,562 @@ +#!/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-v2 "$(sed -n 2p .claude/memory/evals.md)" 'format: 2' +check T9m-pipe-heading "$(grep -c '^## EVAL-001 — pipe dialect (2026)$' .claude/memory/evals.md)" 1 +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 +bash "$MEM" upgrade >/dev/null 2>&1 +check T9o-hyphen-upgraded "$(grep -c '^## EVAL-001 — hyphen dialect$' .claude/memory/evals.md)" 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 +printf -- '---\ntype: evals_registry\nentry_prefix: EVAL\n---\n\n## Index\n\n| ID | Date | Output | Action |\n|----|------|--------|--------|\n| EVAL-001 | 2026-04-01 | a | correct |\n| EVAL-002 | 2026-04-02 | b | correct |\n\n## EVAL-001 — prose action\n- **Action**: fix the prompt next round\n\n## EVAL-002 — body wins\n- **Action**: keep it\n' \ + > .claude/memory/evals.md +bash "$MEM" upgrade >/dev/null 2>&1 +check T9s-eval-index-action-kept "$(sed -n '/^## EVAL-001/,/^## EVAL-002/p' .claude/memory/evals.md | grep -c 'upgrade)\*\*: correct$')" 1 +check T9t-eval-body-wins "$(sed -n '/^## EVAL-002/,$p' .claude/memory/evals.md | grep -c 'upgrade)')" 0 +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 + +# T15 upgrade migrates every measured v1 dialect; the oracle refuses what it +# cannot prove. Blockers fixtures: the open set (reconcile's reader) before +# and after must be the same, the check green, a second run a no-op +v1blk() { # <dir> <body…> → <dir>/blockers.md with a v1 frontmatter + mkdir -p "$1"; { printf -- '---\ntype: blockers_registry\n' + printf 'entry_prefix: BLK\n---\n\n# Blockers\n'; shift; printf '%s\n' "$@" + } > "$(dirname "$1/x")/blockers.md"; } +memory_word_of() { # <file> <ID> → the strict reader's status word + bash -c '. "$1"; memory_status_word "$(memory_entry_status "$2" "$3")"' \ + _ "$MEM" "$1" "$2"; } +openset() { bash -c '. "$1/lib/reconcile.sh"; reconcile_blk_open "$2"' _ \ + "$ROOT" "$1" | cut -f1 | tr '\n' ' '; } +dialect() { # <name> <heading regex expected> — fixture already in d15/<name> + local f="d15/$1/blockers.md" before + before=$(openset "$f") + bash "$MEM" upgrade "d15/$1" >/dev/null 2>&1 + check "T15-$1-rc" "$?" 0 + check "T15-$1-v2" "$(sed -n 2p "$f")" 'format: 2' + check "T15-$1-heading" "$(grep -c "$2" "$f")" 1 + check "T15-$1-check" "$(bash "$MEM" check "d15/$1" 2>&1; echo $?)" 0 + # a ### file: reconcile's v1 reader never saw its entries (asserted below) + [ "${3:-}" = unseen ] && before=$(openset "$f") + check "T15-$1-verdicts" "$(openset "$f")" "$before" + sum=$(cksum < "$f"); bash "$MEM" upgrade "d15/$1" >/dev/null 2>&1 + check "T15-$1-idempotent" "$(cksum < "$f")" "$sum"; } +v1blk d15/hyphen '## BLK-001 - hyphen, resolved' 'Status: resolved' '' \ + '## BLK-002 - hyphen, open' 'Status: open' +dialect hyphen '^## BLK-001 — hyphen, resolved$' +v1blk d15/pipe '## BLK-001 | 2026-05-18 | pipe, resolved' 'Status: resolved' '' \ + '## BLK-002 | 2026-05-19 | pipe, open' 'Status: open' +dialect pipe '^## BLK-001 — pipe, resolved (2026-05-18)$' +v1blk d15/hashes '### BLK-001 — three hashes, resolved' 'Status: resolved' '' \ + '### BLK-002 — three hashes, open' 'Status: open' +dialect hashes '^## BLK-001 — three hashes, resolved$' unseen +# ### entries were never in the v1 reader's set: no repair line, strict read +check T15-hashes-no-repair "$(grep -c 'upgrade)' d15/hashes/blockers.md)" 0 +check T15-hashes-1-resolved "$(memory_word_of d15/hashes/blockers.md BLK-001)" resolved +check T15-hashes-2-open "$(memory_word_of d15/hashes/blockers.md BLK-002)" open +# probe d: a ### entry after a ## one must not leak its status into it +v1blk d15/probed '## BLK-003 — three, open' 'Status: open' '' \ + '### BLK-001 — x' 'Status: resolved' +bash "$MEM" upgrade d15/probed >/dev/null 2>&1 +check T15-probed-no-repair "$(grep -c 'upgrade)' d15/probed/blockers.md)" 0 +check T15-probed-open "$(memory_word_of d15/probed/blockers.md BLK-003)" open +# a heading line quoted inside a ``` fence does not end the entry's range +v1blk d15/fenced '## BLK-003 — three' 'Status: resolved' '```' \ + '### BLK-001 — quoted' '```' 'Status: open' +bash "$MEM" upgrade d15/fenced >/dev/null 2>&1 +check T15-fenced-no-repair "$(grep -c 'upgrade)' d15/fenced/blockers.md)" 0 +check T15-fenced-open "$(memory_word_of d15/fenced/blockers.md BLK-003)" open +# status words inside a ``` fence are not the entry's status +v1blk d15/fstat-a '## BLK-003 — three' 'Status: open' '```' 'Status: resolved' '```' +bash "$MEM" upgrade d15/fstat-a >/dev/null 2>&1 +check T15-fenced-status-a-no-repair "$(grep -c 'upgrade)' d15/fstat-a/blockers.md)" 0 +check T15-fenced-status-a "$(memory_word_of d15/fstat-a/blockers.md BLK-003)" open +v1blk d15/fstat-b '## BLK-003 — three' 'Status: open' '```' \ + '## BLK-009 — quoted' 'Status: resolved' '```' +bash "$MEM" upgrade d15/fstat-b >/dev/null 2>&1 +check T15-fenced-status-b-no-repair "$(grep -c 'upgrade)' d15/fstat-b/blockers.md)" 0 +check T15-fenced-status-b "$(memory_word_of d15/fstat-b/blockers.md BLK-003)" open +# `## ID—x` (no space) is no v1-visible heading: no silent flip +v1blk d15/nospace '## BLK-001—x' 'Status: resolved' '' \ + '## BLK-002 — y' 'Status: open' +sum=$(cksum < d15/nospace/blockers.md) +bash "$MEM" upgrade d15/nospace >/dev/null 2>&1 +check T15-nospace-refused "$?" 2 +check T15-nospace-untouched "$(cksum < d15/nospace/blockers.md)" "$sum" +check T15-nospace-no-repair "$(grep -c 'upgrade)' d15/nospace/blockers.md)" 0 +# RECONCILE_GREP reaches reconcile's v1 pipeline +v1blk d15/v1only '## BLK-001 — v1 file' 'Status: resolved' +printf '#!/bin/sh\necho STUB >&2\nexec /usr/bin/grep "$@"\n' > gstub +chmod +x gstub +stubbed=$(RECONCILE_GREP="$PWD/gstub" bash -c \ + '. "$1/lib/reconcile.sh"; reconcile_blk_current_status "$2" BLK-001' \ + _ "$ROOT" d15/v1only/blockers.md 2>&1 >/dev/null | grep -c STUB) +check T15-reconcile-grep "$([ "$stubbed" -gt 0 ] && echo reached || echo missed)" reached +v1blk d15/suffix '## BLK-001 — suffix — RESOLVED' 'Status: resolved in repo' \ + '' '## BLK-002 — suffix, open' 'Status: open' +dialect suffix '^## BLK-001 — suffix — RESOLVED$' +v1blk d15/datestatus '## BLK-001 — one line' \ + 'date: 2026-06-02 · status: RESOLVED 2026-06-04' '' \ + '## BLK-002 — one line open' 'date: 2026-06-02 · status: open' +dialect datestatus '^- \*\*Status ([0-9-]*, upgrade)\*\*: resolved$' +check T15-datestatus-one-line "$(grep -c 'upgrade)' d15/datestatus/blockers.md)" 1 +v1blk d15/statut '## BLK-001 — fr' '- **Statut** : resolved' '' \ + '## BLK-002 — fr open' '- **Statut** : open' +dialect statut '^- \*\*Status ([0-9-]*, upgrade)\*\*: resolved$' +mkdir -p d15/nofm +printf '# Blockers\n\n## BLK-001 | 2026-05-18 | no frontmatter\n%s\n' \ + '- **Statut** : resolved' > d15/nofm/blockers.md +dialect nofm '^## BLK-001 — no frontmatter (2026-05-18)$' +check T15-nofm-template "$(sed -n 1,3p d15/nofm/blockers.md | tr '\n' '#')" \ + '---#format: 2#type: blockers_registry#' +check T15-nofm-body "$(grep -c '^# Blockers$' d15/nofm/blockers.md)" 1 +# a relative lib path plus -C from another cwd still finds the templates +mkdir -p d15/relpath/.claude/memory +printf '# Blockers\n\n## BLK-001 | 2026-05-18 | no frontmatter\n%s\n' \ + '- **Statut** : resolved' > d15/relpath/.claude/memory/blockers.md +(cd "$ROOT" && bash lib/memory.sh -C "$FIX/d15/relpath" upgrade >/dev/null 2>&1) +check T15-relpath-rc "$?" 0 +check T15-relpath-format "$(grep -c '^format: 2$' d15/relpath/.claude/memory/blockers.md)" 1 +# an em-dash heading stays byte-identical, a dated one included +v1blk d15/keep '## BLK-001 — keep — 2026-05-18' 'Status: open' +bash "$MEM" upgrade d15/keep >/dev/null 2>&1 +check T15-keep-heading "$(grep -c '^## BLK-001 — keep — 2026-05-18$' d15/keep/blockers.md)" 1 +# v1 open, strict reader closed: kept and named (BLK-032..034) +v1blk d15/fix '## BLK-001 — prose' 'Status: Resolved' +err=$(bash "$MEM" upgrade d15/fix 2>&1 >/dev/null) +check T15-fix-named "$(printf '%s\n' "$err" | grep -c 'BLK-001: v1 reader open, strict reader closed')" 1 +# tampered: no status line lands, the oracle refuses, the file is untouched +v1blk d15/tamper '## BLK-001 | 2026-05-18 | lost closure' \ + 'date: 2026-06-02 · status: RESOLVED' +sum=$(cksum < d15/tamper/blockers.md) +err=$(bash -c '. "$1"; _mem_upgrade_repair() { :; }; memory_upgrade "$2"' \ + _ "$MEM" d15/tamper 2>&1 >/dev/null) +check T15-tamper-rc "$?" 2 +check T15-tamper-culprit "$(printf '%s\n' "$err" | grep -c 'moved a verdict: BLK-001')" 1 +check T15-tamper-untouched "$(cksum < d15/tamper/blockers.md)" "$sum" + +# T16 final-review fixes +# lock dir not writable: bounded, named, rc 2 (never a spin) +chmod a-w .git +out=$(timeout 10 bash "$MEM" journal x 2>&1); rc=$? +chmod u+w .git +check T16-lock-rc "$rc" 2 +check T16-lock-named "$(printf '%s\n' "$out" | grep -c 'memory: cannot create lock: ')" 1 +# a bare prefix is not an entry ID +sum=$(cksum < "$B") +bash "$MEM" status BLK "resolved abc" >/dev/null 2>&1 +check T16-bare-prefix-rc "$?" 2 +check T16-bare-prefix-untouched "$(cksum < "$B")" "$sum" +# a bullet Index is refused, byte-identical +mkdir -p t16/bul +printf -- '---\ntype: blockers_registry\nentry_prefix: BLK\n---\n\n# B\n\n' \ + > t16/bul/blockers.md +printf '## Index\n\n- BLK-001 — x (resolved 2026-08-03)\n\n---\n\n' \ + >> t16/bul/blockers.md +printf '## BLK-001 — x\n- **Status**: resolved\n' >> t16/bul/blockers.md +sum=$(cksum < t16/bul/blockers.md) +err=$(bash "$MEM" upgrade t16/bul 2>&1 >/dev/null); rc=$? +check T16-bullet-index-rc "$rc" 2 +check T16-bullet-index-named "$(printf '%s\n' "$err" | grep -c 'blockers.md: ## Index is not a table, not upgraded')" 1 +check T16-bullet-index-untouched "$(cksum < t16/bul/blockers.md)" "$sum" +# check refuses nothing-to-check +bash "$MEM" check --stagd >/dev/null 2>&1 +check T16-check-flag "$?" 2 +err=$(bash "$MEM" check /no/such/dir 2>&1); rc=$? +check T16-check-nodir-rc "$rc" 2 +check T16-check-nodir-named "$(printf '%s\n' "$err" | grep -c 'memory: no memory dir: /no/such/dir')" 1 +# a `- **Date** :` body gets no second Date line +mkdir -p t16/dt +printf -- '---\ntype: blockers_registry\nentry_prefix: BLK\n---\n\n# B\n\n' \ + > t16/dt/blockers.md +{ printf '## Index\n\n| ID | Date | Title | Status |\n|---|---|---|---|\n' + printf '| BLK-001 | 2026-05-01 | x | open |\n\n---\n\n' + printf '## BLK-001 — x\n- **Date** : 2026-05-01\n- **Status**: open\n' +} >> t16/dt/blockers.md +bash "$MEM" upgrade t16/dt >/dev/null 2>&1 +check T16-date-spacing "$(grep -c '^- \*\*Date\*\*' t16/dt/blockers.md)" 1 + +# T12 this repo's registries pass the check +check T12-live-check "$(bash "$MEM" -C "$ROOT" check >/dev/null 2>&1; echo $?)" 0 + +# 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" +echo "PASS=$pass FAIL=$fail" +[ "$fail" -eq 0 ] diff --git a/lib/tests/run-deterministic.sh b/lib/tests/run-deterministic.sh index 1d1f9ff..17bf27e 100755 --- a/lib/tests/run-deterministic.sh +++ b/lib/tests/run-deterministic.sh @@ -155,6 +155,22 @@ if [ -z "$OUT" ]; then ok "stdout empty on rejection (no stale hash)"; else ko " if [ "$BEFORE" = "$AFTER" ]; then ok "HEAD unmoved"; else ko "HEAD moved despite rejection"; fi rm -rf "$R" +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 + echo printf 'RESULT: %d passed, %d failed\n' "$PASS" "$FAIL" [ "$FAIL" -eq 0 ] diff --git a/lib/tests/run-reconcile.sh b/lib/tests/run-reconcile.sh index b4583ce..f9c3e5c 100755 --- a/lib/tests/run-reconcile.sh +++ b/lib/tests/run-reconcile.sh @@ -94,5 +94,21 @@ if reconcile_oracle_msg_committed "$orepo" "ahead commit"; then ok "T7c msg_comm if reconcile_oracle_msg_committed "$orepo" "nonexistent-message-xyz"; then no "T7c msg_committed should be rc≠0 for an absent message"; else ok "T7c msg_committed rc≠0 for an absent message"; fi rm -rf "$OWORK" +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 +case "$(reconcile_blk_current_status "$v1d" BLK-004)" in + *resolved*) ok "T8d lib-shaped v1 blocker (status body line first) reads closed";; + *) no "T8d lib-shaped v1 blocker BLK-004 status not read as resolved";; +esac + echo; echo "================ $pass GREEN / $fail RED ================" [ "$fail" -eq 0 ] && exit 0 || exit 1 diff --git a/settings.json b/settings.json index 523e214..d8e9806 100644 --- a/settings.json +++ b/settings.json @@ -542,5 +542,6 @@ "**Sensitive remote targets**: any namespace, host, database or container whose name carries `prod` or `production` as a whole word or name segment.", "**Sensitive data locations & audiences**: per-project `.env` files (gitignored) hold database, deploy and API credentials; some web projects store customer-submitted form data under a retention policy. Both are personal or client data — never send either to an external service." ] - } + }, + "switchModelsOnFlag": true } diff --git a/skills/bugfix/SKILL.md b/skills/bugfix/SKILL.md index 4b6f95b..b0f6d73 100644 --- a/skills/bugfix/SKILL.md +++ b/skills/bugfix/SKILL.md @@ -272,7 +272,7 @@ A bugfix with an understood root cause is almost always worth one entry: [LRN-XXX — <pattern>] (optionnel) Valider ? (all / blockers-only / edit / skip) ``` -4. Append approved entries + update the Index. Add a line to today's heading in `.claude/memory/journal.md`. +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`. **Language rule**: written entries are ALWAYS English AND caveman — fragments, articles dropped, code/IDs/quoted errors verbatim — per CLAUDE.md "Memory registries" (Always English, always caveman). The interactive gate may mirror the user's language; the appended entries must not. diff --git a/skills/capitalize/SKILL.md b/skills/capitalize/SKILL.md index 5037ea7..d7165c1 100644 --- a/skills/capitalize/SKILL.md +++ b/skills/capitalize/SKILL.md @@ -140,7 +140,7 @@ with no dedup. For every candidate from STEP 1 (and STEP 1B), check whether it is already captured before proposing it. Pull the distinctive keyword(s) of the candidate -and grep the relevant registry (Index + bodies): +and grep the relevant registry (headings + bodies): ```bash # Example: candidate is a learning about "cd -P symlink resolution" @@ -246,14 +246,8 @@ Registries first (in registry order), then the TODO. Registry entries — for each approved: -1. Read the target registry file. -2. Next sequential ID = scan existing `## <PREFIX>-NNN` body headings, take max, - +1 (e.g. last `## BDR-018` → `BDR-019`). Never reuse, never renumber. -3. Append the full entry at the **end** of the body (never rewrite existing - entries — append-only). -4. Add one row to the `## Index` table at the top: `| <ID> | <date> | <title> - | <status> |` (column set varies per file — match that file's header row). -5. Body in **caveman English** per CLAUDE.md memory format: drop articles + +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>"`). +2. Body in **caveman English** per CLAUDE.md memory format: drop articles + filler, fragments OK, short synonyms. Keep code/URLs/error-quotes/IDs/dates verbatim. Entries are ALWAYS English even if the STEP 3 prompt mirrored the user's language. @@ -269,8 +263,7 @@ TODO — for each approved: Write one timeline line under today's `## YYYY-MM-DD` heading — even if every candidate was skipped or already captured. -- Heading exists → append a bullet. -- Missing → create `## YYYY-MM-DD` and write 3-5 bullets summarizing the session. +- `bash "$HOME/.claude/lib/memory.sh" journal "<line>"` per bullet (it creates today's heading when missing). Reference any IDs written this run AND the TODO ops: `BDR-019 + LRN-026 capitalized; checked 1 done, added 1 task.` @@ -302,6 +295,7 @@ Follow `~/.claude/lib/capitalize-commit.md`: - **rc 3** → unsafe git state (detached / merge / rebase) or not a git repo: memory stays in the working tree, surface the helper's stderr, do NOT retry. The flush is safe on disk; STEP 6 must say NOT committed, not ✅-all. + - **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. - **rc 0, hash EMPTY → must NOT happen from this step.** STEP 5 always writes the journal line, so memory is ALWAYS pending at 5B → the helper always has ≥1 change → the hash is non-empty by construction. An empty hash here means diff --git a/skills/feat/SKILL.md b/skills/feat/SKILL.md index e5a2a6c..2898f41 100644 --- a/skills/feat/SKILL.md +++ b/skills/feat/SKILL.md @@ -245,7 +245,7 @@ CAPITALIZE — proposé Valider ? (all / <IDs> / edit / skip) ``` -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`). **Language rule**: written entries are ALWAYS English AND caveman — fragments, articles dropped, code/IDs/quoted errors verbatim — per CLAUDE.md "Memory registries" (Always English, always caveman). The interactive gate may mirror the user's language; the appended entries must not. diff --git a/skills/hotfix/SKILL.md b/skills/hotfix/SKILL.md index be0f3a3..a7a233f 100644 --- a/skills/hotfix/SKILL.md +++ b/skills/hotfix/SKILL.md @@ -231,7 +231,7 @@ Hotfixes are often trivial (typo, config, import) — skip by default. But if th Default behaviour: `CAPITALIZE: hotfix trivial, skip` (no prompt, no output). Ask the user only when there is an actual candidate to propose. -Always append a 1-line entry to today's heading in `.claude/memory/journal.md` (even trivial hotfix — journal is timeline, not signal). +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. **Language rule**: the journal line and any proposed BLK/LRN entries are ALWAYS written English AND caveman — fragments, articles dropped, code/IDs/quoted errors verbatim — per CLAUDE.md "Memory registries" (Always English, always caveman). diff --git a/skills/init-project/SKILL.md b/skills/init-project/SKILL.md index 842302e..1fba43b 100644 --- a/skills/init-project/SKILL.md +++ b/skills/init-project/SKILL.md @@ -298,9 +298,7 @@ capitalizes NOTHING. Do NOT fabricate a BDR to fill the step. Print [ decisions.md ] BDR-XXX — <decision> — <1-line why> Valider lesquels ? (all / <IDs> / edit / skip) ``` -3. Append approved entries to the existing registries (bootstrapped at STEP 5, - in the root commit) + update the Index. Append a journal line under today's - heading in `.claude/memory/journal.md`. +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. **Hash rule — founding decisions carry NO commit hash; use path + date only.** This is by nature, not an omission: a founding decision is made at DESIGN diff --git a/skills/onboard/SKILL.md b/skills/onboard/SKILL.md index c0eaba8..f8cc5d3 100644 --- a/skills/onboard/SKILL.md +++ b/skills/onboard/SKILL.md @@ -1179,7 +1179,7 @@ per the project's commit convention), and verifies every rule is in hash and `git -C <ROOT> show --stat <hash>`, the user decides. S7 — AFTER. `claude -p "/context"` again from `<ROOT>`; append to that -project's `.claude/memory/journal.md` under today's date: `CLAUDE.md +project's journal (`bash "$HOME/.claude/lib/memory.sh" -C <ROOT> journal`): `CLAUDE.md split: <k> sections → .claude/rules/ (<names>), always-on <before> → <after>`. Tell the user the proof step: a fresh session in that project that Reads one file per rule, then `jq -c 'select(.memory_type=="Project" diff --git a/skills/prune-memory/SKILL.md b/skills/prune-memory/SKILL.md index 27f0d10..9c9f244 100644 --- a/skills/prune-memory/SKILL.md +++ b/skills/prune-memory/SKILL.md @@ -80,9 +80,10 @@ age comparisons. Today's date is in the system context. ### A. Obsolete — mark-superseded candidates - Decisions `status: proposed` older than 90 days → propose `status: deprecated` (no follow-up). -- Decisions whose body contains "superseded by <ID>" but Index row still - says `accepted` → propose Index row fix to - `superseded by <that-ID>`. +- 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>"`. - Blockers `status: open` whose root cause matches a commit in last 30 days (grep `git log --since=30.days --grep=<keyword>`) → propose `status: resolved` with commit ref. @@ -108,12 +109,6 @@ age comparisons. Today's date is in the system context. - Detect filler density: count `\b(the|a|an|just|really|basically|actually|simply)\b` matches; if > 5% of word count → bloated. -### D. Index drift -- Body `## (BDR|LRN|BLK|EVAL)-NNN` heading exists but no matching row - in `## Index` table → propose Index backfill. -- Index row exists but body entry missing → propose `status: deleted - (orphaned)` tombstone or removal of Index row (user decides). - ## STEP 2 — PRESENT PLAN ★ MANDATORY STOP Print one block per registry. Example: @@ -127,7 +122,7 @@ PRUNE PLAN — decisions.md (N entries → M after if approved) BDR-901 — example proposed decision — status: proposed since <90+ days ago> → mark: status: deprecated (no follow-up after 90 days) BDR-902 — example decision — body says superseded by BDR-903 - → fix Index: status = "superseded by BDR-903" + → memory.sh status BDR-902 "superseded by BDR-903" [B. Similar — merge] LRN-901 + LRN-902 — SAME concept (two notes on the identical bug) @@ -138,10 +133,7 @@ PRUNE PLAN — decisions.md (N entries → M after if approved) [C. Bloated — inline caveman rewrite] BDR-902 — body 612 words, filler density 7.2% → ~380 expected (-38%) -[D. Index drift] - (none) - -Approve per category? (all / a / b / c / d / edit <ID> / skip) +Approve per category? (all / a / b / c / edit <ID> / skip) ``` Wait for user input. Default = nothing applied. @@ -149,18 +141,22 @@ Wait for user input. Default = nothing applied. ## STEP 3 — APPLY APPROVED CHANGES Order: safe → destructive. +Registry writes follow `lib/capitalize-commit.md` § WRITE (single writer). -1. **Index drift fixes** — no body changes. Backfill missing rows, mark - orphans. -2. **Status flag updates** — Index row status field only. Body untouched. -3. **Merges** — write new merged entry (next-free ID); source IDs marked - `status: superseded by <new-ID>` in Index (body kept verbatim for - history). Merged body: +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: - Preserves all `**Reference**:` lines (dedupe identical paths). - Caveman pass on prose during merge. - Keeps frontmatter fields: id (new), date (today), title, status (accepted), references (union). -4. **Inline caveman compression** — preserve frontmatter exactly (id, +3. **Inline caveman compression** — preserve frontmatter exactly (id, date, title, status, references). Rewrite prose body to fragments: - **NEGATION GUARD (deterministic, overrides every rule below):** never rewrite a sentence containing a negation token (`not`, `never`, `no`, @@ -174,39 +170,13 @@ Order: safe → destructive. - Keep code blocks, URLs, error messages, file paths VERBATIM. - Keep IDs (BDR-XXX, LRN-XXX, commit hashes) verbatim. -After each write, regenerate Index from body when rows changed. - ## STEP 4 — VERIFY ```bash -# Filename → ID-prefix map. Hard-mapped because filenames don't share -# their first 3 chars with the prefix (decisions → BDR, not DEC). -# A prior version derived the prefix via `basename | cut -c1-3`, which never -# matched any heading and made verify a no-op (false-clean signal). -declare -A PREFIX_MAP=( - [decisions]=BDR - [learnings]=LRN - [blockers]=BLK - [evals]=EVAL -) - -# All body entries have Index rows; no orphans -for fname in decisions learnings blockers evals; do - f=".claude/memory/${fname}.md" - [ -f "$f" ] || continue - prefix="${PREFIX_MAP[$fname]}" - - /usr/bin/grep -oE "^## (${prefix})-[0-9]+" "$f" | while read marker; do - id="${marker##\#\# }" - /usr/bin/grep -q "^| ${id} " "$f" || echo "MISSING INDEX: $id in $f" - done - /usr/bin/grep -oE "^\| (${prefix})-[0-9]+ " "$f" | while read row; do - id=$(echo "$row" | awk '{print $2}') - # RED-6 fix: match id at a word boundary (space OR end-of-line) so a - # title-less heading "## BDR-009" is not flagged as a false orphan. - /usr/bin/grep -qE "^## ${id}( |\$)" "$f" || echo "ORPHAN INDEX: $id in $f" - done -done +# 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" # RED-5 fidelity guard (count-based, per-entry x per-category). STEP 0 ensured # a clean tree, so git HEAD is the pre-prune backup. Fails the run if any @@ -271,7 +241,7 @@ PRUNE COMPLETE journal.md : 88 → 62 lines (-30%) evals.md : no candidates -INDEX SANITY: OK +CHECK: OK NEXT: review `git diff .claude/memory/`, then `/commit-change` ``` @@ -302,7 +272,7 @@ NEXT: review `git diff .claude/memory/`, then `/commit-change` | Working tree dirty on registry files | STOP per PRECHECK; tell user to commit/stash first | | User says `skip` at STEP 2 | Exit cleanly, no writes | | Merge produces an entry > 600 words | Re-split — merge was too greedy. Re-prompt user to keep separate. | -| Index sanity FAILED at STEP 4 | Print exact missing/orphan IDs. Do NOT auto-fix — user re-runs or hand-edits. | +| `memory.sh check` FAILED at STEP 4 | Print its culprit lines. Do NOT auto-fix — user re-runs or hand-edits. | | Caveman compression result < 20% of original AND original had code blocks | Revert that entry's compression — flag as needing manual rewrite (likely stripped technical detail). | | Same file already compressed in same session | Skip C-category for that file; warn user that double-pass risks technical drift. | @@ -320,7 +290,7 @@ NEXT: review `git diff .claude/memory/`, then `/commit-change` Baseline RED scenarios were run and their counters are embedded: the RED-2/RED-5/RED-6 guards live in the body above, and `tests/` holds the -fixtures (red3-negation, red4-journal, red6-orphan) plus +fixtures (red3-negation, red4-journal, red6-check) plus `run-deterministic.sh` and `run-behavioral.md`. New rationalizations a subagent finds → add the fixture and its counter to the "Common mistakes" / "Failure paths" tables (`tests/BACKLOG.md` tracks candidates). diff --git a/skills/prune-memory/test-prompts.json b/skills/prune-memory/test-prompts.json index 2f4e111..58b697e 100644 --- a/skills/prune-memory/test-prompts.json +++ b/skills/prune-memory/test-prompts.json @@ -1,5 +1,5 @@ [ - {"id": 1, "prompt": "prune memory — registres trop longs", "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 D) Index drift, presents the per-registry PRUNE PLAN with category-level approval gate, applies only approved changes (mark-superseded never hard-delete), then runs Index sanity verify at STEP 4."}, + {"id": 1, "prompt": "prune memory — registres trop longs", "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."}, {"id": 2, "prompt": "/prune-memory decisions", "expected": "Skill filters audit to decisions.md only — leaves learnings/blockers/journal/evals untouched, presents plan for that single registry, and exits cleanly after applying approved changes with the same append-only + caveman rules."}, {"id": 3, "prompt": "compresse les memoires — mais j'ai des changements pas commités dans .claude/memory/", "expected": "STEP 0 PRECHECK detects dirty working tree on registry files and STOPS immediately: 'Commit or stash pending changes in .claude/memory/ first. Skill writes in-place. Git is the only backup.' — no writes, no plan."} ] diff --git a/skills/prune-memory/tests/fixtures/red6-check/.claude/memory/decisions.md b/skills/prune-memory/tests/fixtures/red6-check/.claude/memory/decisions.md new file mode 100644 index 0000000..cbefce2 --- /dev/null +++ b/skills/prune-memory/tests/fixtures/red6-check/.claude/memory/decisions.md @@ -0,0 +1,13 @@ +--- +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 diff --git a/skills/prune-memory/tests/fixtures/red6-orphan/.claude/memory/decisions.md b/skills/prune-memory/tests/fixtures/red6-orphan/.claude/memory/decisions.md deleted file mode 100644 index a4aacec..0000000 --- a/skills/prune-memory/tests/fixtures/red6-orphan/.claude/memory/decisions.md +++ /dev/null @@ -1,17 +0,0 @@ -# Decisions - -## Index - -| ID | status | date | title | -|----|--------|------|-------| -| BDR-009 | accepted | 2026-06-01 | titleless | -| BDR-010 | accepted | 2026-06-02 | has title | - -## BDR-009 -Body exists. Heading above has NO trailing space and NO title -- this is -the trap. STEP 4 loop-2 checks `^## BDR-009 ` (trailing space required) -and so reports a FALSE ORPHAN even though this body is right here. - -## BDR-010 — Has title -Body exists. Control entry: heading has a title, so STEP 4 finds it and -does NOT false-orphan it. Proves the bug is specific to title-less headings. diff --git a/skills/prune-memory/tests/run-deterministic.sh b/skills/prune-memory/tests/run-deterministic.sh index f6264a5..22dd8a3 100644 --- a/skills/prune-memory/tests/run-deterministic.sh +++ b/skills/prune-memory/tests/run-deterministic.sh @@ -71,16 +71,20 @@ else red 5 "STEP 4 certifies OK after a safety-critical line was deleted (no fidelity check)" fi -# ---- RED-6: STEP 4 verify must not false-orphan a title-less heading -------- -S6="$SANDBOX/red6"; mkdir -p "$S6/.claude/memory" -cp "$HERE/fixtures/red6-orphan/.claude/memory/decisions.md" \ +# ---- 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" && bash step4.sh 2>/dev/null )" -if printf '%s\n' "$out" | grep -qE '^ORPHAN INDEX: BDR-009'; then - red 6 "verify emits FALSE 'ORPHAN INDEX: BDR-009' (body exists; trailing-space bug)" +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 - green 6 "verify does not false-orphan the title-less heading" + red 6 "verify misses the duplicate BDR-009 (no memory.sh check in STEP 4)" fi # ---- RED-7: STEP 2 plan example must use FICTIONAL ids, never live registry ids diff --git a/skills/reconcile/SKILL.md b/skills/reconcile/SKILL.md index 187bb92..58e2290 100644 --- a/skills/reconcile/SKILL.md +++ b/skills/reconcile/SKILL.md @@ -22,7 +22,7 @@ Not for: curating/compressing registries → `/prune-memory`. The skill never ed **REQUIRED ENGINE:** `lib/reconcile.sh` does the mechanical truth-probing. A capable agent CAN reconcile by hand — but burns ~50k tokens, depends on the question being phrased well, and still hits traps (compound status, a disclaimer instead of a check). The engine is deterministic, cheap, repeatable. Source it, then: 1. Enumerate registry entries from BODY headings (`reconcile_enumerate_ids`, never the Index). -2. Per declared item, run the matching oracle (`reconcile_oracle_*`, `reconcile_blk_current_status` = last block wins) and apply `reconcile_verdict`. +2. Per declared item, run the matching oracle (`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) and apply `reconcile_verdict`. 3. Classify into the four categories. 4. **Gate the write-back** (below). @@ -51,4 +51,4 @@ Reconciling the TODO edits a tracked file → never silent. Show the proposed di - Writing a disclaimer ("à vérifier si déjà fait") instead of verifying → the engine verifies, it never hedges-and-advances. ## Validation -`bash lib/tests/run-reconcile.sh` → 25/25, shellcheck clean. Oracle of record = the 2026-06-29 inventory (7 gaps + 3 blocked + 5 deferred + 1 contradiction), fixtures frozen under neutral names in `lib/tests/fixtures/`. +`bash lib/tests/run-reconcile.sh` → 29/29, shellcheck clean. Oracle of record = the 2026-06-29 inventory (7 gaps + 3 blocked + 5 deferred + 1 contradiction), fixtures frozen under neutral names in `lib/tests/fixtures/`. diff --git a/skills/ship-feature/SKILL.md b/skills/ship-feature/SKILL.md index 6ae8ab6..1cf342c 100644 --- a/skills/ship-feature/SKILL.md +++ b/skills/ship-feature/SKILL.md @@ -270,8 +270,8 @@ Feature shipped implies at least one design decision worth capturing. Run this B Valider lesquels ? (all / <IDs> / edit / skip) ``` -4. Append approved entries to the registries. Update the Index table at the top of each file. -5. Append a one-line entry to `.claude/memory/journal.md` under today's date heading (`## YYYY-MM-DD`). +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). **Language rule**: written entries are ALWAYS English AND caveman — fragments, articles dropped, code/IDs/quoted errors verbatim — per CLAUDE.md "Memory registries" (Always English, always caveman). The interactive gate above may mirror the user's language; the appended entries must not. diff --git a/templates/memory/blockers.md b/templates/memory/blockers.md index 0fa558b..e1293c4 100644 --- a/templates/memory/blockers.md +++ b/templates/memory/blockers.md @@ -1,4 +1,5 @@ --- +format: 2 type: blockers_registry entry_prefix: BLK schema: @@ -17,19 +18,13 @@ rules: # Blockers registry (BLK) -## Index +<!-- Written only by `bash ~/.claude/lib/memory.sh add blocker --title "<friction>" +--body-file <file> [--status open]` (it allocates the ID). Entry shape: -| ID | Date | Friction | Status | -|----|------|---------|--------| - -<!-- Append entries below. Template: - -## BLK-XXX - <friction> - -- **Date**: YYYY-MM-DD -- **Friction**: <what was blocked> -- **Real cause**: <root cause> -- **Solution**: <workaround or fix> -- **Status**: open | resolved | upstream + ## 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>"`. --> diff --git a/templates/memory/decisions.md b/templates/memory/decisions.md index a8bf0f9..8896d5b 100644 --- a/templates/memory/decisions.md +++ b/templates/memory/decisions.md @@ -1,4 +1,5 @@ --- +format: 2 type: decisions_registry entry_prefix: BDR schema: @@ -19,22 +20,14 @@ rules: # Decisions registry (BDR) -## Index +<!-- Written only by `bash ~/.claude/lib/memory.sh add decision --title "<title>" +--body-file <file> [--status accepted]` (it allocates the ID). Entry shape: -| ID | Date | Title | Status | -|----|------|-------|--------| - -<!-- Append entries below. Template: - -## BDR-XXX - <title> - -- **Date**: YYYY-MM-DD -- **Status**: proposed | accepted | deprecated | superseded -- **Decision**: <what was chosen> -- **Why**: <motivation> -- **Rejected alternatives**: - - Option A - <why rejected> - - Option B - <why rejected> -- **Reference**: <commit / PR / file> + ## BDR-NNN — <title> [accepted] (YYYY-MM-DD) + - **Decision**: <what was chosen> + - **Why**: <motivation> + - **Rejected alternatives**: <each option, why rejected> + - **Reference**: <commit / PR / file> +Later status: `bash ~/.claude/lib/memory.sh status BDR-NNN "superseded by BDR-NNN"`. --> diff --git a/templates/memory/evals.md b/templates/memory/evals.md index c531351..176701d 100644 --- a/templates/memory/evals.md +++ b/templates/memory/evals.md @@ -1,4 +1,5 @@ --- +format: 2 type: evals_registry entry_prefix: EVAL schema: @@ -18,19 +19,13 @@ rules: # Evals registry (EVAL) -## Index +<!-- Written only by `bash ~/.claude/lib/memory.sh add eval --title "<output>" +--body-file <file> [--status keep]` (it allocates the ID). Entry shape: -| ID | Date | Output | Action | -|----|------|--------|--------| - -<!-- Append entries below. Template: - -## EVAL-XXX - <output> - -- **Date**: YYYY-MM-DD -- **Output**: <what was produced> -- **Method**: <how it was evaluated> -- **Anomalies**: <what is wrong, missing, surprising> -- **Action**: keep | correct | deprecate + ## EVAL-NNN — <output> [keep] (YYYY-MM-DD) + - **Output**: <what was produced> + - **Method**: <how it was evaluated> + - **Anomalies**: <what is wrong, missing, surprising> + - **Action**: <keep | correct | deprecate> --> diff --git a/templates/memory/learnings.md b/templates/memory/learnings.md index 7705a8b..527c5c7 100644 --- a/templates/memory/learnings.md +++ b/templates/memory/learnings.md @@ -1,4 +1,5 @@ --- +format: 2 type: learnings_registry entry_prefix: LRN schema: @@ -16,18 +17,12 @@ rules: # Learnings registry (LRN) -## Index +<!-- Written only by `bash ~/.claude/lib/memory.sh add learning +--title "<abstract pattern>" --body-file <file>` (it allocates the ID). Entry shape: -| ID | Date | Pattern | Applies to | -|----|------|---------|------------| - -<!-- Append entries below. Template: - -## LRN-XXX - <abstract pattern> - -- **Date**: YYYY-MM-DD -- **Pattern**: <what was observed, phrased for reuse> -- **Context**: <where and when, concrete> -- **Future application**: <when to recall this> + ## LRN-NNN — <abstract pattern> (YYYY-MM-DD) + - **Pattern**: <what was observed, phrased for reuse> + - **Context**: <where and when, concrete> + - **Future application**: <when to recall this> -->