Your Claude Code setup is software. It has a CLAUDE.md, rules, skills, subagents, hooks, MCP servers, plugins and settings, and it has bugs: instructions that no longer match the code, skills that never trigger, rules that get lost in a 400-line file, a reviewer subagent that keeps flagging the same non-issue. Every session also leaves evidence of those bugs, in transcripts, telemetry, review findings and the corrections you type. This final session closes the loop. You will learn to run a self-improving setup: one that turns that evidence into small, tested, versioned changes to its own configuration, and can undo any of them in minutes.

Thesis of the sessionA Claude Code setup should improve from its own exhaust, but only through changes that are evidence-backed, evaluated against a baseline, approved by an owner, versioned and reversible. Skip the gates and the loop produces config bloat and confident regressions. Keep them and every week of use makes the next week cheaper and more reliable. The five topics below are the five stages of that loop: Feedback → Evaluation → Distillation and Optimization → Governance.

Facts on this page are as of 2026-10-24 (Claude Code v2.1.310). Claude Code ships weekly, so features that need a minimum version say so inline. Check yours with claude --version.

Delivery 5: products that learn

Improves what you ship. Signals come from users (analytics, support, incidents), and the decisions are to expand, revise, revert or stop a feature. See delivery-5 → Feedback Loops.

Autonomy 5 (this session): the setup that learns

Improves the Claude Code configuration that builds what you ship. Signals come from sessions (transcripts, rejected edits, review findings, corrections), and the decisions are to adopt, narrow, reject or roll back a change to CLAUDE.md, rules, skills, hooks, subagents, MCP servers, routing or plugins.

One turn of the loop, as a ratchet. Each station is a topic of this session; press propose to send a candidate around. The governance pawl lets the wheel click forward one version only when a change clears its gate. A candidate with no measurable effect drops into the lessons log instead of into config, and a rollback lifts the pawl to step back exactly one version. Version numbers are illustrative.

The whole session follows one running example. The Acme Orders team runs a Postgres-backed service. Over three weeks, three developers keep correcting Claude about database migrations: it edits migrations that were already applied, creates indexes without CONCURRENTLY, and forgets the down migration. The widget below walks that example through the entire loop. Each topic then opens up one stage in depth.

Watch one correction change shape: a quoted complaint, a lesson entry, a skill and a hook, an eval case, a score, a passing suite, an approval, a tagged release and a promotion. Step through, press Play or click a stage; each step shows the artifact that exists at that point, in the format Claude Code actually uses. The glyphs grow with the evidence they carry. The counts are illustrative. The file formats, commands and fields are real.

After this session you will be able to:

Builds on: core-3 → Library, core-5 → Business (usage insights), agents-3 → Plugins, agents-5 → Evals and autonomy-2 → Operations.

Feedback

Claude Code already records most of the evidence you need to improve your setup. The skill is knowing where each signal lives, how precise it is, how long it survives, and how to collect it without parsing undocumented formats or leaking secrets.

Hover a tap to see which shelves it fills, or a shelf for how long it keeps what, how private it is and where it lives. Sessions and pull requests produce the signals. Each one lands in a different store with its own retention and privacy rules. Only the lessons inbox is yours to design; everything else Claude Code or your review tooling writes for you.

Transcripts

What it is. Every session is saved continuously as a JSONL transcript at ~/.claude/projects/<project>/<session-id>.jsonl, where <project> is the working directory path with non-alphanumeric characters replaced by -. Subagent conversations live beside it under <session>/subagents/. A transcript holds "messages, tool calls, and tool results, plus the system prompt, tool definitions, and parameters of the requests Claude Code sent the model": your prompts, Claude's replies, the commands it ran and the output it read. It is the richest feedback source you have, because it records not only what went wrong but the context in which it went wrong.

How long it survives. The retention sweep deletes transcripts older than cleanupPeriodDays, 30 days by default (minimum 1; 0 fails validation). If you want to mine a quarter of sessions, raise it in ~/.claude/settings.json or archive transcripts as they close. (Claude Desktop and Cowork transcripts follow their own rule, desktopSessionCleanupPeriodDays.) Transcripts are plaintext and "not encrypted at rest", so anything a tool read, including a .env file or a printed token, is in there. Treat the archive like a credentials store.

How to read them safely. The docs are blunt: "The entry format is internal to Claude Code and changes between versions, so scripts that parse these files directly can break on any release." Use the documented interfaces instead:

  • Agent SDK session helpers: list_sessions(directory=...) and get_session_messages(session_id) return typed records (type is "user" or "assistant", plus uuid, session_id, message and parent_tool_use_id).
  • Ask the session itself: claude -p --resume <session-id> --fork-session --output-format json "list every correction I gave you" lets Claude summarize its own transcript. --fork-session keeps the question out of the session you're mining; add --json-schema if you want the answer as structured output rather than text in result.
  • Hooks: every hook receives transcript_path, so a SessionEnd hook can archive or index the file the moment a session closes.
  • /export [filename]: a rendered plain-text copy for a human reviewer.
# Find candidate corrections in your recent sessions for one repo.
# Uses the documented session helpers, not the raw JSONL format.
# pip install claude-agent-sdk   (Python 3.10+)
import re
from claude_agent_sdk import list_sessions, get_session_messages

CORRECTION = re.compile(   # "no," / "no." need their own branch: \b can't follow the comma
    r"(?:\bno[,.]|\b(?:don't|do not|instead|never|stop|again|you forgot|wrong)\b)", re.I)

def user_text(msg):
    """SessionMessage.message is raw content: a string or a list of blocks."""
    content = msg.message.get("content") if isinstance(msg.message, dict) else msg.message
    if isinstance(content, str):
        return content
    if isinstance(content, list):  # skip tool_result blocks, keep typed text
        return " ".join(b.get("text", "") for b in content
                        if isinstance(b, dict) and b.get("type") == "text")
    return ""

for info in list_sessions(directory="/work/acme-orders", limit=200):
    for m in get_session_messages(info.session_id, directory="/work/acme-orders"):
        if m.type != "user" or m.parent_tool_use_id:   # main-session prompts only
            continue
        text = user_text(m)
        if CORRECTION.search(text):
            print(f"{info.session_id[:8]}  {text[:120]!r}")
{
  "hooks": {
    "SessionEnd": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/hooks/archive-transcript.sh",
            "timeout": 5
          }
        ]
      }
    ]
  }
}
#!/bin/bash
# ~/.claude/hooks/archive-transcript.sh  (chmod +x)
# Copies the closing session's transcript to a private archive outside any repo.
input=$(cat)
src=$(echo "$input" | jq -r '.transcript_path')
sid=$(echo "$input" | jq -r '.session_id')
dest="$HOME/.claude-archive/$(date +%Y-%m)"
mkdir -p "$dest" && chmod 700 "$HOME/.claude-archive"
[ -f "$src" ] && cp "$src" "$dest/$sid.jsonl"
exit 0
PitfallsFormat churn: a regex over raw JSONL works until the next release changes the entry shape, so build on the SDK helpers or claude -p --resume. Secrets: never archive transcripts into a repo, and redact before you share a mined excerpt in a PR. Machine-local: transcripts and auto memory stay on the machine that ran the session; cloud sessions and teammates' laptops aren't in your corpus. Survivorship: sessions you abandoned with /clear after two failed corrections are the most informative ones, so don't filter out short sessions.

Claude Code itself mines transcripts in three bundled flows you can learn from: /fewer-permission-prompts scans your transcripts for common read-only Bash and MCP tool calls, then adds a prioritized allowlist to project .claude/settings.json; /team-onboarding analyzes your sessions from the past 30 days into a guide for a teammate; and /insights, below, reports friction across up to 200 sessions. Docs: sessions, .claude directory, Python SDK reference.

Telemetry

What it is. Claude Code exports metrics and events over OpenTelemetry once you opt in with CLAUDE_CODE_ENABLE_TELEMETRY=1 and choose exporters (OTEL_METRICS_EXPORTER, OTEL_LOGS_EXPORTER; OTEL_EXPORTER_OTLP_PROTOCOL has no default). Transcripts tell you why one session went wrong. Telemetry tells you how often something goes wrong across every developer, which is what you need to prioritize and to watch a rollout.

The events that carry feedback. Most telemetry is usage accounting. A handful of signals describe quality:

SignalKey attributesFeedback question it answers
claude_code.code_edit_tool.decision (counter)tool_name, decision (accept/reject), source (user_reject, user_abort, config, hook, ...), languageWhich kinds of edits do people reject, and in which languages?
claude_code.tool_decision (event)decision, source, tool_use_id, permission_mode and classifier_verdict (both v2.1.301+), tool_parameters with OTEL_LOG_TOOL_DETAILS=1Which commands get denied, by a person, a rule, a hook or the auto mode classifier?
claude_code.safety_event (event, v2.1.307+)category, decision (accept/reject/sent_back), decision_source, reason_code, rule_source, tool_use_id; no command text or pathsWhich check (rule, mode, hook, classifier, sandbox) stopped or prompted a call, and from which settings source?
claude_code.skill_activated (event)skill.name, invocation_trigger (user-slash, claude-proactive, nested-skill), skill.sourceDoes Claude pick the skill on its own, or does someone always have to type it?
claude_code.subagent_completed (event)agent_type, total_tool_uses, duration_ms, model, final_modelWhich subagents run long or switch models mid-run?
claude_code.cost.usage (counter)standard attributes, plus plugin.name when the active skill or subagent belongs to a plugin (your own plugins report "third-party" unless OTEL_LOG_TOOL_DETAILS=1)What does each plugin cost in API spend?
claude_code.feedback_survey (event)event_type, survey_type, response; needs CLAUDE_CODE_ENABLE_FEEDBACK_SURVEY_FOR_OTELThe "How is Claude doing?" rating. Low information per item, but cheap to trend.

How to apply it. Configure exporters in managed settings or each user's ~/.claude/settings.json. Exporter variables in a repository's .claude/settings.json are ignored, so a cloned repo can't redirect your telemetry. Tag every datapoint with the config version you're running, so a dashboard can split before and after a change:

{
  "env": {
    "CLAUDE_CODE_ENABLE_TELEMETRY": "1",
    "OTEL_METRICS_EXPORTER": "otlp",
    "OTEL_LOGS_EXPORTER": "otlp",
    "OTEL_EXPORTER_OTLP_PROTOCOL": "grpc",
    "OTEL_EXPORTER_OTLP_ENDPOINT": "https://otel.acme.internal:4317",
    "OTEL_RESOURCE_ATTRIBUTES": "team.id=orders,claude_config=acme-db-1.4.0",
    "OTEL_LOG_TOOL_DETAILS": "1"
  }
}

Why it matters. A rejected edit is the cheapest correction signal there is: the developer said no without typing a word. A spike in user_reject on Edit for .sql files after a release is a rollback trigger you can alert on.

PitfallsRedaction: for user-defined and third-party plugin skills, skill.name is the placeholder custom_skill and agent names become custom unless OTEL_LOG_TOOL_DETAILS=1. Your organization's own marketplace counts as third-party here: plugin.name is "third-party" on the cost and token counters and is omitted on skill_activated unless you set that variable (before v2.1.273 the counters stayed redacted even with it), which is why the snippet above sets it. Prompt text is never exported unless OTEL_LOG_USER_PROMPTS is set ("Only prompt length is recorded"), so telemetry can count corrections it can't read. Cardinality: every OTEL_RESOURCE_ATTRIBUTES key becomes a label on every series, and values can't contain spaces. Approximations: "Cost metrics are approximations"; reconcile with your bill before you claim savings.
Joining telemetry, hooks and transcripts into one record

The three sources share identifiers, so you can explain a telemetry spike with the transcript that produced it. tool_use_id on tool_result and tool_decision events "Matches the tool_use_id passed to hooks", so a PreToolUse or PostToolUse hook that logs {session_id, tool_use_id, tool_input} to a local file lets you look up the exact command behind a rejection. Events also carry session.id and prompt.id (all events from one prompt share it). Every hook receives session_id and transcript_path, so the chain is: alert on a counter → pull the tool_decision events in the window → join on session.id → resume or export that session.

Two traps. First, event.sequence is per process, so don't sort across machines with it; use event.timestamp. Second, the interactive CLI and -p report decisions differently: in the interactive CLI, user_permanent and user_temporary appear only on the prompt itself and later matches report config, while in SDK and -p sessions every later match repeats the user source. Don't compare reject ratios across the two surfaces without splitting by app.entrypoint, which events carry but metrics include only when OTEL_METRICS_INCLUDE_ENTRYPOINT=true. Source: monitoring usage.

Insights

What it is. /insights generates an HTML report about how you work rather than how many tokens you used: what you work on, "friction points such as misunderstood requests or buggy code", and suggestions for using Claude Code better. A single run analyzes up to 200 sessions it hasn't seen before and skips very short ones; when sessions are left out, the header shows something like 200 sessions (412 total). When auto mode is available and your sessions mostly ran without it, the report can estimate how many permission prompts auto mode would have handled.

Where it lands. The latest report is ~/.claude/usage-data/report.html, with a timestamped copy per run, deleted on the same cleanupPeriodDays schedule as transcripts. It runs on any plan and provider, through your own account, so its tokens count against your usage. It covers sessions on this machine only, and it isn't available in cloud sessions.

Its siblings. Three other built-ins answer narrower feedback questions:

  • /usage on Pro, Max, Team or Enterprise shows a plan usage breakdown: usage attributed to skills, subagents, plugins and individual MCP servers as a share of the total; behavior flags such as long context or cache misses when one accounts for 10% or more of recent usage; and a row per heavy /loop or scheduled task (v2.1.242+). Press d or w for 24 hours or 7 days.
  • /skill-doctor (v2.1.252+, needs feature-flag fetching) shows each skill's context cost and how often it's used, and flags listed skills that have never been invoked.
  • /doctor lists "unused skills, MCP servers, and plugins compared with their context cost" and checked-in CLAUDE.md content Claude could derive from the code.

How to apply it. Make it a ritual. Once every two weeks, run /insights, then paste its friction section into a session and ask Claude to turn each friction point into a lessons-inbox entry with a pointer to one or two example sessions. The report is a hypothesis generator. You confirm each hypothesis against transcripts before it becomes a candidate.

Pitfall: a summary is not evidence/insights is a model's reading of your sessions. It can over-generalize from one dramatic session and it can't see sessions on other machines. "Claude often misunderstood test commands" becomes evidence only once you can point at, say, six sessions and quote the corrections. Also remember the cost: on a large history, a run is a real analysis job, not a free status screen.

Review Findings

What it is. Every code review of Claude-written code is a labeled sample of its mistakes. Claude Code produces review findings in several places: /code-review locally (findings arrive as text in the reply; --max-findings since v2.1.288); claude ultrareview [target] --json from CI (on v2.1.309+ it needs a trusted folder, so a CI job appends --trust-workspace after the target); the managed Code Review product on GitHub pull requests (Team and Enterprise), which posts inline comments ranked as Important ("A bug that should be fixed before merging"), Nit or Pre-existing, plus a check run named Claude Code Review; and of course your human reviewers' comments.

Why it matters. The docs name review as a trigger for changing your setup: add to CLAUDE.md when "a code review catches something Claude should have known about this codebase", and "A repeated mistake or a recurring review comment is a CLAUDE.md edit, not a one-off correction in chat." Findings are also the best raw material for eval cases, because each one comes with a diff that shows the bad behavior.

How to apply it. Treat findings as data, not as a to-do list:

  1. Tag each finding on Claude-authored PRs with a short category (migration-lock, missing-down, generated-file-edit).
  2. Count over a window: "Important: CREATE INDEX without CONCURRENTLY, 4 of the last 30 PRs" is a lesson candidate. One finding is an anecdote.
  3. Separate what the agent introduced from what was already there. Pre-existing findings say nothing about your setup. The Claude Code team reported that about 59% of what one reviewer flagged in a long review loop was old code (How the Claude Code team does code review).
  4. Feed the recurring ones back into whichever artifact steers the reviewer: REVIEW.md for Code Review, your reviewer subagent's prompt, or the skill that produced the code.
A governance detail worth copyingCode Review reads REVIEW.md "from the base or default branch and never from the pull request's own changes". A pull request can't weaken the instructions that review it. Apply the same rule to your own feedback loop: the graders that judge a config change should come from the base branch, not from the change itself (see Governance › Approving).
Pitfall: reviewer noise is feedback about the reviewer"A reviewer that's asked to find problems will always find something." If you distill every Nit into a rule, you get an over-specified CLAUDE.md and over-engineered code. Weight Important findings, ignore Pre-existing ones for this purpose, and when a reviewer subagent keeps flagging non-issues, the lesson is a change to the reviewer.

Human Corrections

What it is. The most precise signal: a person telling Claude it got something wrong. It shows up as a chat correction ("no, never edit an applied migration, add a new one"), an Esc interrupt, a /rewind, a rejected edit or permission prompt, a denied auto mode action you then confirm was right to deny, or the diff between what Claude committed and what was merged. The docs list exactly these as triggers for changing CLAUDE.md: "Claude makes the same mistake a second time" and "You type the same correction or clarification into chat that you typed last session".

The built-in loop: auto memory. Claude already learns from your corrections. Auto memory (on by default in local sessions) saves notes of four types, one of which is feedback: "corrections you give Claude and approaches you confirm". The files live at ~/.claude/projects/<project>/memory/ as a MEMORY.md index (first 200 lines or 25KB load each session) plus topic files like feedback_testing.md, and they're exempt from the retention sweep. That's a real self-improvement loop, but it is personal, machine-local, unreviewed and unversioned. Three developers can each teach Claude the same migration rule in three private memory folders, and a fourth gets none of it.

How to apply it. Capture corrections where you can count them, then promote the shared ones:

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          { "type": "command", "command": "~/.claude/hooks/log-corrections.sh", "async": true }
        ]
      }
    ]
  }
}
#!/bin/bash
# ~/.claude/hooks/log-corrections.sh  (chmod +x). Async, so it never stalls a prompt.
# Appends prompts that look like corrections to a private, local JSONL inbox.
input=$(cat)
prompt=$(echo "$input" | jq -r '.prompt')
if echo "$prompt" | grep -qiE "(^|[[:space:]])(no[,.]|don't|never|instead|again|you forgot|wrong)"; then
  mkdir -p "$HOME/.claude-archive" && chmod 700 "$HOME/.claude-archive"
  echo "$input" | jq -c '{ts: now, session_id, cwd, prompt: (.prompt[0:500])}' \
    >> "$HOME/.claude-archive/corrections.jsonl"
fi
exit 0

Then, every couple of weeks, run /memory, open the auto memory folder, and read your own feedback notes. Anything that would help a teammate is a candidate for CLAUDE.md, a rule or a skill, via a pull request.

Pitfallsn = 1: one correction is a preference or a bad prompt; wait for repetition across sessions and, for team artifacts, across people. Prompt debt, not rule debt: many corrections fix an underspecified request. The docs' fix for repeated corrections is to "run /clear and write a better prompt instead of a third", not a new rule. Keyword detectors are noisy: "Thanks again, could you also add a test?" matches again. Use the detector to find candidates and a person or a clustering pass to confirm them.
From keyword hits to classified corrections: precision, recall and a structured-output pass

A keyword detector has high recall on blunt corrections ("no, ...", "you forgot ...") and two systematic errors: false positives on polite or unrelated phrasing ("Not urgent, but ..."), and misses on corrections phrased as instructions ("Use CREATE INDEX CONCURRENTLY, a plain one locks orders"). Treat it as a cheap first stage and add a second, more precise stage on the hits plus a sample of non-hits, so you can estimate what you're missing.

A headless pass with a JSON schema is enough for the second stage, and --json-schema puts the parsed object in the result's structured_output:

claude --bare -p "You label prompts from coding sessions. Is this prompt correcting something Claude just did?
If yes, state the general lesson in one line and who it applies to. Prompt: $PROMPT" \
  --model haiku --max-turns 3 --tools "" --permission-mode dontAsk --max-budget-usd 0.05 \
  --output-format json \
  --json-schema '{"type":"object","required":["is_correction"],"properties":{
    "is_correction":{"type":"boolean"},
    "lesson":{"type":"string"},
    "scope":{"type":"string","enum":["personal","repo","org"]}}}' \
  | jq 'if .stop_reason == "refusal" then error("declined: \(.result)")
        elif .terminal_reason != "completed" then error("run ended: \(.terminal_reason)")
        elif .structured_output == null then error("no structured output")
        else .structured_output end'

Structured output arrives through a tool call of its own, so real v2.1.303 runs needed two turns; with --max-turns 1 they ended in error_max_turns with structured_output: null (recorded in the course's research notes). Check stop_reason first, then terminal_reason, then whether structured_output is present, as the jq filter does: a declined request usually arrives as subtype "success", and the Agent SDK reference gives the same order. --tools "" removes the built-in tools the classifier doesn't need, and --bare skips CLAUDE.md, plugins and MCP servers, which keeps each call to a fraction of a cent (it needs ANTHROPIC_API_KEY, apiKeyHelper or a cloud provider's credentials, not a /login session).

Then cluster the lesson strings (an embedding or a second Claude pass) and count sessions and people per cluster. Hand-label 50 prompts once to measure the classifier's precision and recall on your own phrasing; re-check after a model change. Keep the pipeline local and private: the prompts you're classifying can contain anything a developer pasted.

Each kind of feedback is a pan of ore: the pile's height is its volume per week, and the density of gold flecks is how often one item points at something worth fixing. Chat corrections are a small, rich pan; session ratings are a big pile with one fleck. The heights and densities are an illustrative ranking, not a measurement. Pick a signal, or hover and click a pan to sift it. The card gives the exact place Claude Code records it, the fields to read, and the capture mechanism.
Toy corpus of eight sessions from three developers. A keyword detector highlights the turns it flags; the margin marks a false positive (⚑) or a correction it missed (○), and each cluster's tallies pass or fail the thresholds. Pre-labelled clusters stand in for an LLM clustering pass. Raise the thresholds and watch personal preferences drop out while team-wide lessons survive.

What you build: a miner over seven lab-made sessions (transcripts/*.jsonl, in the documented stream-json message shape). It finds the human corrections, splits each into directives and groups them by what they ask for; it also finds tool calls that failed the same way across sessions and procedures people repeated. Each group gets one proposed fix with its evidence (sessions, quotes, counts): a hook when CLAUDE.md already says it and people still correct it, a path-scoped rule, a permission deny, a codebase-map line or a skill draft. Nothing is applied; it writes out/transcript_miner/proposals.md, proposals.json and drafts/.

cd labs && python3 autonomy-5/transcript_miner.py
cd labs && python3 autonomy-5/transcript_miner.py --min-sessions 1     # also show one-off corrections
cd labs && python3 autonomy-5/transcript_miner.py --transcripts DIR --claude-md ./CLAUDE.md   # DIR: your saved stream-json runs

What to observe: "run the tests before finishing" was corrected in 3 of 7 sessions although CLAUDE.md already says it, so the proposal is mechanical, not another sentence: "a Stop gate that runs the tests itself and keeps its own budget", with CI as the real gate (a plain Stop hook guarded by stop_hook_active is only a one-time nudge). "Don't edit the tests to make them pass" isn't in CLAUDE.md and every edit it followed was under tests/, so the proposal is .claude/rules/tests.md with paths: ["tests/**"]. Two release sessions ran the same five steps, so it drafts a /release skill with disable-model-invocation: true. Two sessions tried to read a file that doesn't exist, which becomes a one-line CLAUDE.md map fix. Corrections seen once (add-dependency-library, changelog-heading) stay under "Watching". The lab counts sessions, not people, so the widget's people threshold is yours to add. To mine your own work, point --transcripts at saved claude -p --output-format stream-json --verbose runs or Agent SDK messages serialized the same way, which is a documented shape; the lab deliberately doesn't read Claude Code's own session files under ~/.claude/projects/, whose format is internal (for those, use the SDK session helpers above).

Open the lab walkthrough

Exercise: build your lessons inbox

In one repository you use daily: (1) check cleanupPeriodDays and raise it if you want more history; (2) run /insights and copy its friction points; (3) run the mine_corrections.py snippet above (or ask Claude to do the equivalent with claude -p --resume on your five longest sessions); (4) open your auto memory feedback notes with /memory. Merge everything into a LESSONS.md outside the repo with one line per candidate: the lesson, how many sessions, how many people, and one quoted example.

Show a solution

A useful inbox entry looks like this:

## migrations: never edit an applied migration (candidate)
- evidence: 4 sessions, 2 people (me, ben), 2 Code Review "Important" findings
- quote: "no, 0038 is already applied in prod, add a new migration instead"
- current coverage: nothing in CLAUDE.md; my auto memory has feedback_migrations.md
- suggested artifact: deny rule + PreToolUse guard hook (must hold every time) + skill for the procedure

Expect most raw hits to be noise: one-off requests, preferences, or corrections of a vague prompt. If you end up with more than five real candidates, keep the five with the most people affected. Candidates supported by a single person stay in that person's auto memory or CLAUDE.local.md.

Key takeaways

  • Transcripts are the richest source, but their JSONL format is internal. Read them through get_session_messages(), claude -p --resume, hooks' transcript_path or /export, and mind cleanupPeriodDays (30 days) and the secrets inside.
  • Telemetry counts what transcripts explain: code_edit_tool.decision rejects, tool_decision sources and verdicts, skill_activated triggers. Tag datapoints with your config version.
  • /insights, /usage, /skill-doctor and /doctor are built-in feedback reports. Treat them as hypotheses to confirm.
  • Recurring review findings and repeated human corrections are the highest-precision signals. Auto memory already captures corrections, but privately, so promote shared lessons on purpose.
  • Count before you change anything: sessions, people and severity, not a single memorable failure.

Evaluation

Every change to your setup is a hypothesis: "this rule, skill or routing change makes Claude do the right thing more often, without breaking anything else". Evaluation is how you find out, by running the same realistic requests with and without the change, in fresh sessions, enough times that noise can't fake a win.

Proof Ladders

What it is. "It worked when I tried it" is the most common justification for a config change and the weakest one, because the session you tried it in was the one where you'd just written it. The skills docs spell out why: "A fresh session matters because leftover context from authoring the skill will mask gaps in the written instructions." A proof ladder replaces the anecdote with ordered rungs. Each rung asks one question, needs specific evidence, and catches one kind of false improvement.

RungQuestionEvidence in Claude Code termsCatches
0 · AnecdoteDid it ever work?One interactive session, usually the authoring oneNothing
1 · ReproducedDoes it fix this case reliably?The failure is captured as an eval case (prompt.md + graders). It scores low without the change and passes with it, across 3+ fresh runsPlacebo fixes, lucky runs
2 · DeltaDoes it help beyond noise?A set of target cases where WITH beats W/OUT by more than run-to-run noise, on a pinned modelOne-case generalization
3 · Regression-freeDoes it hurt anything else?The full suite, including should-not-trigger cases, at the threshold; always-on tokens and eval cost within budgetStolen triggers, whack-a-mole
4 · CanaryDoes it hold on real work?A release channel or a subset of developers for a fixed window, with guard metrics such as edit reject rateThe gap between your eval set and real prompts
5 · AdoptedIs it the new baseline?Owner approval, a version tag, promotion to the stable channel, and a rehearsed rollbackUngoverned drift

Why it matters. The rung you need depends on blast radius, not on how confident you feel. A line in your CLAUDE.local.md can ship at rung 0 or 1: it affects only you, and you'll notice if it's wrong. A hook in a plugin that forty developers auto-update needs rung 4. The risk tiers in Governance map each kind of change to its minimum rung.

Pitfall: ladder inflation"Canary" means a pre-declared group and window with guard metrics compared against the stable channel, not "I used it for a day and it felt fine". "Regression-free" means you ran the whole suite on the same model as the baseline. If you can't link the evidence for a rung in the change record, you haven't reached it.
Choose a proposed change, then enter the evidence you have. The rungs are camps on a route to the summit: your evidence moves the climber, the flag marks the camp the change's tier requires, and the next pitch names what's missing. The noise check is a rough unpaired approximation that treats every run as independent, which overstates the sample size; real runs of the same case are correlated. Thresholds are policy choices, not laws.

Baselines

What it is. A baseline is the same task run without the change. The docs make it the core of skill evaluation: "Seeing a skill trigger tells you Claude found it, not that it did what you intended. To know a skill is working, measure separately whether Claude invokes it on the prompts it should, and whether the output matches what you expect when it does. The check for both is a baseline comparison." A high score alone proves nothing: "If a case scores 1.0 both with and without the plugin, the plugin isn't what made it pass."

Each calendar is a lesson cluster: weeks run down, weekdays run across, and each cell is a day shaded by how many corrections the transcripts recorded; the solid line is the week its fix shipped. Click or focus a calendar for the weekly counts before and after and whether the drop clears the noise, hover a cell for the correction it counts, and ship the pending skill to see a projection. In this toy corpus the hook and the two skill calendars go quiet below their line and the CLAUDE.md line's doesn't. Only the hook enforces; the skills and the CLAUDE.md line are prose, so measure each fix instead of assuming. The corpus and the projection are illustrative toy data. The mechanism is real: transcripts are swept after cleanupPeriodDays (30 days by default), so a twelve-week baseline needs an export.

How to switch each artifact off. The baseline arm needs a clean way to remove exactly one thing:

Artifact under testBaseline armTool
A plugin (its skills, agents, hooks, MCP servers)No plugin loadedclaude plugin eval runs both arms for you
A personal or project skill"skillOverrides": {"db-migration": "off"} ("skillOverrides doesn't apply to plugin skills")skill-creator, or a headless A/B
A CLAUDE.md line or a rule fileThe same repo copy without the lineHeadless A/B in temp copies
A settings hookA settings file without the hook, passed with --settingsHeadless A/B
Model or effort routing--model / --effort, or the agent's frontmatterclaude plugin eval --model, or A/B

Pin everything else. A baseline only isolates the change if the rest is held still: the same model ID (aliases "update over time"), the same effort, the same Claude Code version (claude plugin eval records claudeVersion in its JSON), a fresh session per run, and no personal config leaking in. For changes that claude plugin eval can't test, such as a CLAUDE.md line, a headless harness does the job:

#!/bin/bash
# ab.sh: run one realistic prompt 3x against two variants of the repo config.
# Each run gets a fresh temp copy; capped; never touches your real checkout.
set -euo pipefail
PROMPT="Orders lookups by customer are slow. Add an index on orders.customer_id."
export CLAUDE_CODE_DISABLE_AUTO_MEMORY=1          # keep your memory out of the comparison
for variant in base cand; do                      # fixtures/repo-base vs fixtures/repo-cand
  for i in 1 2 3; do
    work=$(mktemp -d); cp -r "fixtures/repo-$variant/." "$work"
    ( cd "$work" && claude -p "$PROMPT" \
        --setting-sources project --strict-mcp-config \
        --model claude-sonnet-5-5 --effort medium \
        --tools Read,Grep,Glob,Write,Edit \
        --permission-mode dontAsk --allowedTools "Read" "Grep" "Glob" "Write" "Edit" \
        --max-turns 15 --max-budget-usd 0.50 \
        --output-format json > "$work/result.json" ) || true   # a capped run exits non-zero
    stop=$(jq -r '.stop_reason // ""' "$work/result.json" 2>/dev/null || echo "")
    reason=$(jq -r '.terminal_reason // "unknown"' "$work/result.json" 2>/dev/null || echo unparsable)
    [ "$stop" = "refusal" ] && reason="refusal"          # checked first: a declined run can still read "completed"
    if [ "$reason" != "completed" ]; then                # refusal, api_error, max_turns, budget_exhausted...
      echo "$variant,$i,error,$reason"; continue          # an error, not a fail: don't grade it
    fi
    pass=0; grep -rqi "CREATE INDEX CONCURRENTLY" "$work/db/migrations" && pass=1
    echo "$variant,$i,$pass,$(jq -r '.total_cost_usd' "$work/result.json")"
  done
done

--setting-sources project keeps your user-level settings out of the comparison while the repo copy's own CLAUDE.md and .claude/ still load. MCP servers from ~/.claude.json and claude.ai connectors load regardless of that list, so --strict-mcp-config (with no --mcp-config) keeps them out too. --max-turns exits with an error when the cap is hit, hence || true. Check stop_reason first, then terminal_reason, then subtype, the order the Agent SDK reference gives: a declined response has stop_reason "refusal", usually with subtype "success", and real runs have also reported subtype: "success" with terminal_reason: "api_error". So a refusal, or any reason other than completed, counts as an error to re-run, not as a failed case. Don't use --bare here: it skips CLAUDE.md, which is the thing you're testing. Without --bare, a -p run also executes the hooks in a project's .claude/settings.json and connects the servers in its .mcp.json, even in a folder you've never trusted (headless docs), so only point this at fixture repos you wrote.

How many runs before a delta means anything?

Treat one binary grader as a coin with pass rate p. With r runs per arm, the standard error of the difference between arms is about √(2·p(1−p)/r). At the default r = 3 and p ≈ 0.5, that's ≈ 0.41, so a single case's Δ of +0.33 is well inside noise. Pooling helps: across n cases the error shrinks with √(n·r). To detect Δ = 0.2 with about 80% power at p ≈ 0.5, a two-proportion calculation gives roughly 2·(1.96 + 0.84)²·0.25 / 0.2² ≈ 98 runs per arm, such as 33 cases × 3 runs.

Two corrections make the real picture worse. Runs of the same case are correlated (same prompt, same fixture), so 10 runs of one case are worth far less than 10 cases. Prefer more cases over more runs. And llm graders add their own variance: each one is a majority of three judge votes, and the docs warn that verdicts differ "more the longer the text it has to read", so grade long outputs with regex over the file. This is why the docs recommend --runs 1 --ablation none only for iterating on graders, then "confirm any change at the default three runs before you trust it".

Plugin and Skill Evals

What it is. claude plugin eval (v2.1.269+; Git 2.31+ if git is installed) runs a plugin "against a suite of test cases and scores the results". Each eval case is a realistic prompt plus one or more graders. For skills that don't ship in a plugin, the skill-creator plugin runs a similar loop inside a conversation. "Neither tool reads the other's case files."

Hover a weight for its grader breakdown; the beam tilts by Δ. The runs are the illustrative ones behind the first row of the table below (11/12 with, 1/3 without). Each run is a fresh, isolated claude -p child with only the plugin loaded (with-arm) or no plugin (without-arm). A run's score is the weighted fraction of graders that passed; the case score is the mean over runs; Δ is with minus without.

How a suite is laid out. Cases live under the plugin's evals/ directory (or the path in "experimental": {"evals": "..."}). A case is a directory with a prompt.md (frontmatter: max_turns default 10, timeout_seconds default 300, runs default 3, allowed_tools, model, tags, env keys matching EVAL_*), optional case.yaml for fixtures, and one file per grader under graders/. "There are no custom-code graders." The six types are regex, tool_used, tool_order and file_exists (free, computed from the transcript and files) and llm and baseline (judge model calls). Here is the Acme case that tests the migration skill and guard hook:

plugins/acme-db/
├── .claude-plugin/plugin.json
├── skills/db-migration/SKILL.md
├── hooks/hooks.json
├── scripts/guard-applied-migrations.sh
└── evals/
    ├── adds-index-safely/
    │   ├── prompt.md
    │   ├── case.yaml          # scaffold: a git repo with one applied migration
    │   ├── fixture.sh
    │   └── graders/
    │       ├── skill-fired.md
    │       ├── concurrently.md
    │       ├── down-migration.md
    │       └── no-edit-applied.md
    ├── ignores-frontend-request/
    │   ├── prompt.md
    │   └── graders/{skill-not-fired.md, answer.md}
    └── results/               # written by each run; gitignored
---
description: Index on a hot table must not lock it, and 0038 is already applied
tags: [smoke, migrations]
max_turns: 15
allowed_tools: [Read, Glob, Grep, Skill, Write, Edit]
---

Orders lookups by customer are slow. Add an index on orders.customer_id.
schema_version: "1.1"
name: adds-index-safely
context:
  scaffold_script: fixture.sh   # runs only with --scaffold; creates db/migrations/0038_create_orders.*

graders/skill-fired.md: a "plugin-fired indicator", excluded from the score in two-arm runs.

---
type: tool_used
tool: Skill
input_match: '"skill"\s*:\s*"(?:[\w-]+:)?db-migration"'
---

graders/concurrently.md: the new file's name isn't known in advance, so this grades the Write call's input. Not target: trace: once the skill fires, its own body, which says CONCURRENTLY, is in the trace too.

---
type: tool_used
tool: Write
input_match: 'CREATE INDEX CONCURRENTLY'
---

graders/down-migration.md: only files created during the run count.

---
type: file_exists
path: db/migrations/*.down.sql
---

graders/no-edit-applied.md: grades the outcome, not the path: the applied file must be untouched.

---
type: regex
target: { source: file, path: db/migrations/0038_create_orders.up.sql }
pattern: 'INDEX'
match: not_contains
weight: 2
---
# from plugins/acme-db/ ; Write/Edit are outside the read-only set, so grant them
claude plugin eval . --allow-tools Write Edit --scaffold --threshold 0.8

# iterate on one case cheaply while you tune graders (noisy: confirm at 3 runs)
claude plugin eval . --case adds-index-safely --runs 1 --ablation none --allow-tools Write Edit --scaffold
CASE                       WITH  W/OUT Δ      RUNS COST    NOTES
adds-index-safely          0.92  0.33  +0.58  6    $1.12
adds-column-safely         0.83  0.42  +0.42  6    $1.05   down-migration: no *.down.sql created
ignores-frontend-request   1.00  1.00  +0.00  6    $0.38

3 case(s) · mean Δ +0.33 · 6m 12s · $2.55
Report: /work/acme/plugins/acme-db/evals/results/2026-10-14T09-12-03-118Z/report.html

Illustrative output in the documented format. WITH and W/OUT are case scores per arm, Δ is their difference, computed before the columns are rounded to two places (11/12 − 1/3 = +0.58 for the first case, so it can differ from the rounded columns by 0.01), COST is a list-price estimate, and NOTES shows the highest-weight failing grader from the with-arm.

From a mined session to a case. The documented bridge between Feedback and Evaluation is context.history_file in case.yaml: save a real failing transcript as a .jsonl in the case directory and the case's prompt becomes the next user turn, so you test the exact situation where Claude went wrong. For a path target such a case runs one arm by default ("on the assumption that the recorded conversation already reflects the plugin"); pass --ablation with-without to get Δ. The baseline grader works the other way round: it judges whether a run satisfies the criteria at least as well as a reference transcript you saved from a session that went right. Redact both before you commit them.

What a run can and can't see. Each run gets a temporary home, working directory and configuration: "Your user settings, hooks, CLAUDE.md files, MCP servers, other installed plugins, memory, and skills are absent." Built-in tools beyond the read-only set are removed unless you grant them with --allow-tools; a Bash grant runs under the OS sandbox (and refuses to run on a machine with no sandbox backend). Real plugin MCP servers don't start unless you pass --allow-real-servers or --mocks off; otherwise evals/mocks/<server>/<tool>.md files answer. "The case definitions are hidden from the agent", so Claude can't read its own graders.

Scoring rules that surprise people. In a two-arm run, every tool_used grader on Skill is reported with scored: false, because "a check like 'the skill was invoked' can never pass without the plugin" and would inflate Δ. The default --threshold is 1.0, so any imperfect case exits 1; set the bar you mean. "The with-minus-without delta is reported but never changes the exit code." And the bill: roughly cases × runs agent runs per arm, plus three judge calls per llm or baseline grader per run, all on your account.

skill-creator for single skills. /plugin install skill-creator@claude-plugins-official, then ask "evaluate my db-migration skill with skill-creator". It stores cases in evals/evals.json inside the skill directory, runs each case in its own subagent, writes grading.json and a with-versus-without benchmark.json, can run a blind A/B between two versions of the skill, and tunes the description with should-trigger and should-not-trigger prompts.

PitfallsA Δ near zero with the Skill grader failing is "the most common first finding": Claude isn't choosing your skill on natural phrasing, so fix the description before the body. Skill grader passes but Δ is negative: "suspect the judge before the plugin"; re-run with --judge-model sonnet and tighten the rubric. Wrong grader target: files lists created paths, not contents; use { source: file, path: ... }. Trust: evaluating a plugin "is the same trust decision as claude --plugin-dir"; its hooks run as you, outside the sandbox, and "a suite that passes says nothing about whether the plugin is safe".
Each line is one case, from its score without the skill (left axis) to its score with it (right axis); the thick tick on the right axis is --threshold. A line that ends below the tick is in the accent: that case makes the run exit 1, however steep its climb. A hollow end means a tool_used: Skill grader was left out of that score. Click a line or a table row for its runs. Toy model of the documented scoring rules (weighted grader fraction per run, mean over runs, Δ = with − without, tool_used: Skill excluded from scoring in two-arm mode unless marked arm: both, as the negative case's skill-not-fired check is, exit 1 when any case's with-arm score is below --threshold). Pass probabilities and costs are illustrative. Note how the guard hook protects the applied migration even in runs where the skill never fires.

Regression Checks

What it is. A regression suite is the set of cases every future change must keep passing. In a Claude Code setup, regressions come from three directions, and only one of them is your own change:

  • Your change. A new skill with a greedy description steals triggers from another skill. A longer description pushes the skill listing past its budget (1% of the context window), and Claude Code then "drops descriptions starting with the skills you invoke least". A new hook blocks a legitimate edit.
  • The model. "Aliases point to the recommended version for your provider and update over time." A suite that runs on sonnet can change score on a day nobody touched the config.
  • Claude Code itself. Bundled skills and system prompt guidance change between versions. Anthropic's own April 2026 postmortem traced a quality drop partly to a single verbosity line in the system prompt, which cost about 3% on their evals, and they responded with "a broad suite of per-model evals for every system prompt change" (postmortem). Your CLAUDE.md deserves the same treatment. /doctor prompt-audit (v2.1.283+) flags instructions written for older models after a model change.

How to apply it. Build the suite from real failures (Anthropic's eval guidance: "20-50 simple tasks drawn from real failures is a great start", Demystifying evals), add a case for every incident and every rollback, and run it in CI on every change to the plugin, pinned, plus a scheduled run on the moving alias to catch model drift separately:

# .github/workflows/plugin-evals.yml
name: plugin-evals
on:
  pull_request:
    paths: ["plugins/acme-db/**"]
  schedule:
    - cron: "0 6 * * 1"            # weekly drift check on the unpinned alias
jobs:
  eval:
    runs-on: ubuntu-latest
    timeout-minutes: 45
    steps:
      - uses: actions/checkout@v4
      - name: Judge with the base branch's graders and baseline
        if: github.event_name == 'pull_request'
        run: |
          # existing graders and the baseline file come from the base branch, so a PR can't
          # make its own test easier; new case files the PR adds stay (eval owners review them)
          git fetch --depth=1 origin "${{ github.base_ref }}"
          git checkout FETCH_HEAD -- plugins/acme-db/evals baselines/
      - uses: actions/setup-node@v4
        with: { node-version: "22" }
      - run: npm install -g @anthropic-ai/claude-code
      - name: Run the suite
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          MODEL=claude-sonnet-5-5                     # pinned for PRs
          if [ "${{ github.event_name }}" = "schedule" ]; then MODEL=sonnet; fi
          claude plugin eval plugins/acme-db \
            --trust-plugin --scaffold --allow-tools Write Edit \
            --json results.json --threshold 0.8 \
            --model "$MODEL" --judge-model claude-haiku-5-5 \
            --no-publish --max-cost-usd 20
      - name: Compare per case against the last adopted version
        if: always()
        run: |
          jq -e '.partial != true' results.json
          jq -r --slurpfile base baselines/acme-db-1.3.2.json '
            .cases[] as $c
            | ($base[0].cases[] | select(.name == $c.name) | .aggregates.score) as $b
            | select(($b - $c.aggregates.score) > 0.15)
            | "REGRESSION \($c.name): \($b) -> \($c.aggregates.score)"' results.json | tee drops.txt
          test ! -s drops.txt
      - uses: actions/upload-artifact@v4
        if: always()
        with: { name: eval-results, path: results.json }

The docs give the reason for pinning: "Pin it in CI so a model rollout isn't mistaken for a plugin regression." The per-case comparison matters because a suite-level threshold can hide one case collapsing while others improve. Leave partial: true documents and runs with skippedPaidGraders out of trend charts.

Security: CI evals run the plugin's code--trust-plugin asserts that you trust the plugin's hooks, scaffold scripts and servers, which run "outside the agent's sandbox". Use it only for plugins your org wrote. GitHub doesn't pass repository secrets to pull_request runs from forks, and that's what you want here: never run a fork's plugin with your API key. Gate external contributions behind a maintainer-triggered workflow.
A control chart over twelve weeks of weekly suite runs (toy data): the band is run-to-run noise around the baseline, which moves only with recorded changes, so points outside it need an explanation. Three plugin releases and one model change land during the window: an alias move if CI runs on sonnet, or a deliberate pin bump if it runs on a pinned ID. Switch between a pinned model ID and a moving alias, change runs per case, and see which drops a per-case alert would attribute to the wrong cause.

What you build: an outcome-graded comparison of three versions of a project config (configs/A as the baseline, B and C: CLAUDE.md, rules and skills) on the same five tasks. It first shows what each version loads before the first task (always-loaded tokens versus path-scoped rules that load on demand), then grades each run on what Claude changed, ran and said, and applies a written promotion gate: every task complete for both configs, at least 3 tasks, no regressions against the baseline, a pass rate at least the baseline's, cost within 10% unless the pass rate went up, and a real gain (a fixed task or a lower cost). A declined run (stop_reason refusal, checked first) or one whose terminal_reason isn't completed shows as INCOMPLETE, isn't graded and blocks the gate. It replays recorded runs by default.

cd labs && python3 autonomy-5/config_eval.py
cd labs && python3 autonomy-5/config_eval.py --real --configs A,C --tasks explain-tax --model haiku
cd labs && python3 autonomy-5/config_eval.py --runs autonomy-5/out/config_eval/real-runs --configs C --tasks explain-tax

The second line costs money: one claude -p per config and task in a temp copy of the sample app (2 runs here, $0.10 total), read-only tools in dontAsk, each capped at --max-turns 4 and --max-budget-usd 0.05 by default, with the total cap printed before anything runs. With only Read, Grep and Glob there's no Skill tool, so real runs measure CLAUDE.md and rules, not C's skill. The baseline A is always included, even if --configs leaves it out. Real runs save their raw stream-json to out/config_eval/real-runs/, and the third line re-grades them offline after you change a grader; with no saved runs it exits 2 and grades nothing.

What to observe: B is shorter and cheaper and fixes add-code, but it dropped the integer-cents line and bulk-discount now uses a float. Its pass rate equals the baseline's (4/5), and it's still rejected, because the gate counts regressions, not averages. C moves the money rule into .claude/rules/money.md with paths: tinyapp/** and ships 5/5 with about half of A's always-loaded tokens. The real example on one task can't ship anything: it ends in "rejected: insufficient evidence (1 task(s), one trial each)" and "keep A", which is the gate doing its job. There's no pooled delta or noise estimate: one trial per task is a demo, not evidence, and the output tells you to rerun real evals several times; the lab's README shows a real run where the right answer failed a too-literal grader, and the fix was the grader, not the config.

Open the lab walkthrough

Exercise: one case, two arms

Pick a skill you rely on. If it isn't in a plugin yet, scaffold one around it with claude plugin init my-tools --with skills and copy the skill in. Then write two cases with claude plugin eval init --bare <name>: one prompt that should trigger the skill (phrased the way you'd type it, without naming the skill) and one that shouldn't. Give each a result grader and a step grader. Run claude plugin eval . --runs 1 --ablation none until the graders behave, then run the full two-arm suite and read Δ.

Show a solution

For the should-not-trigger case, use a step grader that must see zero calls, and score it in both arms:

---
type: tool_used
tool: Skill
input_match: '"skill"\s*:\s*"(?:[\w-]+:)?my-skill"'
min: 0
max: 0
arm: both
---

Typical first results: the should-trigger case shows Δ ≈ 0 because the description doesn't match natural phrasing (fix the description, put the key use case first); the should-not-trigger case scores 1.00 in both arms (good, it guards against greed later). If claude plugin eval says "No eval cases found", no <case>/prompt.md or case.yaml exists under the eval directory in effect (usually: you're not at the plugin root), or your --case/--tag filters matched nothing. A case with no grader is a different error: it fails to load with invalid case.yaml naming graders. If it exits 1 with every case at 0.9, that's the default --threshold 1.0.

Key takeaways

  • Climb the proof ladder in order: reproduced, delta, regression-free, canary, adopted. The rung you need is set by blast radius.
  • A baseline removes exactly one thing: no plugin, skillOverrides: "off", a repo copy without the line. Pin model ID, effort and Claude Code version; use fresh sessions.
  • claude plugin eval runs isolated claude -p children in two arms, three runs each by default, scores weighted grader fractions, excludes Skill-invocation graders from two-arm scoring, and gates CI on --threshold, not on Δ.
  • Small n is noisy: prefer more cases over more runs, regex over long-text judges, and per-case comparisons over a single suite threshold.
  • Run the suite pinned on every change and unpinned on a schedule, so model drift and plugin regressions are never confused.

Distillation

Distillation turns a lesson you've confirmed into the smallest artifact that reliably changes behavior, placed where it loads only when it's needed. The two decisions are which artifact (does it need to be enforced, always known, known in one area, or available on demand?) and what goes in it (the steps that actually worked, not the ones you wish had).

Pick one of the eight lessons from the sorting exercise below and walk it: answer yes or no and the path lights to its home. Ask the questions top to bottom and stop at the first yes. Enforcement comes first because prose can't guarantee anything: CLAUDE.md is "context, not enforced configuration". The right-hand column covers packaging and isolation, which apply on top of any of the left-hand answers.

The docs' extension overview gives the triggers in the order most teams hit them: "Claude gets a convention or command wrong twice" → CLAUDE.md; "You paste the same playbook or multi-step procedure into chat for the third time" → a skill; "A side task floods your conversation with output you won't reference again" → a subagent; "You want something to happen every time without asking" → a hook; "A second repository needs the same setup" → a plugin. And: "The same triggers tell you when to update what you already have."

Sessions into Skills

What it is. The best source for a skill is a session where you and Claude finally got a procedure right, after the corrections. That session contains the trigger phrasing you actually used, the commands that worked in the order they worked, and the gotchas you hit. Distilling it means extracting those three things into SKILL.md while the session is still in context.

How to apply it. At the end of the successful session, ask for the skill explicitly, and ask for the rules that must always hold to be listed separately so you can enforce them:

Turn what we just did into a project skill at .claude/skills/db-migration/SKILL.md.
- description: when to use it, in the words I'd naturally type, key use case first
- body: the steps we actually ran, in order, with the exact commands; then the gotchas
  we hit today, one line each
- do NOT put "never edit applied migrations" in the skill as prose; list every
  must-always rule at the end of your reply so I can turn them into a hook
Then propose two prompts that should trigger the skill and one that shouldn't.
---
name: db-migration
description: Write or change a Postgres schema migration under db/migrations (tables, columns, indexes, constraints, backfills). Use when asked for a schema change, a new index, or a data backfill.
allowed-tools: Bash(make migration *) Bash(make db-check)
---

# Writing a migration

1. Generate a new pair: `make migration name=<snake_case_summary>`. It creates
   `NNNN_<name>.up.sql` and `NNNN_<name>.down.sql`. Never reuse a number.
2. Up file:
   - Index on an existing table: `CREATE INDEX CONCURRENTLY IF NOT EXISTS ...`,
     one per file, with `-- migrate:no-transaction` on line 1 (CONCURRENTLY can't
     run inside a transaction).
   - New NOT NULL column: add it nullable, backfill in batches, then SET NOT NULL
     in a later migration.
3. Down file: the exact inverse (`DROP INDEX CONCURRENTLY IF EXISTS ...`).
4. Run `make db-check` and show its output before you say you're done.

## Gotchas
- `orders` is large: anything that rewrites it needs a rollout note in the PR.
- The runner sorts by numeric prefix; check the latest number first.

Built-in distillers. Claude Code ships three skills that do this for a specific job. /run-skill-generator "gets your app running from a clean environment, captures what worked (the install commands, the env vars, the launch script), and commits it as a per-project skill at .claude/skills/run-<name>/". /verify records its own recipe at .claude/skills/verify/SKILL.md when it had to work one out, and "Claude edits the recorded file only when it steered a run wrong", so the file is stable enough to commit. And the skill-creator plugin interviews you, drafts the skill, and runs its eval loop.

PitfallsAuthoring context: the skill looks complete in the session that wrote it; test it in a fresh one. Instructions that fade: Claude Code "doesn't re-read the file on later turns", and after compaction it "can keep only the start of an invoked skill" (5,000 tokens per skill, 25,000 total), so put the critical steps first and word them for the whole task ("Run the tests after every edit"). Must-hold rules in prose: if a step must happen every time, move it out of the skill: into a deny rule where a path can express it, and into a hook (optionally in the skill's own hooks frontmatter) where it needs logic. Review allowed-tools: it pre-approves tools for the invoking turn and "Workspace trust doesn't gate this field", so a repo skill can grant itself broad access.
The session goes into the pot as its transcript lines. Each step lights the lines it draws from and condenses them into one receiver: the description, the steps and the gotchas into SKILL.md, the must-hold rule into a hook, the requests into eval prompts. What stays in the pot is the residue: the wrong first attempt and the thanks. Below the still: the transcript (abridged) and the artifacts as they are assembled. Note what does not go into the skill.

Rules

What it is. A rule is a short, always-true instruction. It can live in a project CLAUDE.md, in .claude/rules/*.md (loaded at launch unless it has paths: frontmatter, in which case it is one of the path-scoped rules that "load only when Claude works with matching files"), in ~/.claude/rules/ for you alone, or in the managed CLAUDE.md for the organization. Rules are the cheapest artifact to write and the easiest to over-produce.

How it works, and its limit. CLAUDE.md content "is delivered as a user message after the system prompt", and "Claude treats them as context, not enforced configuration." That makes rules right for conventions and judgment, and wrong for guarantees. The Acme lesson splits accordingly:

---
paths:
  - "db/migrations/**"
---

# Migrations
- Files under db/migrations/ that exist on main are applied in production.
  Add a new migration instead of editing one; use the db-migration skill.

Path-scoped, so it costs nothing in sessions that never touch migrations. If a rule must survive compaction, "drop the paths: frontmatter or move it to the project-root CLAUDE.md": project-root CLAUDE.md is re-injected after /compact, path-scoped rules reload only when a matching file is touched again.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/guard-applied-migrations.sh",
            "onFailure": "block"
          }
        ]
      }
    ]
  }
}
#!/bin/bash
# scripts/guard-applied-migrations.sh: block Edit/Write on migrations git already tracks.
# Fails closed: a missing jq or any error exits non-zero, and onFailure "block" stops the call.
set -euo pipefail
command -v jq >/dev/null || { echo "guard: jq not found, blocking" >&2; exit 2; }
input=$(cat)
file=$(echo "$input" | jq -r '.tool_input.file_path // empty')
cwd=$(echo "$input" | jq -r '.cwd')
case "$file" in
  */db/migrations/*.sql) ;;
  *) exit 0 ;;                      # not a migration: allow
esac
if git -C "$cwd" ls-files --error-unmatch "$file" >/dev/null 2>&1; then
  echo "Blocked: $(basename "$file") is already tracked, so treat it as applied. Create a new migration with: make migration name=..." >&2
  exit 2                            # exit 2 blocks the call; stderr goes to Claude
fi
exit 0

Lives in the acme-db plugin's hooks/hooks.json. It's a defense-in-depth guardrail, not the boundary: the Edit|Write matcher never sees a Bash write such as sed -i, a > redirect or git checkout --, and a script that opens files itself gets past both the hook and the deny rule unless the sandbox is on. It earns its place because "tracked by git" is logic a path rule can't express, and it tells Claude what to do instead. onFailure: "block" (v2.1.295+) plus set -euo pipefail make a crashed or timed-out guard block the call instead of silently allowing it; the trade-off is that a broken script blocks every Edit and Write until fixed. Test it by piping a payload: echo '{"tool_name":"Edit","cwd":"'$PWD'","tool_input":{"file_path":"'$PWD'/db/migrations/0038_create_orders.up.sql"}}' | ./scripts/guard-applied-migrations.sh; echo $?

{
  "permissions": {
    "deny": ["Edit(/db/migrations/applied/**)"]
  },
  "sandbox": { "enabled": true }
}

If your repo moves applied migrations into a directory, this is the boundary and the hook is the guardrail. "Deny rules block in every mode, including bypassPermissions". Edit and Read deny rules apply to the built-in file tools, to Bash file commands Claude Code recognizes (cat, head, tail, sed; tee from v2.1.269) and to redirect targets (>, >>, 2>; < from v2.1.257). They don't cover a script that opens files itself (a Python or Node one-liner) or a command that reads without naming the file (grep -r): that's what the sandbox is for. With the sandbox on, Claude Code adds Edit deny rules to sandbox.filesystem.denyWrite, which holds at the OS level for every subprocess. One more caveat: without managed settings, or a Team or Enterprise /login as the session credential (an API key or CLAUDE_CODE_OAUTH_TOKEN doesn't count), an installed mod "can approve a call that a deny rule refuses or a PreToolUse hook blocked". For a fleet plugin, deliver the deny rule through managed settings. The leading / anchors the path at the project's primary working directory in project settings (./ would follow the current directory). A Bash deny rule, by contrast, "isn't a security boundary around the program".

How to write a rule that works. Concrete enough to verify ("Use 2-space indentation" beats "format code nicely"), with an alternative whenever you forbid something, written plainly (current models "follow a plainly worded line, and piling on emphasis mostly makes Claude over-apply the rule"), and with no contradiction elsewhere ("If two files give different guidance for the same behavior, Claude may pick one arbitrarily"). Promote rules from your auto memory feedback notes by pull request, not by copying them silently into a shared file.

Why the smallest artifact wins: context cost, adherence and survival after compaction

Each artifact has a different loading strategy (context cost by feature): CLAUDE.md loads in full and costs tokens on every request; skills put only their description in every request and load the body when used; path-scoped rules load on a file match; hooks cost "Zero, unless hook returns additional context"; subagents run in a separate window. A lesson promoted to the wrong level pays twice: once in tokens on every request of every session, and again in adherence, because "Longer files consume more context and reduce adherence."

Compaction changes the picture for long sessions. Per what survives compaction, project-root CLAUDE.md and unscoped rules are re-injected from disk, path-scoped rules and nested CLAUDE.md files reload on demand, invoked skill bodies are re-injected but capped at 5,000 tokens per skill and 25,000 total, and conversation-only instructions are gone. So a must-hold rule written only in a skill's last section can vanish mid-task, while a deny rule or hook keeps applying. The decision rule: enforce with a permission rule (plus the sandbox) when violation is costly, and add a hook where the condition needs logic; keep unscoped what must survive compaction; scope or skill-ify everything else.

Subagents

What it is. A subagent is the right home for a lesson about how work should be split: "A side task floods your conversation with output you won't reference again", or a check that needs fresh eyes because the main session has been staring at its own code. Recurring review findings distill well into a narrow reviewer that runs before every commit of the risky kind.

---
name: migration-reviewer
description: Reviews new or changed SQL migrations for table locks, reversibility and data-loss risk. Use after writing a migration and before committing it.
tools: Read, Bash
model: sonnet
effort: medium
memory: project
---

You review Postgres migrations in db/migrations for this repo. Report only problems
that would hurt production:
- locks on large tables (non-concurrent index builds, table rewrites)
- a missing down migration, or one that isn't the exact inverse
- edits to migrations that already exist on the main branch
For each finding give file:line, the risk and the fix. If there are none, reply
"no blocking findings". Don't report style.
Check your memory for patterns you've seen before; save new recurring ones to it.

Why Read, Bash and not Read, Grep, Glob, Bash: on macOS, Linux and WSL, Grep and Glob are provided only when a subagent's tool list leaves Bash out, and search runs through Bash instead, so the longer list would amount to the same two tools. This reviewer keeps Bash because it diffs against the main branch; an agent that only reads would list Read, Grep, Glob and drop Bash.

Why it works. The reviewer runs in its own context window and returns a summary, so verbose diffs don't crowd the main session. Its description decides when Claude delegates to it, exactly as a skill's description decides triggering. model: sonnet and effort: medium make the review cheaper than the main session (see Optimization › Routing). The memory: project field gives it a persistent directory at .claude/agent-memory/migration-reviewer/ that the subagent uses to "build up knowledge over time" and that is "shareable via version control".

A subagent that learns is a self-modifying artifactAgent memory, like your own auto memory, is a place where Claude edits its own instructions without a gate, and the project-scope kind is shared. It also widens the agent's tools: with memory set, "Read, Write, and Edit tools are automatically enabled so the subagent can manage its memory files", so this reviewer can edit any file in the repo, not only its notes. If you want a pure reviewer, drop memory; if you want both, scope its writes, for example with a PreToolUse hook in the subagent's frontmatter that blocks Edit|Write outside .claude/agent-memory/ (a project file but not plugin-safe: plugin subagents ignore hooks). With the project scope the notes are committed files, so review .claude/agent-memory/** diffs in pull requests like any other config change, and prune notes that encode a one-off. Plugin subagents ignore hooks, mcpServers and permissionMode "for security reasons", so a reviewer shipped in a plugin can't carry its own hooks; put those in the plugin's hooks/hooks.json.

Plugins

What it is. "A Claude Code plugin is a directory of skills, agents, hooks, MCP servers, or other components that Claude Code installs and loads as one unit." For the improvement loop, the plugin is the unit that matters most, because it's the one thing you can evaluate (claude plugin eval), version (version in plugin.json, claude plugin tag), distribute and pin (marketplace entries with ref/sha), measure (claude plugin details, skill_activated with plugin.name) and disable in one move (enabledPlugins). Distill into a plugin when "a second repository needs the same setup", or as soon as a lesson needs a governed rollout.

{
  "name": "acme-db",
  "displayName": "Acme database workflows",
  "version": "1.4.0",
  "description": "Migration skill, applied-migration guard hook and a migration reviewer for Acme Postgres services",
  "author": { "name": "Acme Platform Team" },
  "experimental": { "evals": "evals" }
}

name is the only required key and is permanent ("a renamed plugin is a different plugin to every existing install"). experimental.evals defaults to evals and sits in a container "whose manifest shape may still change".

# from the repo that grew the setup
mkdir -p plugins/acme-db/.claude-plugin plugins/acme-db/hooks plugins/acme-db/skills
cp -r .claude/skills/db-migration plugins/acme-db/skills/
cp -r .claude/agents plugins/acme-db/
# copy the hooks object from .claude/settings.json into plugins/acme-db/hooks/hooks.json,
# then REMOVE it from settings: a hook in both places "runs twice each time its event fires"
# (the same handler in two settings files runs once; the plugin's copy is separate)
claude plugin validate --strict ./plugins/acme-db
claude --plugin-dir ./plugins/acme-db                          # try it for one session
claude --plugin-dir ./plugins/acme-db plugin details acme-db   # always-on vs on-invoke tokens

The docs' form for measuring an unpublished plugin is claude --plugin-dir ./formatter plugin details formatter: the plugin has to be loaded in the same command.

PitfallsAlways-on cost: "An enabled plugin is part of every session, not only the sessions where you use it." Every skill, agent and command description is in every request whether or not anything runs, which is the cost claude plugin details reports as Always-on. Only plugin.json goes inside .claude-plugin/; components saved there don't load. A plugin-root CLAUDE.md isn't loaded as context (claude plugin validate warns about one), so instructions a plugin ships belong in a skill, and team rules still belong in the repo or in managed CLAUDE.md. Executable content: "A Claude Code plugin you install can execute arbitrary code on your machine with your user privileges", which is why plugins sit in a higher governance tier than prose.
Overfitting: when a distilled artifact only fixes the case that inspired it

A skill written straight from one session tends to encode that session's specifics: the table name, the exact phrasing of the request, the one gotcha that bit you. It then passes the eval case built from the same session and fails the next real request. Three habits keep distillation general. First, write the eval prompts from other sessions in the cluster, not the one you distilled from, so the case is held out. Second, always add should-not-trigger cases next to should-trigger ones: an over-broad description is the commonest regression a new skill causes. Third, prefer describing the decision ("index on an existing table → CONCURRENTLY") over the instance ("orders.customer_id"). If a skill needs a dozen special cases to pass its suite, it's probably several skills, or a rule plus a hook.

The same applies to automated distillation. A scheduled job that proposes a rule for every cluster above a threshold will eventually propose rules that exist to satisfy the miner, not the developers. That's a form of eval gaming, and the defense is the same: held-out evidence and a human approval step (see Governance).

Eight lessons from a month of transcripts. Drag each card into the bin where it should live (or select a card and press a bin), then check. Some have two defensible answers; the feedback says which one the docs favor and why.

Exercise: distill one lesson end to end

Take the top candidate from your lessons inbox. (1) Route it with the questions in the figure above. (2) Write the artifact: if it's a skill, run the distillation prompt at the end of a session where the procedure went well; if it's a must-hold rule, write the hook or deny rule and test it by piping a payload into the script. (3) Write two eval prompts from a different session than the one you distilled from, plus one should-not-trigger prompt. (4) Open a fresh session and try the two prompts by hand before you formalize them.

Show a solution

Most lessons split. "Never edit generated files in src/gen/" becomes a deny rule Edit(/src/gen/**) plus one CLAUDE.md line explaining how to regenerate (make proto), because the deny tells Claude what's blocked but not what to do instead. "How we write a migration" becomes a skill plus a path-scoped rule that points to it, plus a deny rule (if applied migrations live in their own directory) and the guard hook as a guardrail for the "already tracked" case. "Ana prefers terse answers" stays personal: her output style or auto memory, never a team rule. If your fresh-session try fails on the first prompt, the description is the usual culprit: rewrite it with the words from the failing prompt, key use case first.

Key takeaways

  • Route by enforcement need first: must-always → permission rule plus the sandbox as the boundary, with a hook as a guardrail where the condition needs logic; always-know → CLAUDE.md; one area → path-scoped rule; procedure or sometimes-needed knowledge → skill; isolation or fresh eyes → subagent; second repo or governed rollout → plugin.
  • Distill skills from the session that finally worked: trigger phrasing → description, working commands → steps, corrections → gotchas, must-holds → hooks.
  • Rules are context, not configuration. Keep them concrete, single-emphasis and non-contradictory, and know which ones survive compaction.
  • Subagents encode how work is split. A reviewer with memory: project learns, so review its memory like code.
  • The plugin is the unit you can evaluate, version, pin, measure and kill-switch, which makes it the natural vehicle for any shared lesson.

Optimization

Distillation adds artifacts. Optimization takes away what doesn't earn its place and routes work to the cheapest configuration that keeps quality where it was. Both halves are measured: every token of always-on context is paid on every request, and every cheaper route is a claim that quality didn't drop, which you prove with the same evals.

CLAUDE.md Pruning

What it is. CLAUDE.md pruning is the regular removal of instructions that cost context without preventing mistakes. The target is explicit: "target under 200 lines per CLAUDE.md file. Longer files consume more context and reduce adherence." Claude Code warns at startup and in /status when one instruction file is over the recommended length, and when files that are each within it add up past a combined limit (each CLAUDE.md, rules file and @path import counts separately).

The test, line by line. The best-practices guide asks two questions: "Could it find this by reading the code?" and "Would it actually go and look?" "If both are yes, leave it out." What stays: "How to confirm work in this repo", "Places where the code is misleading", "Decisions that aren't in the repo", and "Anything you've had to correct twice already". What goes: your architecture and file layout ("Claude reads the repo itself"), rules that can't have exceptions (a hook or a deny rule enforces them), and hooks you wrote for preferences: "if you have hooks for things that are only preferences, delete them and let Claude decide."

The tools.

  • /doctor "proposes trims for a checked-in CLAUDE.md: it cuts content Claude can derive from the codebase, such as directory layouts, dependency lists, and architecture overviews, and keeps pitfalls, rationale, and conventions that differ from tool defaults", and offers to move always-loaded guidance into skills and nested CLAUDE.md files that load on demand. It reports first and changes nothing until you confirm.
  • /doctor prompt-audit [path] (v2.1.283+) looks for "instructions written for older models, references to files or commands that don't exist, and files that contradict each other" across CLAUDE.md, CLAUDE.local.md, AGENTS.md, rules, skills, commands, subagents and output styles. Run it after every model change. The claude.dev post Getting the most out of Opus 5.5 gives a good example of what it catches: "Delete 'think carefully' lines. Opus 5.5 already thinks before every reply."
  • /context lists the memory files actually loaded; an InstructionsLoaded hook logs every load with its load_reason, which tells you whether a path-scoped rule ever fires.
  • Block-level HTML comments (<!-- ... -->) are stripped before injection, so maintainer notes and rationale cost nothing. @path imports don't help: "Imports help you organize a long file but don't reduce its context cost."

Pruning with evidence. Cutting by intuition can remove the one line that prevents a rare, expensive mistake. Prune like you'd refactor with tests: for each section, find the eval cases that cover the behavior it's meant to cause. Remove the section and run them. No drop: delete it. A drop: keep it, or move it somewhere cheaper (a path-scoped rule, a skill) and re-run. No covering case: write one before you decide, or keep the line if a violation would be severe.

A 15-section CLAUDE.md for the Acme repo, drawn to scale: each block is as tall as its tokens, and whatever hangs below the dashed 200-line target is shaded. For each section choose keep, cut, or the move it allows (a skill, a path-scoped rule or a hook); a cut block closes up, a skill leaves a 30-token description stub, and each moved row names where it goes. Toy model, illustrative numbers: a kept line's adherence falls as always-on instructions grow and as emphasis spreads (the docs' qualitative claims); a deleted needed line falls back to what Claude does unprompted.

Model and Effort Routing

What it is. Model routing assigns each kind of work the cheapest model and effort level that still meets its quality bar. Claude Code exposes routing at several levels:

LeverScopeNotes
/model, --model, model settingMain session/model saves a default for new sessions; press s on a row for session-only
opusplan aliasMain session"uses opus during plan mode, then switches to sonnet for execution"
Subagent model: and effort: frontmatterOne subagentOrder: per-invocation model → frontmatter → CLAUDE_CODE_SUBAGENT_MODEL → main model
Skill model: and effort:The invoking turnThe session model resumes on your next prompt
/effort, effortLevel, ultrathinkSession, or one turnultrathink requests deeper reasoning "on that turn without changing your session effort setting"; from v2.1.311, typed in the terminal, it can run that turn at xhigh
--advisor / /advisorMain sessionClaude decides mid-task when to consult a second model
availableModels, maxEffortLevelOrganization, usually via managed settingsRestrict what routing may choose; a managed model "is a default, not a lock"

What the guidance says. On Opus 5.5, Sonnet 5.5 and Haiku 5.5 the default effort is medium, and the model configuration docs warn that max "may show diminishing returns and is prone to overthinking".

Two posts on the claude.dev blog add cautions about effort: "before you raise effort, check whether the model has a way to check its work" (What a task costs on Opus 5.5), and effort "does not fix when the model has the wrong approach" (Spending your effort). On model choice, the official cost post says "Move down to Sonnet or Haiku for lookups, not for writing code" (What a task costs on Opus 5.5), while some practitioners report delegating coding to cheaper subagents successfully. Treat that as contested and measure it on your codebase.

---
name: ci-log-triage
description: Reads CI logs and returns the failing test, the first error line and the likely cause. Use when a CI job fails.
tools: Read, Grep, Glob
model: haiku
effort: low
---

Find the first real failure in the log you're given. Return at most 10 lines:
the failing test or step, the first error with file:line, and one sentence on the
likely cause. Never paste more than 20 lines of log.

It only reads the log it's handed, so it lists Read, Grep, Glob and no Bash; with Bash in the list, Grep and Glob wouldn't be provided on macOS, Linux and WSL anyway.

Routing is a non-inferiority claim. "Cheaper with the same quality" means quality didn't drop by more than a margin you declared in advance, not that a small eval showed no difference. Run the suite on both routes, for example claude plugin eval . --model claude-haiku-5-5 versus --model claude-sonnet-5-5, and adopt the cheaper route only if every slice stays within the margin. The same applies to --judge-model: a smaller judge is cheaper but "can mark a correct answer wrong because it's formatted differently".

Pitfall: routing that breaks the cache"Each model has its own cache", so switching the main session's model mid-task makes the next turn reprocess the whole conversation uncached. Changing effort is cache-safe on the 5.5 models and Fable 5.1 through the Anthropic API or a subscription, but not everywhere. "Pick your model and effort level at the top of a session." Route by giving work its own context (a subagent, a skill with context: fork), not by flipping /model back and forth.
Each workload in the Acme setup is a channel strip: press the knob to change its model, move the fader to set its effort, and watch its light (meets its bar, overkill, or misses) and the cost meter on the main bus. This tunes standing routes for each kind of workload in your setup and the config they imply; autonomy-3's matrix routes the eight tasks of one feature cycle. Assign a model and effort to each workload. Quality and cost indices are a toy model (relative units, not a price list). The panel flags routes that miss a workload's bar, routes that contradict the published guidance, and prints the frontmatter and flags to apply.

Tool and MCP Diet

What it is. Every capability you add has a standing always-on cost. With tool search on, which is the default, "MCP tools are deferred and discovered on demand", so only tool names and server instructions load upfront; a server with alwaysLoad: true, or ENABLE_TOOL_SEARCH=false, puts every schema in context. Skill descriptions sit in a listing whose budget "scales at 1% of the model's context window"; when it overflows, descriptions are dropped "starting with the skills you invoke least". Plugin descriptions are always on, which claude plugin details reports per component. A diet removes what isn't used and moves what's rarely used out of the always-on set.

How to measure.

  • /context: the MCP tools and Skills rows show what the model actually receives (the Skills row reflects the listing after the budget is applied).
  • /skill-doctor: "flags skills in the listing that have never been invoked" and lists plugins you haven't used recently. Start with the never-invoked skills that have the highest context cost.
  • /doctor: unused skills, MCP servers and plugins against their context cost, and slow hooks.
  • /plugin → Installed: a marketplace plugin moves under Not used recently after at least 14 days and 10 sessions unused, with a Last used: line.
  • /usage attribution: each MCP server's share counts "only the requests that consumed one of its tool results".

How to cut, from gentle to final. For a skill: "skillOverrides": {"legacy-context": "name-only"} keeps it listed without a description; disable-model-invocation: true (or "user-invocable-only") removes it from Claude's listing but keeps /name typable, which is right for a rarely used runbook; "off" hides it entirely. For MCP: /mcp disable <server>, and prefer CLIs where they exist, since tools like gh, aws, gcloud and sentry-cli "are still more context-efficient than MCP servers because they don't add any per-tool listing". For plugins: claude plugin disable. A code intelligence plugin is the one addition that usually pays for itself: a "go to definition" call "replaces what might otherwise be a grep followed by reading multiple candidate files".

Diet between sessions, not during themWith tool search deferring MCP tools (the default), "Claude Code keeps the tool list from the conversation's first request for the whole conversation", so disabling a server mid-session neither breaks the cache nor saves anything until the next session. When tools load upfront (alwaysLoad, ENABLE_TOOL_SEARCH=false, or tool search below its threshold or unavailable), adding a definition invalidates the cache, and so does removing one on purpose; plugin MCP server changes follow the same rules. Either way, make diet changes in settings, then start a fresh session. Stage removals: name-only for a week, check skill_activated and complaints, then off.
The session is a balloon carrying its always-on items as sandbags: a bag's size is the tokens it adds to every request, its tag is the uses a week, and hatched bags are dead weight. Press a bag to cut it loose, or use the table, and toggle tool search, which squeezes MCP bags to names-only pouches unless a server has alwaysLoad: true. Inventory of one developer's setup with usage counts like /skill-doctor and /usage would show; the table's categories mirror /context. Token figures and the 1,500 requests a week are illustrative, not measured from a real session.

Cost

Where to read it. /usage's Session block computes cost locally "from token counts at list price" (or your contracted modelPricing when an admin sets one), so it's an estimate; authoritative billing is in the Console. Since v2.1.251 the block adds a Prompt cache (main) line with the share of input served from cache, misses (with a likely cause from v2.1.260), expected rebuilds after compaction, and whether the cache is warm. Headless runs report total_cost_usd and a per-model breakdown in --output-format json ("client-side estimates, not authoritative billing data"). Across a fleet, the claude_code.cost.usage counter carries plugin.name when the active skill or subagent belongs to a plugin, which is how you price one plugin, provided OTEL_LOG_TOOL_DETAILS=1 is set: otherwise your own plugins appear as "third-party".

Calibrate with the documented baseline. "Across enterprise deployments, the average cost is around $13 per developer per active day and $150-250 per developer per month, with costs remaining below $30 per active day for 90% of users." If your outliers are far above that, the usual causes are the ones the docs list: long sessions never cleared, Opus left as the default for everything, cache misses after long pauses, idle /loop tasks and goal check-ins, and agent teams, which use "approximately 7x more tokens than standard sessions when teammates run in plan mode".

The levers, roughly in order of return. /clear between unrelated tasks ("Stale context wastes tokens on every subsequent message"); the right model per workload (above); CLAUDE.md content moved into skills ("Skills load on-demand only when invoked"); the MCP diet and CLIs; hooks that preprocess output before Claude reads it (the docs' example rewrites test commands through updatedInput so only failures come back); verbose work delegated to subagents on smaller models; lower effort where depth isn't needed; and specific prompts, since "Vague requests like 'improve this codebase' trigger broad scanning."

The improvement loop has a budget tooA two-arm plugin eval makes roughly cases × runs agent runs per arm, plus three judge calls per llm grader per run; /insights spends tokens on every run; a nightly miner is a scheduled agent. Cap each one: --max-cost-usd on claude plugin eval (exit 2 with partial results when hit), --max-budget-usd and --max-turns on claude -p. Give quick every-PR suites only free graders and --ablation none, and save two-arm judge runs for release candidates.
Always-on tokens are multiplied, cache or not

Every request in a session resends the prefix: system prompt and tools, then project context (CLAUDE.md, auto memory, unscoped rules), then the conversation. Prompt caching makes the repeated prefix much cheaper per token, but "The match is exact, so a change anywhere in the prefix recomputes everything after it", and the cache expires (by default one hour for the main conversation on a subscription within plan usage, and five minutes for subagents, compaction and everything on API keys or cloud providers; promptCacheTtl, subagentPromptCacheTtl and a subagent's experimental.cacheTtl can change that). So an always-on token is paid as a cache write once per cache lifetime and as a cache read on every request after that.

An illustrative calculation, not a measurement: trimming 1,500 tokens of derivable layout and dependency lists from CLAUDE.md, in a team of 50 developers averaging 400 requests per active day each, removes 1,500 × 400 × 50 = 30 million prefix tokens per day, mostly cache reads plus a write after every expiry. Whether that's material depends on your rates; the point is that the unit of always-on cost is tokens × requests × developers, while the unit of on-demand cost is tokens × uses. That's why moving a 700-token procedure from CLAUDE.md into a skill used twice a week is nearly always a win, and why the adherence argument usually dominates the cost argument anyway. Price questions belong on the pricing page, not in course arithmetic.

Exercise: a measured diet

In your busiest repo: (1) run /context and note the Memory files, Skills and MCP tools figures; (2) run /skill-doctor and /doctor; (3) run /doctor prompt-audit on your CLAUDE.md; (4) pick three cuts (one CLAUDE.md section, one never-invoked skill set to name-only, one MCP server you could replace with a CLI) and make them in a branch; (5) start a fresh session and compare /context. Then name the one eval case you'd want before merging the CLAUDE.md cut.

Show a solution

Typical findings: a directory tree and dependency list in CLAUDE.md that /doctor marks as derivable (often hundreds of tokens); a few skills with zero invocations, usually because their descriptions overlap a better skill; and a GitHub MCP server whose work gh already does. A good merge note for the CLAUDE.md cut reads like: "Removed project layout and dependency sections (derivable, flagged by /doctor). Covered by cases finds-config-loader and adds-api-route, both unchanged at 3/3 with and without the sections on claude-sonnet-5-5." If you can't name a covering case, write one or keep the section for now.

Key takeaways

  • Prune CLAUDE.md to under 200 lines with the docs' two-question test ("Could it find this by reading the code?" and "Would it actually go and look?"), /doctor trims and /doctor prompt-audit, and confirm risky cuts with covering eval cases.
  • Route models and effort per workload through subagent and skill frontmatter, not mid-session /model flips. Medium effort is the 5.5 default; raise it only after giving Claude a way to check its work.
  • A cheaper route is a non-inferiority claim: declare a margin, evaluate both routes, adopt only if every slice holds.
  • Diet with data from /context, /skill-doctor, /doctor, /plugin and /usage; prefer CLIs over MCP; stage removals with name-only; change tools between sessions (deferred tools don't change mid-session; upfront ones break the cache).
  • Read cost from /usage (including the cache line), total_cost_usd and OTel; benchmark against ~$13 per active day; and budget the improvement loop itself.

Governance

A shared Claude Code setup is production configuration that runs with your developers' credentials on their machines. Govern it like code: every change is proposed with evidence, tested at the rung its risk demands, approved by an owner who didn't write it, released under a version you can pin, and reversible by a lever you've rehearsed.

Proposing

What it is. A proposal is a change record: the problem, the evidence, the artifact diff, its risk tier, the evaluation plan and the rollback plan, in the pull request description. Writing it forces the questions the earlier topics answer, and it gives reviewers something to check other than the diff.

## Change record: acme-db 1.4.0
**Problem**: Claude edits applied migrations and builds indexes without CONCURRENTLY.
**Evidence**: 7 corrections in 5 sessions from 3 developers (2026-09-22 to 10-12, quotes
  in thread); 2 Code Review "Important" findings (#4411, #4467).
**Change**: new skill `db-migration`, PreToolUse guard hook, path-scoped rule pointer.
  `claude plugin details`: always-on +38 tok.
**Risk tier**: T2 (adds an executable hook to a shared plugin)
**Evaluation**: 3 new cases + 8 existing; 11/11 at --threshold 0.8; mean Δ +0.21 on
  claude-sonnet-5-5 (+0.33 on the 3 new cases); results.json attached; per-case: no drop vs 1.3.2
**Rollout**: acme-tools-latest channel, 7 days, ~10 devs. Guard metrics vs stable: reject rate
  on SQL edits, skill_activated (claude-proactive share), migration incidents
**Rollback**: stable stays on acme-db--v1.3.2; repoint latest, or ship 1.4.1;
  canary kill switch: managed enabledPlugins "acme-db@acme-tools-latest": false
  (the fleet switch also lists "acme-db@acme-tools": false)

Who proposes. Anyone, and that includes an agent. A weekly job can mine review comments and open a draft pull request of proposals, as long as the bot can only write proposal files and never approves or merges anything:

# .github/workflows/lesson-proposals.yml
name: lesson-proposals
on:
  schedule: [{ cron: "0 7 * * 1" }]
jobs:
  propose:
    runs-on: ubuntu-latest
    permissions: { contents: write, pull-requests: write }
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with: { node-version: "22" }
      - run: npm install -g @anthropic-ai/claude-code
      - name: Fetch last week's review comments
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          gh api "repos/${{ github.repository }}/pulls/comments?since=$(date -d '-7 days' -Iseconds)" \
            --paginate > review-comments.json
      - name: Draft change records (Claude gets the API key, not the GitHub token)
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          claude -p "Read review-comments.json. Cluster recurring findings on Claude-authored code.
            For each cluster with 3+ occurrences, write proposals/<slug>.md as a change record:
            problem, evidence with links, proposed artifact, risk tier, eval plan, rollback plan.
            Write nothing outside proposals/." \
            --tools Read,Grep,Glob,Write,Edit \
            --permission-mode dontAsk --allowedTools "Read" "Grep" "Glob" "Edit(./proposals/**)" \
            --max-turns 20 --max-budget-usd 2 --output-format json > run.json
      - name: Open a draft PR (a person triages; the bot never merges)
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          git config user.name "lesson-bot"; git config user.email "lesson-bot@users.noreply.github.com"
          git checkout -b "proposals/$(date +%F)"
          git add proposals/ && git commit -m "Weekly lesson proposals" || exit 0
          git push -u origin HEAD
          gh pr create --draft --title "Lesson proposals $(date +%F)" \
            --body "Machine-drafted. Each proposal needs evidence review and an eval before adoption."

Edit(...) path rules govern every file-writing tool, and --permission-mode dontAsk denies anything not pre-approved instead of prompting. Review comments are untrusted input (anyone who can comment can write text the bot reads), which is why the claude -p step holds no GitHub token, its tools stop at writing proposal files, and a person decides what's real. For gh pr create to work with github.token, the repository must allow GitHub Actions to create pull requests (Settings → Actions → General).

Pitfall: proposals without a null hypothesisA proposal that only lists evidence for a change invites adoption by enthusiasm. Ask every change record to name the result that would reject it ("if Δ on the target cases is under +0.15, or any should-not-trigger case drops, we don't ship"). Rejected proposals go to the lessons log with their results, so the same idea isn't re-proposed every month.

Testing

What it is. Testing is the gate between a proposal and an approval, and its depth is set by the risk tier. For a plugin release the gate is a fixed sequence:

  1. Static checks. claude plugin validate --strict ./plugins/acme-db (exit 1 on warnings such as an unknown manifest field or a missing version). /doctor prompt-audit plugins/acme-db for outdated or contradictory instructions.
  2. Unit checks of executables. Pipe documented payloads into each hook script and assert exit codes. Mods have claude plugin test for their *.test.ts files.
  3. Behavioral evals. The full suite with claude plugin eval, pinned, at the threshold, plus the per-case comparison against the last adopted version (Regression Checks).
  4. Security review of anything that executes: hooks/hooks.json, scripts, .mcp.json, bin/, skills with allowed-tools or ! commands. Hooks "execute shell commands with your full user permissions", and plugin hooks, monitors and MCP servers run outside the sandbox. /security-review on the branch is a first pass, not a sign-off.
  5. Dogfood, then canary. The author runs claude --plugin-dir ./plugins/acme-db for a few days; then a release channel carries it to a canary group.

Release channels. "Claude Code has no release-channel concept, and one marketplace serves one version of each plugin at a time." The documented pattern is two marketplaces whose entries point at different refs of the same plugin, with different name values:

{
  "name": "acme-tools",
  "owner": { "name": "Acme Platform Team" },
  "plugins": [
    { "name": "acme-db",
      "source": { "source": "git-subdir", "url": "acme/claude-plugins",
                  "path": "plugins/acme-db", "ref": "acme-db--v1.3.2" } }
  ]
}

The plugin lives in a subdirectory of a monorepo, so the source is git-subdir (url, path, ref, sha); a github source takes only repo, ref and sha and can't point inside the repository.

{
  "name": "acme-tools-latest",
  "owner": { "name": "Acme Platform Team" },
  "plugins": [
    { "name": "acme-db",
      "source": { "source": "git-subdir", "url": "acme/claude-plugins",
                  "path": "plugins/acme-db", "ref": "acme-db--v1.4.0" } }
  ]
}

Canary developers add acme-tools-latest instead of acme-tools. A user "can't have two marketplaces with the same name registered at once", which is why the names differ. It also means the canary's install id is acme-db@acme-tools-latest, which matters for every per-plugin setting and for the kill switch.

When something breaks, start with safe modeclaude --safe-mode starts with every customization disabled (CLAUDE.md, skills, plugins, hooks, MCP servers, agents, output styles, auto memory) while authentication, model selection, built-in tools and permissions work normally. "If the problem disappears in safe mode, you've narrowed the cause to one of the items you turned off." Managed plugins, skills, CLAUDE.md and MCP servers are turned off too, but managed hooks and settings policy still apply, so a guard delivered as a managed hook is still running. Then bisect with --plugin-dir and --setting-sources.

Approving

What it is. Approval assigns the decision to a person who owns the affected surface and didn't author the change. How much evidence they need is set by a risk tier, a policy your team writes once. A reasonable starting policy:

TierExamplesMinimum rungApprover
T0 · personalCLAUDE.local.md, ~/.claude/ skills and rules, your auto memory0–1You
T1 · project proseCLAUDE.md lines, .claude/rules/, skills without allowed-tools or ! commands, read-only subagents (none with memory, which enables Write and Edit), routing changes2 · deltaOne code owner
T2 · executable or sharedHooks, skills with allowed-tools or injected commands, MCP servers, plugins (especially with bin/ or hooks), agents with Bash4 · canaryCode owner + security reviewer
T3 · organizationManaged settings, managed CLAUDE.md, enabledPlugins and marketplace policy, autoMode rules5 · adoptedPlatform team, in a change window

How to apply it. Encode ownership with CODEOWNERS so the right approvers are required automatically, and give the eval suite a different owner from the artifacts it judges:

# .github/CODEOWNERS
/CLAUDE.md                     @acme/orders-leads
/.claude/rules/                @acme/orders-leads
/.claude/skills/               @acme/orders-leads
/.claude/agents/               @acme/orders-leads
/.claude/agent-memory/         @acme/orders-leads
/.claude/settings.json         @acme/platform @acme/security
/.mcp.json                     @acme/platform @acme/security
/plugins/acme-db/              @acme/platform
/plugins/acme-db/hooks/        @acme/platform @acme/security
/plugins/acme-db/scripts/      @acme/platform @acme/security
/plugins/acme-db/evals/        @acme/eval-owners

Why separate the graders' owners. A change that makes Claude better and a change that makes the graders easier both raise the score. Code Review reads REVIEW.md only from the base branch for exactly this reason. A pull request that edits an artifact and its own graders together should need both owners, and the regression comparison should run with the base branch's graders. That's the practical defense against eval gaming.

Agents propose; people approveThe Claude Code team's own rule: "An agent's approval never counts as a person's", and "the person directing the agent counts as one of the required reviewers" (How the Claude Code team does code review). Claude Code enforces the same principle internally: "A teammate can't approve a permission prompt or supply consent on your behalf." Don't build a loop where a reviewer subagent's "LGTM" merges a config change.
Six proposed changes to the Acme setup. Select a card, tick the evidence it has, and try to advance it. The gates between the columns show what the selected card's tier needs (evidence held / required). Each column's gate depends on the card's tier. Cards in Canary or Adopted can be rolled back, which records a lesson.

Versioning

What it is. Every adopted state of your setup should have a name you can return to. For repository config (CLAUDE.md, .claude/, .mcp.json) git is the version. For plugins the version is explicit, and its semantics trip people up:

  • version in plugin.json pins. "Setting it pins the plugin to that version until you change it." If you push commits without bumping it, "claude plugin update prints <name> is already at the latest version (1.0.0). and users keep the old copy". Either bump on every release or omit version so Claude Code uses the commit SHA (shortened to 12 characters). Don't set it in both plugin.json and the marketplace entry: plugin.json wins silently and claude plugin validate reports the mismatch.
  • Tags. claude plugin tag --push creates {name}--v{version}, for example acme-db--v1.4.0. Dependency ranges such as ^1.2 resolve against these tags.
  • Pins per entry. A marketplace entry's github, url or git-subdir source takes ref (branch or tag) and sha (a full 40-character commit; with both set, Claude Code checks out sha). Users can also pin a catalog with owner/repo#ref on marketplace add.
  • Names are forever. "Never change a published plugin's name"; use displayName for labels and the marketplace's renames map when a rename is unavoidable.

Version the harness too. Eval results record claudeVersion, and behavior can change with Claude Code itself. Fleets can hold the client steady with autoUpdatesChannel: "stable", a minimumVersion floor, or managed requiredMinimumVersion / requiredMaximumVersion. Tag telemetry with the config you're running (OTEL_RESOURCE_ATTRIBUTES="claude_config=acme-db-1.4.0") so every dashboard can split by version.

The effective config is a merge: what a version number doesn't capture

A session's behavior comes from several layers at once: managed settings and managed CLAUDE.md, user settings and ~/.claude/CLAUDE.md, project and local settings, the repo's CLAUDE.md files and rules (concatenated, root first), auto memory, every enabled plugin's components, MCP servers from four scopes, the Claude Code version, the model behind an alias, and effort. List keys such as permissions.allow merge across files; most scalar keys take "the value from the highest level that sets it". So "we're on acme-db 1.4.0" doesn't pin behavior, and two developers on the same commit can run materially different setups.

For anything you want to compare over time, record the whole tuple: Claude Code version (claude --version; claudeVersion in eval JSON), plugin versions (claude plugin list --json gives id, version, scope, enabled), the repo commit, the managed-settings revision from your MDM or admin console, and the pinned model ID. /status shows the "Setting sources" a session actually loaded. This is also why claude plugin eval isolates runs from user and project configuration: it measures the plugin, not the plugin plus whatever is on the author's machine. When a regression only reproduces on some machines, diff these tuples before you diff code.

Two release channels as two tracks; hover a station. Stable stays pinned to 1.3.2 while 1.4.0 runs on the canary channel. A guard metric trips, latest is repointed to 1.3.2 within the hour, a regression case is added, and 1.4.1 ships through the same gates before stable moves.

Rolling Back

What it is. A rollback returns users to the last adopted state. The levers differ in scope and, more importantly, in how fast they reach people:

LeverScopeHow it reaches users
git revert the config PROne repo's CLAUDE.md, rules, skills, settingsWhen developers pull. Running sessions keep the old CLAUDE.md until /clear, /compact or a restart; mid-session edits "don't apply" before that
Repoint the marketplace entry (ref/sha to the previous tag)Everyone on that marketplaceOn claude plugin update, or via auto-update, which is off by default for your own marketplace. When it's on, a session updates the plugin on disk up to ten minutes after its first message, and the new version loads after /reload-plugins or at the next launch
Fix forward: ship 1.4.1SameSame as above; keeps history linear and the version string fresh
Kill switch: managed "enabledPlugins": {"acme-db@acme-tools-latest": false} for the canary; add "acme-db@acme-tools": false for the fleetEvery machine receiving managed settings, for exactly the ids you listfalse blocks it at every scope and hides it from the marketplace. Keys are plugin@marketplace, so acme-db@acme-tools alone would leave the broken canary running. Server-managed settings refresh at startup and hourly; MDM every 30 minutes; files on change
claude plugin disable acme-db@acme-tools-latest (or @acme-tools), or skillOverrides "off" for a non-plugin skillOne developerImmediately for new sessions; /reload-plugins in a running one

How to apply it. Decide the triggers before the canary starts, and write them into the change record: for example "reject rate on SQL edits more than 1.5× the stable channel for two days", "any incident linked to a migration the plugin produced", or "a nightly per-case drop over 0.15". When one trips, pull the fastest lever that covers the affected users first (canary only: repoint acme-tools-latest; whole fleet: the kill switch), then fix forward. Afterwards, the failing scenario becomes a regression case, and the lesson goes in the log with the version that caused it.

PitfallsReusing a version string: users with 1.4.0 cached won't fetch a different 1.4.0; always bump. Rollback you never rehearsed: the kill switch needs an admin with access to managed settings at 2 a.m.; test it on a canary group first. Client-side control: managed settings "operate as a client-side control, not a security boundary"; on unmanaged devices a user can bypass them, so a kill switch stops an accident, not an adversary. Stale sessions: long-running background sessions keep what they loaded; tell canary users to restart sessions after a rollback.
Rollback triggers that neither cry wolf nor sleep through a regression

A guard metric is a hypothesis test you run every day of the canary, which creates two classic failures. Check a noisy ratio daily at a loose threshold and you'll eventually roll back a good change on noise; with five independent daily checks at a 5% false-alarm rate each, the chance of at least one false alarm is about 1 − 0.95⁵ ≈ 23%. Set the threshold so high that noise never trips it and a real 30% regression in a 10-developer canary may never reach significance before the window ends.

Practical rules that work at canary scale: compare against the stable channel over the same days, not against last month (work mix changes week to week); require persistence ("1.5× for two consecutive days") rather than a single spike; prefer counts with a clear causal link to the change (rejected edits on .sql files, blocked tool calls from the new hook, incidents) over global ratios; and give severe, unambiguous signals, such as one incident traced to a migration the plugin produced, an immediate trigger with no statistics at all. Whatever you choose, write the trigger into the change record before the canary starts, so nobody tunes it after seeing the data.

Pick an incident, pull a lever and scrub the clock: the crowd is the developers the incident affects, and each figure turns protected when that lever reaches them, in its own rhythm (the whole managed fleet at each settings refresh, people one by one as they update, pull or read your message). Figures a lever can't reach stay exposed. This is about which lever reaches whom; autonomy-2's rollback clock covers when a revert lands in running and new sessions. The curves are a toy model built from the documented refresh behavior (server-managed settings hourly, MDM every 30 minutes, plugin updates on request or auto-update); real rollouts depend on how often people start sessions and pull.

Exercise: write the policy and rehearse one rollback

For your team: (1) write a one-page risk-tier policy (tiers, examples, minimum rung, approvers) and a CODEOWNERS block that enforces it, with evals owned separately; (2) take one plugin or shared skill and publish it through two marketplaces (stable and latest) pinned to different tags; (3) push a deliberately broken version to latest, notice it with an eval or a guard metric, and roll back by repointing latest. Time each step.

Show a solution

The rehearsal usually surfaces three problems. The version wasn't bumped, so claude plugin update said "already at the latest version" and nothing changed. Auto-update was off for your marketplace, so canary users only received the fix when they ran claude plugin update themselves (turn it on per marketplace in /plugin → Marketplaces, or with "autoUpdate": true on a managed extraKnownMarketplaces entry). And running sessions kept the old components until a restart or /reload-plugins. Write all three into your runbook. A good target: canary rolled back in under an hour, fleet kill switch in under two.

Key takeaways

  • Every change ships with a change record: problem, evidence, artifact, tier, eval plan, rollout and rollback, plus the result that would reject it.
  • Agents may draft proposals with tools scoped to proposal files; only people approve, and the graders' owners differ from the artifact's.
  • Test in order: validate, unit-test executables, eval pinned with per-case comparison, security-review anything that runs, dogfood, canary via a second marketplace.
  • Version plugins explicitly: bump or omit version, tag with claude plugin tag, pin entries with ref/sha, never rename. Version the client and tag telemetry with config versions.
  • Know your rollback levers and their propagation: repoint for canaries, managed enabledPlugins: false for the fleet, per-user disable for one person. Decide triggers before the canary starts.

Session wrap-up

You now have the full loop for improving a Claude Code setup from its own evidence. Feedback finds lessons in transcripts, telemetry, /insights, review findings and corrections, read through documented interfaces and counted across sessions and people. Evaluation proves a change on a proof ladder against a baseline, with claude plugin eval, skill-creator or a headless A/B, pinned and repeated. Distillation puts each lesson into the smallest artifact that changes behavior: permission rules and the sandbox for guarantees, hooks as guardrails where a condition needs logic, CLAUDE.md for always-true facts, path-scoped rules for areas, skills for procedures, subagents for isolation, plugins for anything shared. Optimization removes what doesn't earn its context and routes work to cheaper models only on non-inferiority evidence. Governance wraps it all in change records, risk tiers, code owners, versions, channels and rehearsed rollbacks.

StageClaude Code mechanismsOutput
FeedbackTranscripts via get_session_messages() / -p --resume, cleanupPeriodDays, OTel (code_edit_tool.decision, tool_decision, skill_activated), /insights, /usage, Code Review findings, auto memory feedback notesLesson candidates with counts and quotes
Evaluationclaude plugin eval (two arms, graders, --threshold, JSON), skill-creator, claude -p A/B with pinned model, CI on PRs and scheduleA rung on the proof ladder
DistillationCLAUDE.md, .claude/rules/ with paths:, SKILL.md, PreToolUse hooks and deny rules, .claude/agents/ with memory:, pluginsThe smallest artifact that works
Optimization/doctor, /doctor prompt-audit, /context, /skill-doctor, skillOverrides, /mcp disable, subagent model:/effort:, /usage cache lineFewer always-on tokens, cheaper routes, same quality
GovernanceChange records, CODEOWNERS, claude plugin validate --strict, version + claude plugin tag, marketplace ref/sha, stable/latest marketplaces, managed enabledPlugins, --safe-modeAdopted, versioned, reversible config

How this connects

Labs for this session

Mine seven recorded sessions for repeated corrections, failed lookups and repeated procedures, then propose a hook, a path-scoped rule, a permission deny, a map line or a skill draft, each with its evidence. cd labs && python3 autonomy-5/transcript_miner.py (add --min-sessions 1 to see one-off corrections). Observe why "run the tests before finishing", which CLAUDE.md already says, becomes a Stop gate with CI as the real gate rather than another sentence. Point --transcripts at your own saved stream-json runs to mine your work.

Open the lab walkthrough

Compare three config versions on five outcome-graded tasks and apply a promotion gate. cd labs && python3 autonomy-5/config_eval.py (offline replay), or --real --configs A,C --tasks explain-tax --model haiku for a capped real run. Observe B rejected for one regression despite an equal pass rate, C shipping 5/5 with less always-loaded context, and a one-task real run refused as insufficient evidence.

Open the lab walkthrough

What to do next

  1. This week: raise cleanupPeriodDays if you want more history, install the correction logger hook, and run /insights and /skill-doctor.
  2. In two weeks: build your lessons inbox, pick the top candidate, distill it, and write two cases plus one should-not-trigger case.
  3. In a month: move your shared skills and hooks into a plugin with an evals/ suite, run it in CI pinned and on a schedule, and publish it through stable and latest marketplaces.
  4. Every quarter: prune CLAUDE.md with /doctor and /doctor prompt-audit, re-run routing comparisons after model releases, and rehearse one rollback.

This is the last session of the course. Go back to the course hub to see your progress across all four milestones.