---
name: context-strategy
created: 2026-04-19
updated: 2026-04-19-v3
status: review-complete
sources: [gemini, codex]
rounds: [v2-initial, v3-memory-delta]
---

# Context preservation strategy — synthesis

> **v3 update (Apr 2026, post memory-layer review):** two reviewer rounds converged on a new tagline — **"Memory can remind; artifacts decide."** Full v3 delta synthesis in the "v3 Addendum" section at the bottom of this file. All items below represent the v2 baseline that v3 extends; v2 is still valid as written.

## v2 baseline — Consensus

Where both reviewers agreed in the first round (high confidence):

1. **Coverage matrix is oversold.** "5/5 gaps closed" is rhetoric. The reality is *reduced probability*, not closure. Weakest case: judgment failures — documentation never prevents an AI override; only executable tests do.
2. **The numbers are hand-wavy.** Specifically:
   - `-40% tokens` is speculation (likely *increases* token burn at first while retrieval paths warm up).
   - `10-15 min per ADR` understates context-switching cost.
   - `0 silent invariant violations` is only true for correctly encoded, fast-executing tests.
3. **Property-based tests should not be blanket.** Use *selectively*: parsers, transformations, schedulers, state machines, pricing/math, serialization, boundary logic. Everything else gets example-based regression tests or contract tests.
4. **Bring back Semgrep / lightweight static checks.** Both reviewers independently flag this. Cheap, zero-token, fails fast, ideal for structural invariants a solo dev would otherwise need to enforce by hand.
5. **There IS a sixth gap.** Named differently by each reviewer but pointing at the same retrieval/attention problem:
   - Codex: **authority conflict** — when sources disagree, AI picks the wrong one.
   - Gemini: **attention/retrieval failure** — context exists and fires, but AI drops the constraint under prompt saturation.
6. **Failure mode of this proposal itself is known.** Call it "Context Bankruptcy" (Gemini) or "false confidence under partial adoption" (Codex) — same phenomenon: docs multiply, bit-rot, and AI hallucinates from stale sources. *More destructive than no ADRs at all.*
7. **Defer mutation testing.** Only useful on a mature, fast test suite. Skip from Phase 3.
8. **Reduce doc surface area, raise enforcement.** Fewer files, more executables.

## Key insights

- **(Codex)** Add an explicit **source-of-truth priority order**: `tests > spec/requirements > ADRs > code comments > context notes`. Without it, the system produces contradictory guidance.
- **(Codex)** Replace the prose pre-edit grep with a **`criticality.yml` manifest** mapping path globs → invariants/ADRs/must-run tests. Lower ceremony than scattered CLAUDE.md triggers, deterministic routing.
- **(Codex)** Replace the generic "pre-edit ritual" with a **change-impact prompt**: "What invariant could this break? Which adjacent modules participate? Which doc/test did you consult?"
- **(Codex)** Golden/regression approval tests often beat property-based for AI-assisted refactors — they catch "looks cleaner, behaves differently."
- **(Gemini)** **Test-driven context**: put the *why* in test docstrings. When the AI breaks a rule, the failing test output literally prints the architectural constraint.
- **(Gemini)** The "AI Lazy Override" pattern: even with an ADR present, AI can hallucinate a reason to bypass it ("the user asked for Y, so ADR-X must be obsolete"). Only tests prevent this.
- **(Gemini)** Solo-dev stack is three things, not five: in-code comments + CLAUDE.md + executable specs. Everything else is enterprise residue.

## Disagreements

### ADRs — keep vs. kill

- **Codex:** keep `docs/decisions/`, but make ADRs structured with frontmatter (`status, scope, supersedes, last_verified, tags`). Small number, consequential only.
- **Gemini:** kill standalone ADRs entirely. Merge decisions into module docstrings and existing `docs/context/` files. The `docs/context/` + `docs/decisions/` split guarantees one rots.

**My assessment:** Middle ground. Gemini's concern about doc split-brain is legitimate. But a docstring can't fully capture "alternatives rejected and why." The answer: **very few ADRs (3-5 lifetime per project)**, reserved for catastrophic-trap decisions only. For narrower decisions, Gemini is right — put it in the module docstring. Add the frontmatter Codex specified so the ones we keep stay searchable.

### Pre-edit lookup — ritual vs. automation

- **Codex:** replace with change-impact *prompt* and a path-based manifest.
- **Gemini:** kill manual lookup entirely; force context injection via Claude hooks.

**My assessment:** Both are right that manual grep is fragile. The synthesis: use hooks (PreToolUse on Edit/Write in sensitive paths) that read `criticality.yml` and inject relevant invariants + ADRs automatically. Then the change-impact prompt runs as a gated step. No manual ritual.

### How many `docs/context/` files

- **Codex:** 8 is probably too many. Collapse to `invariants.md` + optional ADRs + thin architecture overview.
- **Gemini:** don't add `docs/decisions/` on top; consolidate.

**My assessment:** Both right. The 8-file layout is structurally sound but in practice several will stay stubs or rot. Shrink to: `architecture.md`, `invariants.md` (new, absorbs gotchas), `interfaces.md`, `operations.md`. Everything else moves to docstrings or gets deleted.

## Action items (ordered for the deck rewrite)

1. **Fix all overclaims.** "Closed" → "materially reduced." Drop `-40% tokens`. Drop `0 silent violations`. Be honest about cost numbers (20-45 min per ADR when including review/linking).
2. **Add the 6th gap.** Name it *attention/retrieval failure* with "authority conflict" as a flavor of it. The two reviewers converge on this point.
3. **Restructure the layers from 5 to 4.**
   - Comments / docstrings (with embedded "why")
   - Slim `docs/context/` (architecture, invariants, interfaces, operations only)
   - Optional ADRs for catastrophic traps (3-5 per project lifetime, with frontmatter)
   - Executable guardrails (unit tests + Semgrep/static checks + *selective* Hypothesis + golden tests)
4. **Introduce `criticality.yml` manifest.** Maps path globs → invariants/ADRs/must-run tests. Replaces scattered CLAUDE.md trigger prose. Consumed by a PreToolUse hook for auto-injection.
5. **Bring Semgrep back into the deck.** Slot it as the enforcement layer for structural invariants. Not governance-heavy; 3-10 cheap rules per project.
6. **Make Hypothesis selective.** Remove the "top 3-5 per project" blanket rule. Use it only for parsers / transforms / state machines / pricing / serialization. Default to example-based or golden tests.
7. **Add authority order.** New slide: `tests > spec > ADRs > comments > context notes`.
8. **Replace pre-edit grep slide with change-impact + hook-driven injection.** Drop the 4-step manual ritual.
9. **Test-driven context.** New slide pattern: test docstring = the "why." Failing test = enforced architectural constraint with explanation.
9a. **Update `/qatests` skill with a conditional WHY-docstring rule.** Narrow scope — don't rewrite the skill. Add one rule: *if* the test is in a `criticality.yml` `must_run` list, or the filename matches `test_invariants*` / `test_golden*`, the generated test must include a `WHY:` line in its docstring stating (i) the architectural constraint it enforces and (ii) the ADR or `invariants.md` anchor it references. Routine unit tests keep their current docstring style. Rationale: `/qatests` owns test authorship; the WHY rule belongs with it, not split across `context-save`. Keeps skill responsibilities clean.
10. **Add explicit failure-mode slide.** Name it "Context Bankruptcy." The meta-risk of the proposal.
11. **Drop quarterly mutation testing from Phase 3.** Defer indefinitely; mention only as a maturity-stage option.
12. **Update industry-positioning slide.** Semgrep moves from "not doing" to "bringing back." Revise the honest self-assessment accordingly.

## Adjacent primitive — agent memory systems (post-review addition)

Research into April 2026 OSS launches surfaced a distinct category worth naming, even though it's deferred:

- **MemPalace** (Apr 6, 2026) — MIT-licensed. 96.6% on LongMemEval (100% hybrid — highest-scoring free option). Verbatim conversational storage + vector search. Local-first, zero API cost. Claude Code-compatible via MCP.
- **Hermes Agent v0.7.0** (Apr 3, 2026) — OSS agent stack with pluggable memory providers.
- **Mem0, Letta (ex-MemGPT), Zep, Cognee, LangMem** — established OSS frameworks; varying strategies (extraction vs verbatim, graph vs vector, etc.).
- **Cloudflare Agent Memory** (Apr 13–17, 2026) — managed service, not OSS; public beta Apr 30.

**Positioning relative to this strategy:** these systems persist *conversational/episodic* memory (user preferences, prior-session context, cross-repo patterns). Our strategy persists *project knowledge* (rules, decisions, invariants) inside the repo. They are **additive layers, not substitutes**.

**Decision:** defer to Phase 3+. Revisit if Claude Code's built-in auto-memory proves insufficient for cross-session/cross-project continuity. MemPalace is the highest-probability candidate due to its MCP integration and open-source licensing. Context noted on The AI Daily Brief: *Harness Engineering 101* (memory as harness layer) and *Operator's Bonus* (Apr 18 — "memory gap holding the whole field back").

## Risks flagged

- **Partial adoption = worst outcome.** Stale ADRs and half-written invariants cause more damage than no system at all. Enforce "write a new ADR or delete an old one" as the only two options on every save.
- **Property-based test decay.** Slow, flaky, hard to debug tests get commented out within weeks. Restrict scope or don't start.
- **Hook complexity.** Claude Code hooks injecting context can surprise users and bloat context windows. Test cost per triggered edit before enshrining.
- **ADR staleness.** Without `last_verified` frontmatter and a periodic re-verify prompt, ADRs become the liability Gemini warns about.

## Recommendation change

**Original proposal:** Phase 1 / 2 / 3 over ~4 weeks.

**Revised:**
- **Phase 0 (1 day)** — slim `docs/context/` to 4 files; fix overclaims; write this review into the source of truth.
- **Phase 1 (3-4 days)** — update `context-save` skill with authority order, criticality.yml, change-impact prompt, Semgrep slot. Update `/qatests` with the conditional WHY-docstring rule. Write *one* ADR as the format template.
- **Phase 2 (1 week)** — per-project: identify 1-3 catastrophic-trap decisions (become ADRs); 3-10 Semgrep rules; 1-3 property-based tests (only where domain warrants); wire criticality.yml.
- **Phase 3 (defer)** — mutation testing skipped until test suite is fast and stable.

One-line summary (borrowed from Codex): **fewer documents, stronger authority, more selective tests, a little more enforcement.**

---

# v3 Addendum — memory layer review

*(Second reviewer pass, April 2026. Both Gemini and Codex re-reviewed focused on the agent-memory delta.)*

## One-line outcome

**"Memory can remind; artifacts decide."** — Codex's final policy line. Both reviewers effectively endorse this posture.

## Consensus (high confidence)

1. **Agent-memory is a parallel axis, not inserted into the linear authority order.** Both reviewers independently arrive here. Keep `tests > spec > ADRs > comments > context notes` intact. Memory is a retrieval/recall aid, not a source of truth.

2. **Pull MemPalace into Phase 2, not Phase 3+.** The "defer" label in v2 was reflexive. OSS / MIT / local / zero-cost / MCP-native / no infrastructure makes the operational bar trivial. Narrow pilot on one project first, opt-in writes, expiry/recency bias.

3. **Write-back rule is mandatory.** If a memory changes future behavior across sessions, it must be promoted to one of: spec, ADR, guardrail, or context note. Memory is "remember to look here," not "this is now policy." Gemini calls this a Promotion Protocol; Codex calls it a write-back rule — same mechanism.

4. **Context Bankruptcy becomes a new subclass, not the same risk.** Token bankruptcy improves (less redundant context feeding) but *semantic / governance* bankruptcy worsens (hidden accumulation outside reviewable artifacts). Codex's name: "shadow context." Gemini's name: "stateful drift." Same phenomenon, worth an explicit slide.

5. **Superpowers plugin: subset only, not all 14 skills.** Both reviewers agree. Converging subset:
   - repo / context scan (semantic search / deep grep)
   - change impact analysis
   - test selection / risk-based verification
   - spec-to-checklist extraction
   - regression review / diff audit
   - workspace / status summarization
   Avoid anything that adds autonomous behavior, new memory surfaces, or workflow abstraction in Phase 1.

6. **Sub-agent architectures with separate memory domains: NOT in the deck.** Both reviewers reject codifying this now. Operational detail / premature architecture. Revisit later if evidence emerges it's needed.

## Disagreement

### `/qatests` WHY-docstring rule

- **Gemini:** keep in Phase 1. Zero-infra, high-leverage, makes future guardrails understandable. Tests without WHY become "magic behavior."
- **Codex:** demote out of Phase 1 as a blanket rule. Easy to cargo-cult. Narrow to: non-obvious invariants, surprising failure modes, externally constrained behavior.

**My synthesis:** keep in Phase 1 *but narrow the trigger conditions*. The rule fires only when the test is (a) in `criticality.yml` `must_run`, OR (b) filename matches `test_invariants*` / `test_golden*`, OR (c) test asserts behavior that would constitute a catastrophic-trap regression. Routine unit tests get normal docstrings. This honors both concerns: gets the high-leverage discipline in Phase 1 without broad cargo-culting.

## Key insights

- **(Codex)** *Memory can remind; artifacts decide.* Operational one-liner, deserves to be a deck tagline.
- **(Gemini)** *Promotion Protocol* — at milestone / end of debug session, explicitly ask the agent to promote structural learnings to CLAUDE.md or ADRs and forget the episodic memory. This is the concrete write-back mechanism.
- **(Codex)** *Phase 1 should harden truth sources, not improve agent convenience.* This frames why memory belongs in Phase 2 even though it's easy to install.
- **(Gemini)** Memory "directly attacks the attention/retrieval failure gap" (Gap 6 from v2). It won't fix judgment failures, but it shrinks the surface on Gap 6.
- **(Codex)** Memory adoption risks include *cross-project contamination* and *temptation to skip writing docs/ADRs because the agent remembers*. Both are silent failure modes that deserve explicit countermeasures.

## Action items (deck updates)

1. **Slide 11 (Authority order)** — change from linear-only to **linear stack + parallel memory axis**. Memory axis labeled "recall aid only — never final authority."
2. **Slide 20 (Context Bankruptcy)** — add a "Shadow context" / "Stateful drift" subclass specific to the memory layer. Include countermeasure: mandatory write-back.
3. **Slide 21 (Rollout)** — move MemPalace pilot from "Phase 3 / deferred" into **Phase 2 (narrow pilot, one project, opt-in writes, expiry/recency bias)**.
4. **Slide 23 (Adjacent primitive — agent memory)** — update framing from "defer to Phase 3+" to "Phase 2 pilot with write-back rule." Add the Promotion Protocol as a concrete practice. Add "Memory can remind; artifacts decide" as a tagline.
5. **NEW slide — Memory handoff rule** — between slide 23 and 24. Covers: what memory may store, what memory may *not* be the only home for, the write-back trigger, and the Promotion Protocol.
6. **Slide 25 (Recommendation)** — include the new tagline: "Memory can remind; artifacts decide."
7. **Slide 22 (What we're not doing)** — update Superpowers framing: "Phase 1 adopts a narrow subset (repo scan, change impact, test selection, spec-to-checklist, regression diff audit). Not the full 14 skills."
8. **Slide 29 (Tests/* deep dive)** — narrow the `/qatests` WHY-docstring rule to three trigger conditions (criticality.yml `must_run`, filename pattern, catastrophic-trap regression) rather than "all guardrail tests."

## Stale-memory reconciliation — `context-save` extension

When Claude queries memory and gets a result contradicted by a test/ADR/current code, the authority order handles the in-session conflict (test wins). But the *stale memory still exists* in MemPalace. Without cleanup, next session inherits the bad recall.

**Decision:** extend `context-save` with a reconciliation step. No new skill needed.

- Claude flags every memory it overrode this session (e.g., "memory said X, test said Y, trusted the test").
- At Stop/SessionEnd, `context-save` reviews the flags and prompts the user: *forget* (stale), *update* (new reality), or *keep* (memory was fine; context changed).
- Never auto-delete — always ask. Over-eager forgetting is worse than stale memories.
- This completes the memory lifecycle: query at turn start → override in authority conflict → reconcile at session end.

## Risks flagged

- **Shadow context** (Codex) — hidden accumulation outside reviewable artifacts. Countermeasure: mandatory write-back + quarterly memory review.
- **Stateful drift** (Gemini) — stale memories survive past code changes. Countermeasure: expiry/recency bias, explicit "forget" instructions during Promotion Protocol.
- **Cross-project contamination** (Codex) — memory learned on project A applied to project B where it doesn't fit. Countermeasure: per-project memory wings; don't share a global vault across unrelated repos.
- **Over-trust** — users/agents come to treat memory as authoritative. Countermeasure: explicit authority-order training, memory clearly labeled non-authoritative in every UI surface.
- **Doc-writing skipped** — "the agent remembers, why write it down?" Countermeasure: write-back rule + enforce "no durable decisions in memory alone" during context-save hook.

## Updated rollout

- **Phase 0 (1 day)** — slim docs/context to 4 files; fix v1/v2 deck overclaims; write this synthesis into repo.
- **Phase 1 (3-4 days)** — update `context-save` skill with authority order (linear + parallel memory axis), criticality.yml, change-impact prompt, Semgrep slot. Update `/qatests` with narrowed WHY-docstring rule. Adopt the Superpowers subset (repo scan, change impact, test selection, spec-to-checklist, regression diff audit). Write *one* ADR as template.
- **Phase 2 (1 week, per project)** — identify 1-3 catastrophic-trap ADRs, 3-10 Semgrep rules, 1-3 property-based tests. **MemPalace pilot: one project only**, opt-in writes, expiry/recency bias, per-project wing. Exercise the Promotion Protocol at least once.
- **Phase 3 (deferred indefinitely)** — mutation testing, knowledge graphs, enterprise ADR governance, broader sub-agent memory domain architecture.

## One-line summary

v2 said "fewer documents, stronger authority, more selective tests, a little more enforcement."
v3 adds: **"memory can remind; artifacts decide — with mandatory write-back."**
