← Back to Portal ↑ Claude Artifacts

Context Save

Decisions outlive code. Why each project records its requirements, architecture and rules in docs/context/ — and how the context-save skill keeps them current
Measured 2026-11-11 from claude-shared@3827c28 · skill skills/context-save/ · hooks hooks/context-save-*.sh
8
Default files
4
Hook scripts (7 events)
3
Pressure tiers
85
Projects with docs/context/
74
Declare the menu
3
On version 2

❓ Why save context — the decisions matter more than the code

Code shows what the system does today. It does not show why — which requirement each part fulfils, which decision ruled out the obvious alternative, which rule must never break. That why is the asset; the code is one implementation of it.

Every enhancement is built on top of the ones before it. A change made without knowing what the existing code is there for can break a requirement an earlier enhancement delivered — and nothing complains:

Enhancement A
a requirement and a decision, implemented in code
→
Enhancement B, months later
changes the same code for a new need
→
A is silently broken
B works and its tests pass; nothing recorded what A needed from that code
Before changing code, a session asksWithout saved contextWith it
Why is this code here?guessed from the coderequirements.md names the requirement it fulfils
Can I simplify this?looks redundant, gets removedarchitecture.md records the decision and what it ruled out
What must still hold after my change?whatever the tests happen to coverinvariants.md — INV-nn rules, each named by a test
Was this approach already tried?tried again, fails againthe decision record says so
How context-save protects earlier work
  • Captured when decided the reasoning exists only inside the session that made it; hooks fire before that session loses it
  • Pinned to tests a change that breaks an earlier requirement fails a named test, not a user
  • Short enough to read one home per fact, under 200 lines per file — cheap to check before every change
  • The asymmetry code can be rebuilt from decisions; decisions cannot be rebuilt from code. Design goal, not yet measured: with the code gone and these files intact, an AI rebuilds about 75% of the application in one pass
The rule this page serves: every change is checked against the decisions that came before it. context-save is how those decisions get written down — at the moment they are made, in the repo they govern.

🛡️ Saved is not obeyed — make the decisions enforceable

Having the context is not the same as obeying it. A rule can be in the prompt and still lose: two sources disagree and the model follows the wrong one (authority conflict), or a long session drowns it (attention decay). More documents do not fix this. Two things do.

1 · An authority order — who wins a conflict

Tests › Requirements (requirements.md) › Decision records and invariants (docs/adr/, invariants.md) › Code comments › Other context notes (architecture.md, operations.md, …)

  • The rule if a test enforces it, the test is right
  • Rank ≠ importance the order settles disagreements only: a description that contradicts a test or a requirement is the one that is out of date — which is why context-save keeps the notes current
  • Agent memory a recall aid on a separate axis, never an authority. Memory can remind; artifacts decide.
  • Memory may hold preferences, work in progress, pointers, hypotheses, dead ends
  • Memory must not own decisions, invariants, interfaces, runbooks, risk boundaries — promote them into the files, or they become shadow context nobody reviews
2 · Executable guardrails — rules that fail loud
Kind of ruleGuardrail
Most rulesUnit and integration tests — known inputs, known outputs. The default
Forbidden pattern, required wrapperStatic checks (Semgrep): 3–10 cheap rules per project, zero tokens
High-risk outputGolden / approval tests — catch "looks cleaner, behaves differently", the classic AI refactor failure
Parsers, transforms, schedulers, state machines, pricing, serializationProperty-based tests (Hypothesis) — selectively, never the default

Put the why in the test. A docstring that names the constraint and the decision behind it turns a failure into an explanation: the failing output tells the next session exactly which earlier requirement it just broke.

Load the right rules before the edit

criticality.yml at the project root maps sensitive paths to their invariants, decision records and must-run tests, each with an authority tier. In the strategy, a PreToolUse hook injects them before an edit and asks what could this change break?

Decision records stay rare

Everyday decisions follow the routing below: architecture.md or requirements.md. A separate record in docs/adr/ is only for catastrophic-trap decisions — the ones a future change could silently undo with no way back. About 3–5 in a project's lifetime.

Strategy vs adoption. These concepts come from the context strategy (v3, April 2026, Review Board synthesis). Its proposal to cut docs/context/ to four files became a per-project option; the skill ships the eight (see How the set changed over time). On this host today: invariants.md with INV-nn anchors is in every default set; 4 projects keep decision records in docs/adr/ (cicd, research, aiagentchat, agents/memory); 1 project has a criticality.yml (agents/memory), where agent-memory recall drops a memory whose subject a higher-tier rule covers. The edit-time injection hook is not deployed anywhere yet.

🔁 How it works

context-save writes the durable part of each session into the project's own repo, at the moments a session is about to lose it.

Session work
code, decisions, fixes, lessons
→
Trigger
a hook at a context-loss boundary, or /context-save
→
Route
each fact to exactly one file
→
docs/context/*.md
committed with the code it describes
→
Next session
the CLAUDE.md menu points to it
CLAUDE.md holds directives — what to do and not do — and loads every session. docs/context/ holds knowledge — how the system works — and is read when a task needs it. A fact kept in both drifts; keep it in one.

🕹️ Three ways it runs

🔔 Automatic
Claude Code only — plugin hooks
  • When Stop, SubagentStop, PreCompact, SessionEnd, and when you type /clear /compact /exit /quit
  • What a checklist nudge; a block when code changed and context pressure is high
  • Safety net a mechanical wip.md snapshot once pressure passes 30%
✍️ Manual
/context-save
  • What full review of every file, plus two manual-only steps: write a missing menu, slim an oversized CLAUDE.md
  • Invoke Claude Code /context-save · Codex $context-save · Antigravity /context-save
  • Ends with a test-gap scan that offers /qatests
🌱 Bootstrap
/context-save init
  • What creates docs/context/ from templates/ (9 templates on disk: the 8 defaults plus gotchas.md)
  • Then fills in what is already known and stages it
  • Existing project? /context-save-upgrade instead
A save chained from another workflow — /refocus-complete, codex-handoff, an orchestrator recording a worker's changes — behaves like a hook save: it skips the menu and slim steps.
Codex and Antigravity run no context-save hooks. Nothing nudges, blocks or snapshots there; the skill runs only when you ask for it. Save before you end the session.

📚 The eight files — one question each

The set is not arbitrary: these are the questions someone would have to answer to rebuild the system. A fact that answers none of them probably does not belong in docs/context/.

#FileAnswers
1requirements.mdWhat must the system do? Business rules, workflows, product constraints
2architecture.mdHow do the parts connect? Components, boundaries, data flow
3interfaces.mdWhat are the contracts? APIs, schemas, events, config surfaces
4conventions.mdHow is code written here? Patterns, naming, libraries, layout
5security.mdWho may do what? Auth, secrets, trust boundaries
6operations.mdHow does it run? Deploy, containers, ports, env, networks
7testing.mdHow is it proven? Critical paths, regression checks, coverage gaps
8invariants.mdWhat must never break? Hard rules with INV-nn anchors that tests cite
🪤 Gotchas — routed, not filed
accreting observations are the wrong shape for a reference doc
  • agent-memory available agent-memory write --memory-kind gotcha --subject "<topic>" "<lesson>" — when the menu sets gotchas_via_memory: true or the CLI is on PATH
  • Otherwise a plain docs/context/gotchas.md
  • Cross-project lesson the shared troubleshooting skill
Tree (version: 2)HoldsTrue until
docs/context/how the application behavesthe code changes
docs/runbooks/procedures a person runs, one file per subsystemthe procedure changes
docs/releases/CI-parsed; never touched by this skill—
Projects inherit the eight and declare only what they add; an extension or runbook file opens with a one-line > Purpose: … header. invariants.md differs in kind: the other seven describe, it forbids.

🕰️ How the set changed over time

WhenChangeWhy
2026-03First versioned skill: eight files, the eighth was gotchas.md. The 200-line ceiling and the 75% design goal were already thereQuestions someone must answer to rebuild the system
2026-04-19The context strategy proposes cutting to four files (architecture, invariants, interfaces, operations), folding gotchas into invariantsFewer documents, stronger authority
2026-04-24invariants.md replaces gotchas.md as the eighth; gotchas move to agent-memory; each project picks its files from a menu in CLAUDE.mdGotchas accrete like a log; invariants are rules a test can cite. The four-file cut became a per-project choice, not a global one
2026-07-16The eight become an inherited default; projects declare only additions (extends:), files: can still trimRe-declaring the list in every project let defaults drift, and a mistyped name silently dropped a file
2026-09-05Version 2: docs/runbooks/ as a second tree, and the "not a doc" ruleA file can only lag live state, and procedures serve a different reader than behaviour
2026-09-17Mechanical wip.md snapshot; pressure tiers lowered to 30 / 50 / 70%A session hit 98% of its window before Stop blocked, and saved nothing
2026-11-09A manual save writes a missing menu and slims a CLAUDE.md over 40,000 charactersKnowledge was piling up in the one file that loads every session

Source: git history of skills/context-save/ in claude-shared (from 2026-06-14) and claudecodeconfig (before). The set will keep changing; the skill is authoritative, this table is history.

📐 Size limits — and why

WhatLimitWhy
Each docs/context/ or runbook fileUnder 200 lines. Full means prune, not appendAn unbounded file becomes an append-only log, and nobody reads a log. The prune forces the real work: deciding what still matters. A short file is also cheap enough to read before every change — the check the Why section depends on
Project CLAUDE.mdSlim when over 40,000 characters, to about 30,000CLAUDE.md loads in full on every turn of every session; docs/context/ loads only when a task needs it. Claude Code warns once all loaded instruction files pass 150,000 characters, and the user and platform layers already take about 45,000 on an administrator account before any project file. Every extra character costs tokens on every turn and dilutes attention to the rules that matter
Each entryOne fact, one file, one self-contained bulletA fact kept in two places disagrees with itself within months; a bullet that needs its neighbours cannot be pruned safely
Dates on entriesNoneGit already records when. A dated line is perishable state, which does not belong in the file at all

🧭 Routing — which one file?

First question, always: does this stay true until someone changes the code or the procedure?

No it is not a doc
Current state (live tag, schema level, what is armed, a count) → name the script or endpoint that answers it. Action item → a GitLab issue. Anything carrying a date is the author telling you it is perishable.
Yes — how the app behaves → docs/context/
Pick the file by the question it answers (table above). Non-obvious behaviour → a gotcha.
Yes — steps a person runs deploy, recover, verify
docs/runbooks/<subsystem>.md on a version: 2 project; otherwise operations.md.
Not about this project other homes
Cross-project lesson → troubleshooting skill. A user's correction or preference → feedback memory in ~/.claude/projects/…/memory/. Compose, Dockerfile, deploy.sh, CI, dependency or SQL change → also docs/architecture/ if the project has it (architecture-docs skill).
Route by the fact's audience, never by who found it: a bug in the app discovered during a deploy is a docs/context/ fact, not a runbook line.

🗂️ Per-project menu — CLAUDE.md frontmatter

---
context-save:
  extends: [signal-lifecycle, options-exec]  # APPENDED to the default 8
  files: [architecture, operations]          # optional: REPLACES the default
  gotchas_via_memory: true                   # gotchas → agent-memory
  version: 2                                 # also maintain docs/runbooks/
  routing:                                   # optional topic → file map
    trading-rules: tradingrequirements.md
---
How the effective set is built
  1. Start from the default 8 — unless files: is present, which replaces them with a subset.
  2. Append extends: — the recommended knob. List only what you add.
  3. Auto-discover: any non-canonical docs/context/*.md is maintained too. Still list it in extends:.
  4. On version: 2, add every docs/runbooks/*.md.

No frontmatter? The default set plus discovered files applies, and the next manual /context-save writes exactly that as the menu. Hooks never write it.

🔔 Hooks and context pressure (Claude Code)

EventScriptDoes
Stop · SubagentStop · PreCompact · SessionEndcontext-save-check.shMeasures pressure and the diff; nudges or blocks (tiers below)
UserPromptSubmitcontext-save-on-prompt.shOn /clear /compact /exit /quit: blocks when the project has docs/context/, more than 15 lines of git diff HEAD and no doc update — unless a wip.md under 15 minutes old covers it
PreToolUse Bash|Edit|Write|NotebookEditcontext-save-wip-pretooluse.shRefreshes wip.md mid-turn at medium pressure or above, checked after every 250,000 bytes of transcript growth. Silent; never blocks
SessionStartcontext-save-wip-resume.shShows a leftover wip.md and asks the agent to fold it into a real save, then delete it
SignalPressureBehaviour
docs/context/ or docs/runbooks/ already touchedanySoft reminder
Any sessionmedium >30%wip.md written mechanically — zero model tokens
>15 diff lines, no doc touchedhigh >50%Blocks stop; asks for the full save
>15 diff lines, no doc touchedcritical >70%Blocks stop; asks for one plain sentence — no skill load, no tool calls
>15 diff lines, no doc touchedlow / mediumStrong reminder naming the 8 files
Minor or no code changeanySoft reminder / checklist
How pressure is measured
  • Tokens input + cache-creation + cache-read, from the transcript's own usage records
  • Window inferred from peak usage: the 200k floor, or a 1M-class window
  • Fallback a transcript-size heuristic, only when there are no usage records
  • PreCompact bumped one tier: compaction loses detail regardless
  • Shared logic hooks/lib/context-pressure.sh
Why a mechanical wip.md

A session reached 98% of a 1M window before Stop ever blocked: one autonomous turn chained dozens of tool calls, and Stop samples only between turns. The save it then asked for was too large for the room left, the next call failed with Prompt is too long, and nothing was saved.

So the hooks now write the snapshot themselves — branch, git status, recent commits, the last prompt — beside the transcript (~/.claude/projects/<slug>/wip.md), never in the repo. It is overwritten on each fire and never deleted automatically. Regression suite: hooks/test-context-save-wip.sh, 30 cases.

Every fire injects the same checklist: decisions → architecture.md / requirements.md · lessons → gotchas or troubleshooting · user corrections → feedback memory · code that moved architecture, interfaces, security or operations → the matching file · build and deploy changes → docs/architecture/.

✍️ A manual /context-save, in order

  1. Tree check. git fetch; is docs/ clean and current? Clean → write in the working tree. Behind upstream or already dirty → write anyway, then commit and push on context/<user>-<YYYY-MM-DD>.
  2. Menu. No context-save: frontmatter → write extends: (only if CLAUDE.md is uncommitted-clean). A menu without version: 2 → a one-line v1 notice; v2 is never run for you.
  3. Size. claudemd_slim.py measure; over 40,000 characters → slim first (next section).
  4. Review. Read every file, compare with the project, fix what is stale or missing, prune what is no longer true.
  5. Test-gap scan. Changed source files without tests → offer /qatests for just those gaps.
  6. Lessons. Project gotcha → agent-memory or gotchas.md; cross-project → troubleshooting.
Writing is never refused; losing it is. A dirty tree is visible to nobody, and some repos hard-reset their working tree on deploy. That is why a save that cannot ride the next commit goes to a pushed context/ branch.
Never stash, checkout -- or reset another session's uncommitted docs/ edits — they go onto the context/ branch with yours.
Context-only changes are bundled with the code commit they describe — no separate "update docs" commits. The one exception is the slim's move and repoint commits.

✂️ Slimming an oversized CLAUDE.md (manual only)

CLAUDE.md loads every session; docs/context/ does not. A large CLAUDE.md is usually knowledge captured in the wrong place. Over 40,000 characters (wc -m), a manual save moves the descriptive part out, verbatim, to about 30,000.

What moves
  • Keep anything that tells the agent what to do or not do: deploy/CI and migration rules, environment and access, safety gates (real money, prod data, destructive commands). Unsure → keep.
  • Move what describes how the system works
  • Receivers new extension files under 200 lines, each with > Purpose: … Moved verbatim from CLAUDE.md., added to extends:
  • Left behind a "before touching X, read docs/context/Y" table, one-line forms of safety rules, and a moved-from → now-in table in docs/README.md
  • Precondition clean, current tree with nothing staged, and no unmerged context/* branch already carrying a slim. Otherwise it skips and says why.
# read-only helper
SLIM=~/.claude/skills/claude-shared/skills/context-save/lib/claudemd_slim.py
$SLIM measure             # exit 1 = over 40,000
$SLIM sections --by-size  # heading blocks, line ranges (fence-aware)
$SLIM verify              # lossless check vs HEAD
$SLIM verify --base HEAD~1   # on the committed move
Two commits, one branch
  1. Move — cut by line range with a script, never retyped. verify must exit 0: every removed line reappears once, in order. It fails on rewording, summarising, a dropped line, a reorder, or a receiver over 200 lines. Fix the move, never the check.
  2. Repoint — fix references to moved headings. Checked by its diff, not by verify, because it rewords on purpose.

Helper tests: lib/test_claudemd_slim.py, 57 passing.

📏 Writing rules

Must
  • Terse bullets and tables, no prose
  • Factual true now, or marked [PLANNED]
  • Scoped one home per fact
  • Pinned a fact worth acting on names the test that keeps it true (INV-nn)
  • Bounded under 200 lines per file; prune when full
  • Atomic each bullet reads on its own
Must not
  • Filler, pleasantries, narrative
  • Timestamps on entries — git has them
  • Duplicates of CLAUDE.md directives
  • Empty section headers
  • Separate context-only commits
Status markers
- [IMPLEMENTED] PostgreSQL primary store
- [PLANNED] Redis session cache
- [DEPRECATED] MongoDB connector

⌨️ Commands and key paths

Command / pathWhat
/context-saveFull save, plus menu and slim steps
/context-save initScaffold docs/context/ for a new project
/context-save-upgradeEdit the menu, or migrate gotchas.md into agent-memory (one-time, idempotent)
/context-save-upgrade v2Human-reviewed durable/perishable pass that adds docs/runbooks/. Needs a clean, current tree; never automatic
claude-shared/skills/context-save/SKILL.mdThe skill — authoritative over this page
claude-shared/skills/context-save/templates/Scaffolding templates
claude-shared/skills/context-save/lib/claudemd_slim.pySlim helper: measure · sections · verify
claude-shared/hooks/context-save-*.shThe four hook scripts; registered in hooks/hooks.json
claude-shared/hooks/lib/context-pressure.shPressure tiers and the wip.md writer
claude-shared/hooks/test-context-save-wip.shHook regression suite

⚠️ Rules that bite

  • Hooks are Claude Code only. In Codex or Antigravity, nothing reminds you to save.
  • Commit what you save. A gitpull or a deploy that hard-resets the tree destroys uncommitted context.
  • wip.md is not a context file. It is a perishable snapshot outside the repo; fold it into a real save, then delete it.
  • v1 is not broken. version: 2 is opt-in, human-reviewed, and never run by a hook.
  • A slim never runs from a hook, never rewords, and never skips verify.
  • This page describes; the skill decides. Where they differ, SKILL.md wins — and this page is out of date.