Diagnose

From pedrohcgs/claude-code-my-workflow · View interactive version

Diagnose is an AI agent skill from the GitHub repository pedrohcgs/claude-code-my-workflow. Root-cause a failing or wrong empirical result with a disciplined reproduce → minimise → hypothesise → instrument → fix loop, instead of guessing-and-poking. Use when the user says "why is my regression wrong", "this number changed", "my script errors out", "the result won't reproduce", "debug this"

How to use this skill

Skill file

/diagnose — Root-Cause a Wrong or Failing Result

Find why an analysis errors, returns the wrong number, or won't reconcile — with a structured debugging loop rather than scattershot edits. Adapted from the diagnose pattern in mattpocock/skills, reshaped for empirical research code where the bug is usually a silent wrong number, not a crash.

The discipline: never edit before you can reproduce, and never fix before you can explain. A guessed fix that makes the symptom disappear without a named root cause is how a wrong number gets laundered into a published table.

When to use

Diagnose is symptom-driven and single-target: ONE wrong number / ONE failing run. Use a sibling instead when the job is different:

Phases

Phase 0 — Pin the symptom (expected vs. actual)

State the bug as a falsifiable gap before touching anything:

If expected/actual can't be stated, the task is understanding, not diagnosis — stop and clarify first.

Phase 1 — Reproduce deterministically (get a reliable red)

A bug you can't reproduce on demand can't be fixed, only hidden.

  1. Fix every source of nondeterminism: set the seed, pin the working directory, record sessionInfo() / pip freeze / Stata version (lean on CODE3).
  2. Re-run the smallest unit that exhibits the bug and confirm it fails every time. An intermittent failure is its own hypothesis (uninitialised RNG, order-dependent merge, race in parallel code) — note it and carry it into Phase 3.

Phase 2 — Minimise to an MWE

Shrink until the bug sits in the open:

The MWE is the deliverable even if the fix is later trivial: it's what makes the root cause undeniable.

Phase 3 — Hypothesise (enumerate, then rank)

List candidate causes before testing any — a written list beats poking because it prevents fixating on the first idea. For research code, walk the usual suspects (all of these run cleanly with no error message — they are silent-wrong-number bugs):

For a genuinely ambiguous bug, fan out the top competing hypotheses to parallel Agent subagents (one per hypothesis, each in a fresh context), each instructed to try to confirm its own cause on the MWE and report back — the loop-first analogue of asking three colleagues at once (see CODE1).

Phase 3b — Reduce the hypotheses (so you don't launder a guess)

Each hypothesis (whether tested by hand or by a fan-out Task) returns {hypothesis, evidence for, evidence against, confidence, one-line conclusion}. Then:

Phase 4 — Instrument & localize (bisect, don't stare)

Test the ranked hypotheses cheaply:

End Phase 4 with a one-sentence root cause naming the exact line/step and mechanism.

Phase 5 — Fix & verify (then guard against regression)

Confidence gate (the anti-laundering rule): do not apply a fix unless the root cause is named and its mechanism is explicit. If Phase 3b left a near-tie, behave as --no-fix: report the candidates and ask. Editing research code on an unproven hypothesis is exactly the laundering this skill exists to prevent.

Unless --no-fix is set:

  1. Apply the minimal fix at the root cause — not a downstream patch that masks it (prefer fixing the bad merge over filtering its duplicate rows afterward).
  2. Re-run the MWE → confirm actual == expected within the Phase-0 tolerance.
  3. Re-run the full unit and any dependent step → confirm the fix didn't move another number. If the result feeds a manuscript claim, re-check it (cross-ref the passport in CODE0).
  4. Note a prevention — the assertion/check that would have caught this earlier. One concrete guard per bug class:

| Bug class | One-line guard |

|---|---|

| Types & coercion | stopifnot(is.numeric(x)) after read |

| Missingness | explicit na.rm = FALSE; stopifnot(sum(is.na(x)) == 0) |

| Joins & shape | record nrow pre-merge; stopifnot(nrow(out) == nrow(left)) for a 1:1 join |

| Weighting | stopifnot(abs(sum(w) - 1) < 1e-8) or !anyNA(w) |

| Convergence | assert the optimizer/model convergence flag is OK before using estimates |

| Sample | one explicit filter() with a stated reason, not a mid-pipe drop |

| Environment | pin versions in renv.lock; set.seed() at the top of each script |

Propose the guard; don't silently install a test suite.

With --no-fix, stop after the root cause is named and report it for the user to fix by hand.

Worked example

A demand-forecasting model's held-out MAE jumped from 0.043 to 0.071 after a data refresh; nothing in the spec changed.

# Phase 1 — reproduce: set.seed(1); same script, same number every run. Red is stable.

# Phase 2 — MWE: one region, two horizons still shows the jump.
#           Strip to: read panel -> merge features -> lm(). Bug survives the merge step.

# Phase 4 — instrument: row counts before/after each step
nrow(panel)                          # 12,400  (expected)
nrow(merge(panel, feats, by="id"))   # 12,933  <-- inflated! a many-to-many merge

# Root cause: the refresh left duplicate feats rows for a subset of ids; the
# join fans those ids out, 12,400 -> 12,933 (+533 rows), re-weighting the MAE
# toward the duplicated units.

# Phase 5 — minimal fix at the root (dedup the key), NOT a downstream row filter:
feats <- feats[!duplicated(feats$id), ]
# re-run: MAE back to 0.043 within tolerance; full pipeline re-checked, no other number moved.

# Prevention (Joins & shape guard):
stopifnot(nrow(merge(panel, feats, by = "id")) == nrow(panel))

Output / report format

Write a short diagnosis to quality_reports/diagnoses/YYYY-MM-DD_<slug>.md (create the directory first: mkdir -p quality_reports/diagnoses). These reports may contain real data values and file paths — they are project-internal and gitignored, like session logs. Include:

Plus a chat summary leading with the one-line root cause.

Cross-language notes

The usual-suspects model is illustrated in R but the bug classes are language-neutral; the diagnostic idioms differ:

(Forkers in other fields: the five structural classes — Types, Missingness, Joins, Sample, Environment — are discipline-neutral; the econometric suspects above are the worked instance.)

Exit behavior

| Outcome | Action |

|---|---|

| Root cause NAMED (high confidence), fix applied, re-verified | report root cause + diff + prevention |

| --no-fix | stop at a named root cause; write the report, make no edit to source |

| Phase 0 blocked (no statable expected/actual) | halt, ask for the expected value — diagnosis needs a target |

| Phase 1 blocked (cannot reproduce / nondeterminism) | report the nondeterminism as the finding (it is the bug class) + how to make the analysis deterministic; do not edit blindly |

| Phase 3b near-tie / <50% | report the competing hypotheses and ask the user; do not apply a fix |

Flags

Step 0 — State the contract before touching anything

Before proposing or writing any fix, state in 3–5 bullets and stop for confirmation:

  1. What the function's or pipeline's documented contract is.
  2. What the reporter claims is broken.
  3. Whether the reported scenario is even in contract — a caller violating the contract is

not a bug in the callee.

  1. What the correct behaviour would be.
  2. What evidence would settle it.

This costs thirty seconds and prevents the most expensive class of wasted work: a confident fix

to a misunderstood contract. In one logged case the same semantic point had to be corrected

twice before a fix was scoped right, because the agent asserted a stance on the contract

rather than restating it and asking.

Severity follows the contract. A scenario outside the documented contract is at most a

documentation or validation issue, never a high-severity correctness bug. Inflating it

because it looks wrong is how a fix ends up changing behaviour users depend on.

Separate the audit pass from the repair pass

The strongest outcomes in the logged sessions began as investigations, not fix requests.

The messier ones mixed auditing with editing.

Audit pass — read-only. Produce a findings table: `severity | file:line | claim | evidence I

actually ran | proposed fix`. Mark anything not verified by execution as UNVERIFIED. Edit

nothing.

Repair pass — on approved rows only. The user picks which findings get fixed. This is

what makes declining a finding cheap, and declining findings is how scope stays bounded.

--no-fix runs the audit pass alone.

Cross-references

What this skill does NOT do

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.