# claude-md-doctor

Adopt this skill: https://proskills.md/skills/other/agent-clinic-claude-md-doctor-skills-claude-md-doctor

Page: https://proskills.md/skills/other/agent-clinic-claude-md-doctor-skills-claude-md-doctor
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/claude-md-doctor/SKILL.md
size: 8068
upstream: https://github.com/agent-clinic/claude-md-doctor/blob/main/skills/claude-md-doctor/SKILL.md

```text
---
name: claude-md-doctor
description: Give this repo's CLAUDE.md / AGENTS.md a checkup — size vitals vs official guidance, dead references, dead commands, stale claims — then backtest every rule against the repo's own Claude Code session history to see which rules were actually followed, ignored, or never used, and produce a doctor-style HTML report with evidence-cited prescriptions. Use when asked to check, diagnose, audit, review, improve, optimize, lint, grade, fix, clean up, shorten, or "doctor" CLAUDE.md, AGENTS.md, or agent instruction/memory files, or to find out whether CLAUDE.md rules actually work. Also use when a repo has NO memory file and the user wants one — "write/generate/suggest a CLAUDE.md (or hooks) from my sessions" — the skill mines the repo's real session history and drafts a proposed file with receipts.
argument-hint: "[repo path] [--include-user]"
---

# CLAUDE.md Doctor — exam procedure

You are running a checkup on this repository's agent-instruction files. The
deterministic work lives in scripts; your job is the judgment between them.
Do not re-derive what a script already measured, and do not skip a stage — the
report verifies the work-state manifest and will disclose skipped stages.

Definitions used below:
- `SCRIPTS` = `${CLAUDE_SKILL_DIR}/scripts` — Claude Code substitutes
  `${CLAUDE_SKILL_DIR}` with this skill's own directory at run time, so the
  scripts resolve no matter the working directory or how the skill was
  installed. Use it literally; do not try to locate the skill yourself.
- `REPO` = the repository to examine (the argument if one was given, else the
  current working directory).
- `WORK` = `REPO/.claude-md-doctor/work` (scripts default to this; pass
  `--work` to relocate, e.g. into a scratch directory to avoid writing in the
  user's repo — prefer that when the repo is not yours to dirty).

## Stage 0 — preflight

Run `python3 --version`. If python3 is missing, stop and tell the user this
skill needs Python 3.9+ (stdlib only, nothing to install).

## Stage 1 — intake

    python3 SCRIPTS/intake.py --repo REPO --work WORK

Then read `WORK/intake.json` (it is small). Note for later judgment:
- Is the project CLAUDE.md a **pointer** (`is_pointer`) to AGENTS.md? That is
  the healthy, officially-recommended pattern — the target is the patient.
  Never diagnose a pointer file as "too short." Check `pointer_style`:
  `symlink` and `import` work; **`bare-text` is a broken pointer** — a regular
  file containing just `AGENTS.md` without `@` means Claude Code never loads
  the target. That is a critical diagnosis with a one-character fix (`@`),
  unless you are examining a raw-fetched copy where symlinks flatten to text.
- Ancestor and user-scope files are context the session loads but the repo
  can't fix — mention them, don't prescribe changes to them unless asked.
- A file with scope `orphan-agents` means the repo has an AGENTS.md but no
  CLAUDE.md pointing at it — **Claude Code loads nothing**. That is a critical
  diagnosis with the official one-line fix (create a CLAUDE.md containing
  `@AGENTS.md`), and you should still run the full static exam on the
  AGENTS.md itself, since it becomes the patient the moment the pointer
  exists.
- If NO memory files exist at all, do not stop with an empty report — switch
  to **Mode B** (below): mine the session history and write the initial
  chart. Only when there is no session history either does the exam end,
  with the `/init`-plus-aggressive-pruning prescription and a note saying
  why nothing else could run.

## Stage 2 — vitals

    python3 SCRIPTS/vitals.py --work WORK

Read `WORK/vitals.json`. The script measured; you interpret. Detector notes:
- `init_boilerplate` means the file still opens with stock `/init` output — a
  generated-and-never-pruned marker.
- `emphasis_per_100_lines` matters as **density**, not presence (sparse
  emphasis is officially endorsed).
- High `dated_per_100_lines` suggests session-log/changelog accretion.
- Very low `imperative_ratio` on a large file suggests narrative documentation
  rather than instructions — read a sample and judge; the arcan case (a
  CLAUDE.md containing a sabotage manual) is why this check exists.
- **Judge the aggregate surface, not only each file** (`launch_loaded_combined`
  plus the file count): many individually-healthy files can still sum to a
  heavy standing context, and cross-file duplication or contradiction is
  invisible per-file. When the combined surface is the problem, prescribe the
  escalating ladder — consolidate duplicates, then a thin router/index over
  on-demand files, then a one-screen always-on invariants file with
  procedures moved to skills (citation id `surface-bloat`).

## Stage 3 — records check

    python3 SCRIPTS/refcheck.py --work WORK

Read `WORK/refcheck.json`. Your judgment passes:
1. **Review the failures, don't parrot them.** For each `missing` /
   `machine_specific` / `glob_empty` reference and each `missing` command,
   open the cited file:line and confirm it is a real reference (not prose that
   merely looks like a path — API endpoints, MIME types, git refs, and files
   the text describes as deleted are the common false positives). Record each
   false positive in `dismissed_refs` with its reason: the report shows only
   confirmed findings and discloses dismissals in a collapsed note.
2. **Extract checkable claims** the scripts cannot: countable assertions in
   the memory files ("3,540 tests across 374 files", "12 UI components",
   "there is no ESLint config"). Verify the cheap ones with quick commands
   (file counts, grep for configs). Do NOT run test suites or builds unless
   the user asked. Record each as `verified` / `drifted` / `unverified` with a
   one-line detail — `unverified` is an honest answer for anything expensive.

## Stage 4 — history backtest

Skip this stage only if intake found no session directory (`sessions.dir`
null) — and then say so in chat; the report's History section will state it.

### 4a — condense the transcripts

    python3 SCRIPTS/sessions.py --work WORK

### 4b — decompose the memory files into a rulebook (your judgment)

Write `WORK/rulebook.json` (schema documented at the top of `backtest.py`).
Guidance:
- **Decompose EVERY directive in the file** — the rulebook is the complete
  directive inventory, and the enforcement ladder's "N of M" is only honest
  if M is the whole file. Only **mechanically checkable** rules get matchers:
  bans and requirements visible in Bash commands or Edit/Write content, and
  finish-ordering rules via `ordering`. Judge-class and not-yet-mechanizable
  rules go in as **classification-only entries** (enforcement block, no
  matchers) — never force a regex onto a semantic rule. Informational
  content (facts, architecture, API semantics) stays OUT of the rulebook.
- For edit/write events the matchable text is `PATH: <file_path>` on the first
  line followed by the (truncated) new content — anchor path-based rules on
  `^PATH: .*…` and content rules on the body.
- Write **conservative** regexes (prefer false negatives over false
  positives), use `scope.paths` / `scope.exclude_paths` to confine
  file-scoped rules, and date each rule with `introduced` from
  `git log --follow --format=%aI -- <file>` when the file's history makes
  that cheap — sessions that ended before a rule existed must not count
  against adherence.
- **Classify every rule's enforcement** (the `enforcement` block — schema at
  the top of `backtest.py`). Split compound rules into clauses first; each
  clause classifies independently. The class is the cheapest reliable
  detector: `hook` (event-stream regex: bash/edit/path/tool-input/output
  gates, ordering, cadence — try the event-ordering and standing-invariant
  reframings BEFORE surrendering a rule to judge), `linter`/`test` (static
  analysis over artifacts: lint rules, discipline tests, import-graph
  boundaries — record `scope_kind: file|project`), or `judge` (only an
```

## File: README.md
upstream: https://github.com/agent-clinic/claude-md-doctor/blob/main/README.md

````text
<p align="center">
  <img src="assets/doctor.svg" width="96" alt="pixel robot doctor">
</p>

<h1 align="center">claude-md-doctor</h1>

<p align="center"><b>Give your CLAUDE.md — or AGENTS.md — a checkup.</b><br>
Vitals, lab work, diagnoses, prescriptions — and a backtest of every rule
against your own session history.<br>
No CLAUDE.md yet? The doctor mines your sessions and drafts one — every
line with receipts.</p>

<p align="center">
  <img src="https://img.shields.io/badge/License-MIT-2f6f5e" alt="MIT license">
  <img src="https://img.shields.io/badge/Made%20for-Claude%20Code-1c2024" alt="Made for Claude Code">
  <img src="https://img.shields.io/badge/Deps-none%20(Python%20stdlib)-5b6470" alt="No dependencies">
</p>

<p align="center">
  <img src="assets/report-card.svg" width="760" alt="Sample checkup report: grade B, a critical dead reference, an ignored rule with a session timeline showing verify never ran, and a prescription to graduate the rule to a hook">
</p>

> Linters check the file. Analytics grade your sessions. The doctor
> cross-examines one against the other — and cites receipts.

## Quickstart

As a Claude Code plugin (recommended):

```
/plugin marketplace add agent-clinic/claude-md-doctor
```

then install `claude-md-doctor` from the `/plugin` menu. Or via the
[skills.sh](https://skills.sh) CLI:

```
npx skills add agent-clinic/claude-md-doctor
```

Or bare: copy `skills/claude-md-doctor/` into `~/.claude/skills/`.

Then, in any repo, just ask — *"give my CLAUDE.md a checkup"* — or invoke
directly: `/claude-md-doctor:claude-md-doctor` (bare install:
`/claude-md-doctor`). The report lands in `.claude-md-doctor/report.html`
plus machine-readable `report.json`.

Requires Python 3.9+ (standard library only). Everything runs locally;
nothing leaves your machine.

## What the exam covers

- **Vitals** — effective size vs the official guidance (*"target under 200
  lines per CLAUDE.md file"* — [Claude Code memory docs](https://code.claude.com/docs/en/memory)),
  estimated token cost per session, structure, and pathology markers: stock
  `/init` boilerplate never pruned, emphasis saturation, changelog accretion.
- **Records check** — does everything the file points at exist? Dead file
  paths, paths from a teammate's machine, `@imports` that don't resolve,
  `pnpm`/`make` commands with no matching script, `.claude/rules/` scopes
  that match zero files.
- **Checkable claims** — countable assertions ("2,100 tests across 180
  files", "9 UI components; no dialog") verified against the repo. Inlined
  numbers rot; the doctor catches them.
- **The report** — a single self-contained HTML page: chart grade, chief
  complaint, per-finding evidence, the session-adherence History table, and
  concrete prescriptions, each footnoted with the official doc or study
  behind it (the evidence base lives in [docs/RESEARCH.md](docs/RESEARCH.md)).

It understands the real memory surface: `CLAUDE.md`, `.claude/CLAUDE.md`,
`CLAUDE.local.md`, nested files, `.claude/rules/*.md` (with `paths:` scopes),
`@imports` (depth 4, backtick-aware), `claudeMdExcludes`, ancestor
directories — and it treats the pointer-to-`AGENTS.md` pattern as healthy,
examining the target, while flagging the broken variant (pointer text without
`@`, which Claude Code never actually loads). A repo with an AGENTS.md but no
CLAUDE.md at all gets the doctor's simplest prescription: the official
one-line pointer, so Claude Code stops loading nothing.

## The backtest — check if CLAUDE.md actually works in your sessions

Your own Claude Code session transcripts (`~/.claude/projects/…`) already
record whether past sessions actually followed each rule in your CLAUDE.md.
The doctor decomposes the file into rules and replays them against that
history — per rule, a verdict with receipts:

| Rule | Opportunities | Compliance | Verdict |
|---|---|---|---|
| Never import the legacy API types | 12 | 100% | healthy |
| Run `verify` before you finish | 2 | 0% | **ignored** |
| Never hardcode a colour | 0 | — | inert |

Behind every number: matched excerpts, and for finish-ordering rules a
session-timeline strip showing exactly what ran after the last edit.
Two ideas drive the verdicts ([full taxonomy](docs/TAXONOMY.md)). Every rule
gets an **enforcement class** — the cheapest reliable detector:

| Class | Detector | Binds |
|---|---|---|
| `hook` | gate over tool calls (commands, edits, orderings) — *prevents* | the agent |
| `linter`/`test` | static analysis over the code itself | every agent **and** every human |
| `judge` | LLM audit, post-hoc, with a stated reliability ceiling | audit only |

~70% of real-world directives land in the first two — laws waiting to be
passed. And every violation is **triaged by cause**, because the cause picks
the medicine:

| Cause | What happened | Medicine |
|---|---|---|
| defiance-proven | the agent *echoed the rule*, then broke it | block-mode gate — the reminder already lost |
| defiance | violated in fresh context | warn-hook, then block |
| dilution | drowned late in a heavy session | slim the file, move the rule to point-of-use |
| absence | non-root rule lost to compaction | re-inject; never block |

The arming ladder (reminder → warn → block) is set per rule from its own
violation forensics, and **review-then-arm hook proposals** are written to
the exam folder — nothing is ever installed automatically. Every checkup
also emits a **share-safe card** (grade, hearts, doctor's note — aggregates
only, never a string from your repo) and a **`claude-md-health.svg` badge**
for your README. Matcher fires are
sample-verified before they count, because matchers have bugs; unverified
results are banner-labeled provisional. Research shows agents silently skip
mandated steps while outputs still pass checks; only behavioral evidence
catches that — and it's free, sitting in your transcript history.

Run it on your own repo: the rules you'd bet on being followed are rarely the
ones that are.

## No CLAUDE.md? The doctor writes your chart

Most repos have no memory file at all (18 of the 20 on our own machine).
But their session transcripts already contain the unwritten rulebook, and
the same engine that backtests rules can run in reverse — mine the history,
then validate the checkable candidates against it:

| Signal | Example | Becomes |
|---|---|---|
| repeated corrections | "no, use pnpm not npm" typed in 3 sessions | a rule |
| failed → fixed pairs | `npm test` fails, `pnpm test` works, again | a rule (often a hook) |
| re-discovery | agent reads `package.json` at every session start | a fact, stated once |
| permission denials | you rejected `git push` twice | a "never" rule |
| repeated preambles | the same context paragraph pasted each session | a fact |

Grouped signals survive only with recurrence (≥2 sessions or ≥3
occurrences; re-discovery needs 3 distinct sessions) and carry recency
flags — a preference the repo moved past is marked stale for the judge
pass to decline. Corrections reach the judge ungated (wording varies too
much to group), deduped and capped, and are judged hardest. Each accepted
mechanically-checkable rule is then **replayed through the backtest** for
precise counts. The result is `PROPOSED-CLAUDE.md`: a lean
draft where every line carries its receipt as an HTML comment (stripped at
load, so it costs the adopter nothing), hook-class rules arrive as
review-then-arm guard proposals ("born mechanized"), and the report shows
the re-discovery tax your sessions have been paying. The draft is held to
the same 200-line vitals this tool grades everyone else on — the generator
refuses to prescribe the disease it diagnoses. Nothing is installed and no
CLAUDE.md is written for you — the draft lands in the exam folder
(`.claude-md-doctor/`), and adoption is your move. Repos that *do* have a CLAUDE.md get the
same mining as a **gap analysis**: rules you keep dictating by hand that
the file never says.

## FAQ

**Why does Claude ignore my CLAUDE.md?**
Usually
````
