# Claude Code: Self-Improving Global Configuration Instruction

Version 2, revised after expert review. See "Known limitations" at the end for what this does not do.
Source: https://egbdigital.com.au/blog/self-improving-claude-code-config
Free to use, copy, and adapt. No attribution required.

**What this is:** a curation system for your Claude Code configuration. It keeps the always-loaded
rules lean, evidence-backed, and current against the official docs, and it prunes what stops earning
its place.

**What this is not:** a system that measures whether a config change made the agent better. Nothing
here runs an experiment or scores an outcome. Version 1 of this instruction implied more than that,
and the corrections are in "Known limitations". Read that section before you rely on any of it.

**How to run:** Open a fresh Claude Code session (any directory), use your strongest model in plan
mode, and paste everything below the line. Expect Phase 1 to be conversational: an audit report and
a batch of keep/update/drop questions, before anything is built.

---

Build the global Claude Code configuration at `~/.claude/` into a lean, self-curating system. Operate on `~/.claude/` regardless of the current working directory. This instruction must work equally on a mature personalized config or a completely fresh install. Proceed in two phases: AUDIT first, then IMPLEMENTATION only after my approval of the audit findings.

═══ GROUND RULES (apply to both phases and to every command you build) ═══

EVIDENCE RULE. Every finding, every proposed change, and every lesson must cite something you actually read: a file path and line, a transcript entry with its session file and timestamp, or a URL you fetched. You may not cite your own recollection of what happened in a session, your impression of how well work went, or your sense of which rules were followed. A model is not a reliable witness to its own behaviour, least of all inside the session it is reporting on. If you cannot produce a citation, the finding does not go in the report. Say "no evidence found" instead.

DEFAULT TO KEEP. Absence of evidence for a rule is not evidence against it. A rule that no citation contradicts stays exactly as it is, unchanged, and is not mentioned in the report. Do not propose a change to demonstrate thoroughness. Churn is a failure mode of this system, not a sign it is working. A run that proposes nothing is a valid and common outcome; say so plainly and stop.

SAMPLE SIZE. A single session proves nothing. Do not derive a rule, promote a lesson, or delete anything on the basis of one occurrence. Thresholds are defined per operation below, and they are minimums, not targets.

NEVER GRADE THE SESSION YOU ARE IN. Any audit, curation, or health check must run in a session whose only job is that audit, started fresh, with no implementation work in its history. Where the tool allows it, run it on a different model from the one that did the work being audited. If you are asked to audit and the current session has been doing implementation work, say so and refuse to grade it: report on files and transcripts only, and tell me to re-run in a clean session.

NATIVE-FIRST. Before building anything specified below, check whether current Claude Code natively provides that capability (built-in auto memory, per-project topic files, a MEMORY.md index, native checkpointing, and the built-in `/insights` session-analysis report). If it does, USE the native feature as the foundation and adapt this spec's commands to operate ON it. Never build a parallel custom system duplicating a built-in; two systems doing the same job will drift. Report each native substitution in the audit.

ROLES, NOT NAMES. Every directory and file name in this spec (references/, patterns.md, stack-notes.md, and so on) describes a ROLE, not a required name. If an existing structure already plays that role under a different name (for example a docs/ directory as the on-demand layer), ADOPT the existing name and structure. Do not rename or migrate it, since its name may be baked into other commands, gitignores, and cross-references. Map spec-role to existing-name in the audit report.

═══ PHASE 1: AUDIT (no file changes in this phase) ═══

- Assume NOTHING about the user, their stack, their projects, their tooling, or their preferences. Derive facts only from files you actually read in `~/.claude/`. Where something needed is absent, ASK. Never fill gaps with guesses.
- Read every existing file in `~/.claude/` (CLAUDE.md, supporting .md docs, templates, commands/, settings.json, hooks). On a fresh install with nothing present, say so, skip to the audit summary, and note the build will be baseline-only.

Produce an AUDIT REPORT with these sections. Every item in every section carries its citation.

1. HEALTH GRADE: score the existing config against Claude Code best practices.
   - Bloat: is CLAUDE.md carrying content that shouldn't be always-loaded (catalogs, walkthroughs, examples, one-off notes)? Give the measured line and byte count, and what percentage is rules versus detail. If bloated, say so plainly and quantify the reduction available.
   - Rule quality. Apply this test to each rule, and quote the rule with your answer: "describe, in one sentence, an observation in a transcript or a file that would prove this rule was violated." A rule is VAGUE if and only if you cannot complete that sentence. "Write good code" fails, because no observation proves it. "Never commit directly to master" passes, because a commit on master proves it. Report only the rules that fail, each with a proposed testable rewrite or a recommendation to delete. Do not report a rule as vague because you would have worded it differently.
   - Contradictions: two rules that cannot both be satisfied by the same action. Quote both, and the action that trips them. Overlapping wording is not a contradiction; do not report it.
   - Dead weight, which means one of exactly these: a hook whose script file does not exist on disk; a command referencing a path that does not exist; a doc listed in the reference index with no matching file, or a file with no index entry; a plugin in settings.json that fails to load. Verify each by checking the path. Do not report anything as dead because it "appears unused".
   - Structure: is there separation between always-loaded rules and on-demand detail? For each reference-index trigger, state what observable condition fires it. A trigger nobody can evaluate ("read when relevant") is dull; propose sharper wording.

2. OUTDATED REQUIREMENTS CHECK: for each substantive requirement or preference stated in the existing CLAUDE.md (tool choices, model policies, workflow rules, banned or mandated practices), test it against this definition and nothing else.
   A rule is STALE if one of these is true and you can cite it:
   (a) it names a tool, model, flag, command, or file path that no longer exists or has been renamed;
   (b) the current official Claude Code documentation or changelog now contradicts it;
   (c) it mandates a workaround for a limitation that has since been fixed;
   (d) it duplicates a capability the tool now provides natively.
   A rule is NOT stale because it is old, because it has not come up recently, or because you could phrase it more elegantly. Age and low usage are not evidence. Updating for the sake of updating is the exact failure this definition exists to prevent.
   Consult the current official Claude Code documentation and changelog (via web search or fetch if available) rather than relying on training knowledge alone. For each rule that meets the definition, QUOTE it, cite the specific doc or changelog line that makes it stale, and ask whether to keep, update, or drop it. Batch these questions together. Rules that do not meet the definition are not mentioned at all.

3. PERSONALIZATION INVENTORY: every custom command, hook, skill, template, and workflow found. These are the user's investments; none may be lost or broken without explicit agreement. For each: keep as-is / integrate with the new structure (for example, any sync, backup, or propagation command must be extended to cover new directories and git state) / flag as redundant and ask.

4. PROPOSED TARGET STATE: summarize what Phase 2 will build, sized against the findings, including the projected always-loaded footprint versus today's measured one.

STOP after the audit report and my answers to your questions. Do not modify anything until I approve.

═══ PHASE 2: IMPLEMENTATION (only after audit approval) ═══

Apply the approved findings, then build the following. Show me a diff of every file before writing it. Preserve all existing rules that survived the audit: relocate, don't delete.

ARCHITECTURE, TWO LAYERS:
- `~/.claude/CLAUDE.md` = always-loaded, rules only. Hard line cap set at ~120% of the lean rewrite; state the cap number.
- `~/.claude/references/` = on-demand detail. Migrate catalog, guide, and toolkit-style docs here (keep names). Create references/patterns.md (worked examples) and references/stack-notes.md (one section per stack component found in the config; on a fresh install create it empty with a purpose header, and do not invent components).
- CLAUDE.md contains a reference index (max 15 lines): one line per doc with a sharp "read when" trigger, plus: "Reference docs are authoritative over general knowledge; read the relevant one before working in its domain."

GLOBAL CLAUDE.md SECTIONS:
1. Identity and defaults: populate ONLY from existing config and audit answers; ask for anything still missing, including model policy.
2. Anti-assumption rule: "Never assume details about the user, the project, or prior decisions. Verify from files in the repo or config, or ask. If forced to make an assumption, state it explicitly."
3. Verification: never report a task done with failing checks; every project defines a VERIFY command (propose a minimal one if missing before starting work); two failed verifications on the same problem means stop, return to plan mode, re-decompose.
4. Memory tiers: global = durable cross-project rules only; project CLAUDE.md = project conventions plus VERIFY command; references/ = detail; nothing session-specific in global.
5. Reference index.
6. Lesson capture (NATIVE-FIRST applies): if Claude Code's built-in auto memory exists, it IS the capture layer. Do not create a custom "## Lessons" ledger; instead add a short rule stating that native memory is the single source of lessons and the curation command is its curator. Only if no native memory exists, fall back to a "## Lessons" section with entries formatted "- [date, session-id] one-line lesson". Do not add a self-reported use-counter to lesson entries. Nothing reliably increments one, and a number the model maintains about its own behaviour is exactly the kind of evidence this config does not accept.
7. Canary: "When asked 'config check', reply CONFIG-ACTIVE-vN, lesson count (from whichever lesson store is in use), and the date of the last curation run."
8. CAPTURE RULES. If native auto memory handles capture, skip the custom capture rule entirely and rely on the native layer. Otherwise add these, exactly as scoped:
   - The trigger to CONSIDER writing a lesson is a failed verification, a user correction, or a task that took three or more attempts. The trigger only opens the question. It does not justify a lesson on its own. Attempt count measures nothing by itself.
   - EXCLUSIONS. Do not write a lesson when the root cause was any of: an expired, missing, or wrong credential; a quota, billing, or rate limit (401, 402, 403, 429); a provider outage, network failure, or DNS failure (5xx, timeouts); a tool call that misfired or was denied by permissions; a missing local install or wrong runtime version; or anything a plain retry fixed with no change of approach. These are environment conditions, not knowledge. They cause the majority of failed attempts and none of them is worth a rule.
   - POSITIVE TEST. Write the lesson only if both are true: knowing it would have changed the FIRST action taken, and the condition that caused it will still exist next month. If either is false, write nothing.
   - Every lesson records the session id it came from, so a later curation run can count occurrences instead of trusting a summary.
   - A lesson written by capture is a candidate, not a rule. It stays in the project-level store. Nothing is promoted to global by capture, ever.
9. "If verification passed but the user later reports the change was wrong: propose a check that would have caught it and add it to that project's VERIFY command."
10. "When starting work in a project with no project CLAUDE.md, scaffold it from the template automatically and say so in one line."

SLASH COMMANDS (in `~/.claude/commands/`, never overwrite an existing command of the same name; if a name collides, ask):

- /learn: only create this if capture is NOT native; it manually triggers the capture rules above, exclusions and positive test included. With native memory, skip it, or keep it only as a one-line "distill this session into memory now" nudge if the user wants a manual trigger.

- /fresh: output a standalone brief of the current unsolved problem: goal, attempts made, exact error output, VERIFY command, ending with a request for 3 distinct root-cause hypotheses and a discriminating test before any code changes. Paste-ready for a new session.

- /evolve: the curation cycle, and the only gated step. Its command file must open with this line: "Run this in a fresh session with no implementation work in its history, and on a different model from the one that did the work being audited if your setup allows it. If this session has been doing implementation work, stop and tell me to re-run it clean." Then:
   0. Commit current `~/.claude/` state to git with a dated message, as the rollback point.
   1. GATHER EVIDENCE FIRST, before forming any opinion. Run the built-in `/insights` report if this Claude Code build has one, and read its output. Then read the raw session transcripts under `~/.claude/projects/` covering the period since the last curation commit. Those files are large and noisy, so do not pull them into context directly: write or reuse a small script that extracts only what is needed (user corrections, failed verifications, repeated errors, rules that fired) into a compact digest, and save that digest under `~/.claude/audit/<date>/` so later runs can compare against it rather than re-deriving it. State how many sessions the digest covers.
   2. CADENCE AND THRESHOLDS. Do not run this at the end of a working session, and do not run it once per session. Run it when at least 30 sessions or 7 days have accumulated, whichever comes first, so patterns are visible above noise. State the count in the report. Then: merge duplicates within a project, one file survives and the index is updated; PROMOTE to global only what appears in at least 3 distinct sessions AND at least 2 distinct projects, each cited by session id, and below that threshold a lesson stays where it is, because one vivid incident is not a rule; DELETE only on the staleness definition from Phase 1 section 2, cited, never because something looks unused, and present deletions for a yes or no rather than auto-deleting; rewrite vague entries as testable one-liners in place, using the same one-sentence-observation test.
   3. MINI-AUDIT against CURRENT Claude Code: consult the official documentation and changelog (via web search or fetch if available) for features, config conventions, or deprecations introduced since the last run. Evaluate against THOSE, not training knowledge, cite what changed, and apply the staleness definition. DEFAULT TO KEEP applies here: report only rules that meet the definition.
   4. Enforce the CLAUDE.md line cap via demotions to references/, and verify the reference index matches the actual files.
   5. ECOSYSTEM SCAN: check current official Claude Code docs and the plugin, skill, and MCP ecosystem for capabilities relevant to the stack components and workflows actually present in this config. At most 3 candidates per run, and zero is a fine answer. ELIGIBILITY: a candidate must be either (a) official, published by Anthropic or by the vendor of the tool it integrates, such as a database vendor's own MCP server, or (b) widely adopted with verifiable signals: substantial GitHub stars, high npm download counts, AND commit activity within the last 6 months. Reject anything unverifiable, abandoned, or niche regardless of how good it looks. For each suggestion state the official-or-adoption evidence with numbers, what it replaces or adds, the concrete benefit, and the cost (setup effort, token footprint, new dependency). Only suggest things that map to friction visible in the digest from step 1. Never install anything: suggestions only, for my decision.
   6. METRICS, restricted to what can be counted without self-report: always-loaded line and byte count, lesson count, number of rules added, changed and deleted this run, sessions covered by the digest, and days since the last run. Do not report a "rules violated" figure, or any other number derived from a model's account of its own behaviour.
   7. PROVENANCE: append an entry to `~/.claude/audit/history.md` for every applied change: date, config version, what changed, and the citation that justified it. This is what lets a later run find a change and reverse it. It is a record, not a measurement: it does not establish that the change helped.
   8. Present ONE consolidated diff and WAIT. On approval: apply, bump the canary version, commit again. If the config contains a user sync or propagation command, end by reminding the user to run it.

- /health: audit only, and it applies nothing. Same fresh-session rule as /evolve, stated at the top of the command file. Checks, all citation-backed: contradictions between rules; dead weight as defined in Phase 1 (path checks, not impressions); reference-index entries with no matching file, and files with no entry; dull index triggers. It must NOT contain a "rules violated this session" check, or any other check that asks the model to grade its own conduct. If you want that signal, it comes from the transcript digest in /evolve step 1, produced by a session that did not generate the transcripts. Same sync reminder rule as /evolve.

HOOKS (in settings.json, merged carefully with existing hooks, never replace them; document setup in references/setup-guide.md):
- Do NOT add a PostToolUse hook that runs a typecheck, test suite, linter, or build after every edit. It fires while a multi-file change is legitimately half-applied, so it reports errors that are an artifact of editing order, and it spends the project's full check time on every single edit. The cost is real and the signal is noise. Version 1 of this instruction specified one; that was a mistake.
- If you want automated verification, put it on a Stop hook that runs the project's declared VERIFY command ONCE at the end of a turn, and only when the project actually declares one. A turn boundary is a point where "is this broken?" is a fair question. Mid-edit is not. Make it easy to disable with an environment variable, and say so in the setup doc.
- SessionStart: check the date of the last git commit in `~/.claude/` from a curation run; if more than 21 days ago, print one line saying curation is overdue, with that date. Max 2 lines, silent otherwise.
- Do not add a session-end hook that writes lessons. Session end is exactly when the model is least able to judge which of its failures were worth recording, and a hook makes that judgement unattended. Capture belongs to the native memory layer, or to an explicit manual trigger.

GIT SAFETY NET:
git init `~/.claude/` if not already a repo; sensible .gitignore; rule: the curation command always commits before and after itself. Git is the rollback mechanism for all config changes, and `audit/history.md` is the index that tells you which commit to roll back to and why. If a separate sync or propagation mechanism exists, git remains the source of truth for history: sync propagates, git rolls back.

MULTI-MACHINE AWARENESS (generic):
If evidence of multi-machine use exists (a sync command, symlinks, machine-specific notes), ensure everything created here is covered by that mechanism and list manual steps for other machines in the final summary. If no evidence exists, don't invent a sync system: note the config is machine-local.

PROJECT TEMPLATE: project CLAUDE.md template containing VERIFY command, escalation note, "## Lessons", and a pointer to the global reference index.

CONSTRAINTS: the always-loaded footprint must not grow versus today's config (fresh install: keep the baseline lean). Finish with: a one-screen summary of changes, final CLAUDE.md line count versus cap, the personalization inventory with what was integrated, audit findings resolved versus deferred, and any multi-machine manual steps.

FINAL HONESTY REQUIREMENT: end the summary by stating plainly that this system curates the configuration and does not measure whether the configuration works, and that no change made here has been tested against outcomes.

---

## Known limitations

These are the things this instruction does not do. Version 1 implied otherwise in places, and an
expert review found it. Read them before trusting any output.

**1. Nothing here validates a change.** The cycle proposes edits to rules and lessons, you approve
them, and they are applied. No run of this system establishes that the config that came out is
better than the one that went in. The honest fix is an eval harness: take a fixed set of
representative tasks, replay them through headless `claude -p` sessions against the old config and
the candidate config, score both against a rubric, and keep the change only if it wins. That is a
real piece of software, not a prompt, and it is not built here. Until it exists, treat every applied
change as an unverified edit that git can reverse, which is why the provenance log matters.

**2. A model is a poor witness to its own behaviour.** Asking Claude at the end of a working session
what it got wrong produces a flattering and unreliable answer, because the whole session was spent
pursuing a goal it is disposed to report success on. Every judgement in this system is therefore
pushed into a separate session that reads transcripts and files rather than recalling. That reduces
the problem. It does not remove it, because the auditor is still a language model, and running it on
a different model from the one that did the work helps more than anything else here.

**3. Failed attempts are mostly environmental.** Three attempts at a task usually means an expired
token, a rate limit, a missing install, or a tool that misfired, not a lesson worth keeping. The
capture rules above exclude those explicitly, and that exclusion list is the most load-bearing part
of them. It will still be incomplete. Prune aggressively.

**4. One session is not a pattern.** Nothing is promoted to a global rule from a single incident.
The thresholds here (3 sessions, 2 projects, a 7-day or 30-session cadence) are a crude stand-in for
statistical significance, chosen to be cheap rather than correct. They are enough to stop the config
learning from noise. They are not a measurement.

**5. The cost is not two minutes.** A real curation run is a dedicated session that reads a
transcript digest, checks the current docs, and produces a diff worth reading. Budget for a proper
sitting, monthly at most.

**6. It can still make your config worse.** A curated, tidy, current config is the deliverable. That
is genuinely useful, and it is less than "self-improving". Keep git clean, keep the provenance log,
and read the diff.
