How to keep AI coding sessions coherent across time — minimizing tokens, errors, and silent regressions.
Claude Code · solo-developer strategy · April 2026 · v2 (post review board)
A future enhancement looks reasonable. The change compiles. Tests pass. A silent constraint — a workaround, a rate limit, a legal requirement — has just been erased.
Re-exploring the repo every session.
Lost invariants, broken assumptions, regressions.
Critical rules depend on memory — and memory decays.
Targeted loading. Don't re-read the whole repo to answer a narrow question.
Preserve the why across sessions so enhancements don't silently regress.
Critical rules enforced, not remembered.
Part 1
Three layers of context capture, already in use. Each has a job. Each has limits.
Localized why at the constraint site. Seen whenever the file is read. Travels with refactors.
Snapshots of current state: architecture, interfaces, conventions, security, ops, testing, gotchas, requirements.
Scoped triggers: "before modifying X, read Y." Tells the AI what to load for sensitive areas.
Maintained by the context-save skill, invoked via Stop / PreCompact / SessionEnd hooks.
Read)git blame / commit historydocs/context/ files (must match the task)The right-hand column is where most gaps live.
Five were identified up front. The sixth surfaced during the review board pass — and it's the most common.
Comments/docs lag reality.
Reason was in someone's head. Never written.
Directive names one area; change lands elsewhere.
Invariant lives in the interaction between files.
AI reads the rule, "improves" past it.
Context loaded. Trigger fired. AI still drops it — from saturation or from conflicting sources.
Having the context isn't the same as obeying it. Gap 6 is why doc-only strategies plateau. The fix isn't more documents — it's stronger signal: an explicit authority order, plus executable guardrails that fail loud.
Codex named it authority conflict; Gemini named it attention/retrieval failure. Same gap.
Part 2
Original proposal had 5 layers. Review board pushed back. The revised shape is 4 layers, 1 manifest, 1 authority order — fewer documents, stronger enforcement.
| Primitive | Holds | Job |
|---|---|---|
| 1. Comments / docstrings | Localized why + test docstrings as spec | Seen on every Read. Failing test output prints the constraint. |
| 2. Slim docs/context/ 4 files | architecture.md, invariants.md, interfaces.md, operations.md |
Current-state snapshot. No more 8-file sprawl. |
| 3. ADRs rare | Catastrophic-trap decisions only | 3–5 lifetime per project. With frontmatter. Everything else stays in docstrings. |
| 4. Executable guardrails | Unit + Semgrep + selective Hypothesis + golden tests | The only layer that actually forces respect. Fails loud. |
Supporting: criticality.yml (path → invariants/ADRs/tests manifest) drives a PreToolUse hook that auto-injects relevant context. No manual grep ritual.
Linear stack for canonical truth. Separate parallel axis for agent memory — because memory is a recall aid, not an authority.
Canonical truth — linear precedence
Parallel axis — behavioral recall
Rule: if a test enforces it, the test is right. Memory can remind; artifacts decide. Memory never wins conflicts with any written artifact — if forced to linearize, it sits below context notes.
Linear stack: Codex (v2). Parallel memory axis: both reviewers (v3). Without this separation, people over-trust memory.
status, scope, supersedes, last_verified, tags.last_verified is the staleness killer. Re-verify quarterly.# See ADR-0007. Indexed in criticality.yml.Gemini wanted ADRs killed. Codex wanted them structured. The revision keeps them — but at a drastically lower volume, so they can't rot into a graveyard.
Context Bankruptcy. Unverified ADRs multiply faster than they decay. AI hallucinates from stale sources. Worse than no ADRs at all.
Ruthless scope. Write a new ADR or delete an old one — no other options on save.
---
id: ADR-0007
status: Accepted
scope: price-services
supersedes: null
last_verified: 2026-04-19
tags: [ib, yahoo, data-routing, catastrophic-trap]
---
# IB for realtime, Yahoo for historical
## Context
IB HTTP API times out on 5Y weekly bars. Yahoo has a 15-minute delay.
## Decision
IB for live/delayed. Yahoo for historical.
## Alternatives rejected
- All IB: fails on 5Y weekly requests
- All Yahoo: 15m delay unacceptable for live
## Consequences
Two code paths in price services. Fallback order: IB → Yahoo → DB cache.
## Invariant test
tests/test_price_routing.py::test_historical_uses_yahoo
Frontmatter makes it searchable, staleable, and supersedable. last_verified is the single most important field.
Both reviewers agreed: docs don't prevent judgment failures. Only tests do. And not every rule needs the same tool.
Default. Example-based. Known inputs, known outputs. Fast feedback.
3–10 cheap rules per project. Forbid dangerous patterns, require wrappers. Zero-token enforcement.
For high-risk outputs. Catches "looks cleaner, behaves differently" — the classic AI refactor failure.
Only for parsers, transforms, schedulers, state machines, pricing/math, serialization. Not the default.
Dropped from the default stack: quarterly mutation testing. Defer until the test suite is fast and stable; it's triage-heavy and easy to abandon.
Put the why in the test docstring. When the AI breaks the rule, the failing test output literally prints the architectural constraint.
def test_historical_uses_yahoo():
"""Historical price requests must route to Yahoo, never IB.
WHY: IB HTTP API times out on 5Y weekly bars (see ADR-0007).
The fallback chain is IB-live -> Yahoo-historical -> DB-cache.
If this test fails, you've broken the data-routing invariant.
"""
client = PriceClient()
result = client.get_history("AAPL", period="5Y", interval="weekly")
assert client.last_source == "yahoo", (
"Historical request reached IB - violates ADR-0007 data routing"
)
The failing assertion becomes a self-describing error. AI can't "improve past" what a test explicitly names.
criticality.yml + PreToolUse hook replaces manual ritualBoth reviewers flagged the 4-step manual grep workflow as fragile. Replace it with deterministic path-based routing.
# criticality.yml - maps code paths to required context
- path: "src/services/ib_client.py"
invariants: [docs/context/invariants.md#data-routing]
adrs: [ADR-0007]
must_run: [tests/test_price_routing.py]
- path: "src/trading/**"
invariants: [docs/context/invariants.md#trading-rules]
adrs: [ADR-0002, ADR-0005]
must_run: [tests/test_trading_invariants.py]
change_impact_prompt: true # force AI to answer: what could this break?
A Claude Code PreToolUse hook reads this before any Edit/Write, auto-injects the listed context, and (when flagged) prompts the change-impact question. No scattered CLAUDE.md triggers.
Reviewers were right: "closed" was rhetoric. The honest claim is reduced probability, unevenly.
| Gap | Today | Revised design | Dominant closer |
|---|---|---|---|
| Staleness | low | high | Tests + last_verified |
| Never-captured rules | low | medium | ADRs + docstrings |
| Wrong-trigger scope | medium | high | criticality.yml hook |
| Cross-cutting behavior | low | high | Semgrep + property tests |
| Judgment failures | low | medium | Executable guardrails only |
| Attention / retrieval (Gap 6) | low | medium | Authority order + test docstrings |
No gap reaches "closed." Judgment failures and Gap 6 are the hardest — they plateau at "medium" because models can always over-ride context; only failing tests are non-negotiable.
| Change | Setup (one-time) | Ongoing | Tokens |
|---|---|---|---|
| Slim docs/context/ | ~1 day (absorb gotchas → invariants.md; delete stubs) | ~10 min per material change | Lower (4 files vs 8) |
| ADRs (rare) | 2–4 hours (template + 3–5 backfills per project) | 20–45 min per ADR including review + linking | Neutral |
| Semgrep checks | 1–2 hours per project (3–10 rules) | ~15 min per new rule | Zero in conversation |
| Hypothesis (selective) | 1–3 hours per applicable surface | Only when contracts change | Zero in conversation |
| criticality.yml + hook | 3–4 hours (hook script + initial paths) | Grows with project | Variable — measure per triggered edit |
Original deck said "ADRs: 10–15 min" — both reviewers said that's unrealistic. Revised: 20–45 min including the context switch to draft + link properly.
Gaps materially reduced
"Closed" was overstated.
Judgment + Gap 6 plateau at medium.
Silent invariant violations
For encoded invariants.
Unencoded rules still at risk.
Token savings
Claimed -40% was speculation.
Measure before claiming.
The original deck claimed measurable token savings and "5/5 gaps closed." Review board pushed back on both. Revised: honest reductions, not marketing numbers.
v2 identified one subclass (doc bankruptcy). v3 adds a second once memory enters the picture — shadow context, hidden accumulation outside reviewable artifacts.
last_verified — quarterly re-verify or retireOne-line policy (Codex): Memory can remind; artifacts decide.
/qatests WHY-docstring rule (triggered, not blanket)v2 was 2 weeks to working state. v3 keeps the same timeline; MemPalace fits inside Phase 2 at no infra cost.
Designed for 450K+ file monorepos. Overkill for single-developer apps.
Valuable when multiple agents/humans query shared ADRs. Solo-dev can grep the folder directly via the criticality manifest.
No review boards. No approval workflow. ADRs are five-minute files. Keep ceremony low or no one uses them.
Originally dismissed as "too narrow." Review board independently recommended bringing it back. Cheapest enforcement layer for structural invariants.
Not the full 14 skills (too much ceremony). Phase 1 adopts a narrow subset: repo/context scan, change-impact analysis, test selection, spec-to-checklist, regression diff audit. Avoid anything that adds autonomous behavior or new memory surfaces.
v2 said “defer to Phase 3+.” Both reviewers pushed back — MemPalace is OSS/MIT/local/zero-cost/MCP-native, so the integration tax is trivial. v3 pulls it into Phase 2 as a narrow pilot with explicit write-back rules.
Project knowledge — rules, decisions, invariants. Repo-bound. Travels with the code.
Episodic memory — user prefs, prior-session context, cross-repo patterns. Vector store. Travels with the user.
Memory can remind; artifacts decide.
If a memory changes future behavior across sessions, it must be written back to an artifact (spec, ADR, guardrail, context note). Memory is “remember to look here,” never “this is now policy.”
| Project | Released | Notable |
|---|---|---|
| MemPalace | Apr 6, 2026 new | MIT. 96.6% on LongMemEval (100% hybrid — best free option). Verbatim storage + vector search, local-first, zero API cost. MCP-compatible with Claude Code. |
| Hermes Agent v0.7.0 | Apr 3, 2026 new | OSS agent stack. Pluggable memory providers. 32k+ stars. |
| Mem0 | Established | Universal memory layer. AI-driven extraction (summaries), not verbatim. |
| Letta (ex-MemGPT) | Established | OS-inspired virtual context. Moves info between immediate & long-term stores. |
| Zep, Cognee, LangMem | Established | Frameworks with varying retrieval strategies (graph, temporal, hierarchical). |
| Cloudflare Agent Memory | Apr 13–17, 2026 | Managed service (not OSS). Profile-based API. Public beta Apr 30. |
Covered on The AI Daily Brief: Harness Engineering 101 (memory as harness layer) · Operator's Bonus Apr 18 (“memory gap holding the whole field back”).
The mechanism that keeps shadow context from accumulating. Gemini: Promotion Protocol. Codex: write-back rule. Same thing.
invariants.md)At milestone end, explicitly tell Claude:
“Promote structural learnings into ADRs/invariants. Forget the episodic memory.”
context-save at Stop/SessionEnd prompts: forget / update / keepWithout this, memory becomes shadow context — durable decisions or stale assumptions living outside reviewable artifacts. Worse than no memory at all.
Revised deck is even more mainstream than v1. The review board's pushback converged us toward established patterns (Semgrep, authority order, selective property testing, path manifests).
| Component | Industry status | Note |
|---|---|---|
| CLAUDE.md + scoped rules + skills | consensus baseline | Standard Claude Code pattern. |
| Slim docs/context/ (4 files) | consensus | Gemini + Codex both pushed for collapse. 8 files was sprawl. |
| Rare structured ADRs | de facto standard | ICSE 2026 confirms. Frontmatter + scarcity is the pragmatic form. |
| Authority order | standard (under-taught) | Codex's contribution. Well-known in ML systems engineering. |
| Semgrep / cheap static checks | mainstream | Used across many solo and team projects. We were wrong to exclude. |
| Selective property tests | emerging mainstream | Anthropic-endorsed. Both reviewers said: selective, not blanket. |
| criticality.yml manifest | synthesis | Distinctive of this plan. Codex's framing, solo-dev tuning. |
| Low-ceremony solo framing | our synthesis | Industry targets teams. We deliberately stay small. |
Net: mainstream toolkit, selectively assembled. The novelty is in the scarcity discipline, not the primitives.
Phase 0 + Phase 1 ship in <1 week. Phase 2 adds per-project ADRs, Semgrep rules, property tests, and a narrow MemPalace pilot (opt-in writes, per-project wing, Promotion Protocol exercised). Phase 3 — mutation testing, knowledge graphs, enterprise governance — deferred indefinitely. Honest on what's closed: reductions, not closures. Shadow context is the new meta-risk; the write-back rule is the countermeasure.
One edit cycle, start to finish. ■ you · ■ framework (automated) · ■ Claude
"Add retry to scraper fetch."
recalls: user prefs, prior-session context, cross-repo patterns — lead generator only, never overrides an artifact
reads: criticality.yml (path → required context)
injects: matching invariants, ADRs, must-run test names
asks Claude: what invariant could this break? adjacent modules? doc/test consulted?
applies authority order: tests > spec > ADRs > comments > context
Semgrep · unit · golden · Hypothesis (where applicable)
fail → Claude reads failing test docstring (carries the why) → fixes → back to step 6
Commit message references touched ADRs / invariants where relevant.
decides: update invariants.md? new ADR? update last_verified? reconcile stale memories? write non-durable prefs to memory with expiry?
writes: durable → ADR/invariant/context; ephemeral → MemPalace w/ expiry; stale-detected → forget or flag
Normal code review. Invariants already enforced by tests — you're checking intent, not policing rules.
Key property: steps 2–4 and 6 are framework-enforced, not Claude-remembered. The ritual disappears; the enforcement doesn't.
Memory axis (dashed circles): recall after you ask, write-back at session end. Never authoritative. Memory can remind; artifacts decide.
Every asset referenced in the prior flow, mapped to its filesystem home and the step(s) it serves. NEW = added in v2. REVIVED = originally excluded, brought back after review.
CLAUDE.md directives, authority order step 5 criticality.yml path → context manifest steps 2–4 NEW .semgrep.yml structural guardrails step 6 REVIVED src/**/*.py code + # See ADR-NNNN comments steps 1,5,9 tests/ test_*.py unit + integration (default) step 6 test_invariants.py Hypothesis (selective) step 6 NEW test_golden_*.py golden / approval step 6 NEW — docstrings carry the WHY — failing tests print constraint steps 6→7 NEW docs/ context/ slim snapshot (4 files, not 8) architecture.md system overview step 3 invariants.md cross-cutting rules (absorbs gotchas) step 3 NEW interfaces.md contracts & schemas step 3 operations.md deploy/run/config step 3 decisions/ rare ADRs with frontmatter ADR-0001-*.md catastrophic-trap decision steps 3,7 NEW ADR-0007-*.md ” steps 3,7 NEW
~/.claude/skills/ context-save/ SKILL.md step 8 decides what to record on Stop / SessionEnd .claude/settings.json steps 2,8 PreToolUse + Stop hooks .claude/hooks/ pre_tool_use.py steps 2–4 NEW reads criticality.yml injects relevant context fires change-impact prompt
git commit log step 7 diff & trace of change ADR / invariant refs in commit message ~/.mempalace/ turn start, step 8 v3 ChromaDB + SQLite + filesystem queried at turn start (recall aid) written at step 8 via Promotion Protocol per-project wing, expiry bias
Assets outside the project (~/.claude/skills/, .claude/hooks/) are cross-project — write once, every repo benefits.
Assets inside the project (criticality.yml, docs/, tests/) are per-repo and evolve with the code.
criticality.yml — what it containsLives at the project root. Read by the PreToolUse hook on every Edit/Write. One entry per sensitive path or pattern.
| Field | Meaning |
|---|---|
path |
File pattern (glob). Matches files whose path fits; this entry activates when Claude edits one. ** = any depth. |
invariants |
Anchors into invariants.md. Rules that must always hold for this code (e.g. "orders ≤ 5% of account"). |
adrs |
ADR IDs. Hook loads the full decision record so Claude sees the why and the alternatives that were rejected. |
must_run |
Test files that must run (and pass) when this code is touched. Failing tests loop back to Claude with the docstring as explanation. |
change_impact_prompt |
If true, hook forces Claude to answer "what invariant could this break? which modules participate?" before writing code. |
owner |
Person or team responsible for this surface. Vestigial for solo devs; useful when project has mixed contributors or AI agents. |
Order matters: first matching path wins. Put specific paths before wildcard ones.
- path: "src/services/ib_client.py"
invariants: [docs/context/invariants.md#data-routing]
adrs: [ADR-0007]
must_run: [tests/test_price_routing.py]
change_impact_prompt: false
- path: "src/trading/**"
invariants:
- docs/context/invariants.md#trading-rules
- docs/context/invariants.md#position-sizing
adrs: [ADR-0002, ADR-0005]
must_run:
- tests/test_trading_invariants.py
- tests/test_golden_quick_trade.py
change_impact_prompt: true # always ask; trading is high-risk
owner: websurfinmurf
- path: "sql/migrations/*.sql"
invariants: []
adrs: []
must_run: [tests/test_migration_idempotency.py]
change_impact_prompt: true # one-way change; flag every time
- path: "src/scraper/**"
invariants: [docs/context/invariants.md#scraper-rate-limits]
adrs: [ADR-0003]
must_run: [tests/test_scraper_fallback.py]
Terms used on this slide
invariants.md.
* = any filename chars. ** = any directory depth. Used to match groups of files.
tests/* — QA coverage + architectural enforcement
Not a separate test framework — this is QA. The /qatests skill handles coverage; this strategy adds the intent layer via test docstrings. v3 narrowing The WHY-docstring rule is triggered, not blanket — routine unit tests keep their default docstring style.
| Type | Role | Tool |
|---|---|---|
| Unit / integration | Standard QA coverage — happy path, edges, errors, security | pytest via /qatests |
| Golden / approval | Catch "looks cleaner, behaves differently" after AI refactor | pytest-approvaltests |
| Property-based selective | Formal invariants over input space | Hypothesis |
| Contract / schema | API/event boundaries | Pydantic / JSON schema |
| E2E | Cross-component flows | pytest + docker-compose |
/qatests covers six QA categories (happy, edge, error, integration, regression, security).
This strategy adds one thing: docstring carries the why — but only when the test fires on a narrow trigger.
WHY-docstring fires when:
test is in a criticality.yml must_run list, OR filename matches test_invariants* / test_golden*, OR asserts catastrophic-trap regression. Routine unit tests: default style.
# tests/test_trading_invariants.py
from hypothesis import given, strategies as st
from src.trading import sizing
def test_quick_trade_rejects_oversized_position():
"""Quick Trade orders must not exceed 5% of account value.
WHY: Risk management (see ADR-0005).
Oversized positions are a catastrophic-trap scenario.
Violating bypasses sizing.accept_order().
"""
assert not sizing.accept_order(size=10_000, account=100_000)
@given(account=st.floats(min_value=1000, max_value=1e9),
size=st.floats(min_value=0))
def test_position_sizing_property(account, size):
"""Property: accepted orders <= 5% of account value.
WHY: ADR-0005 invariant must hold for arbitrary inputs.
If this test fails, you've broken the sizing guard.
"""
if sizing.accept_order(size, account):
assert size <= 0.05 * account
docs/decisions/* — what goes hereReserved for catastrophic-trap decisions — changes a future enhancement could silently undo, causing a one-way mistake. Target: 3–5 lifetime per project. Everything else goes in docstrings.
CLAUDE.md)
---
id: ADR-0005
status: Accepted
scope: trading
last_verified: 2026-04-19
tags: [risk, position-sizing]
---
# Position size capped at 5% of account
## Decision
Order paths MUST pass `sizing.accept_order()`.
Rejects any size > 0.05 * account_value.
## Alternatives rejected
- Trust UI: single point of failure
- Backend soft warning: easy to click through
- Per-symbol caps: wrong risk model
## Consequences
- No direct order creation in handlers
- Property test enforces the bound
- Bypass requires ADR-0005 supersede
If you can't articulate "the alternative was considered and rejected because …", it's not an ADR — it's a docstring.
If approved, Phase 0 + Phase 1 ship in <1 week: slim docs/context, fix overclaims, update context-save skill with authority order (linear + parallel memory axis) + criticality.yml + change-impact prompt, narrow the /qatests WHY rule, adopt the Superpowers subset, scaffold an ADR template. Phase 2 runs per-project and includes the MemPalace pilot under the write-back rule.
📄 Full review synthesis (v2 + v3): context-strategy.final.md — two reviewer rounds, consensus, disagreements, action items, risks.
Sources & external references: adr.github.io · AgDR · Hypothesis · Anthropic PBT · Semgrep · ICSE 2026 ADR context · Context rot
Review board: Gemini 3.1 Pro + Codex (GPT-5.x). Two rounds — v2 (baseline strategy) and v3 (memory-layer delta). Full synthesis at docs/reviews/context-strategy.final.md.