---
title: "My Claude Code Setup"
subtitle: "A Comprehensive Guide to AI-Assisted Academic Workflows: Slides, Papers, Analysis, and Beyond"
author: "Pedro H. C. Sant'Anna"
date: "2026-05-31"
date-modified: last-modified
format:
  html:
    toc: true
    toc-depth: 3
    toc-location: left
    number-sections: true
    theme:
      - cosmo
      - custom.scss
    code-copy: true
    code-overflow: wrap
    highlight-style: github-dark
    smooth-scroll: true
    self-contained: true
    link-external-newwindow: true
    include-in-header:
      text: |
        <style>
        :not(pre) > code { background-color: rgba(185,151,91,0.1) !important; color: #8b6914 !important; padding: 0.15em 0.45em !important; border-radius: 3px !important; font-size: 0.87em !important; }
        pre code { background-color: transparent !important; color: inherit !important; padding: 0 !important; font-size: inherit !important; border-radius: 0 !important; }
        body:not(.floating):not(.docked) .page-columns.toc-left {
          grid-template-columns: [screen-start] 1.5em [screen-start-inset] 5fr [page-start] 35px [page-start-inset] minmax(0px,175px) [body-start-outset] 35px [body-start] 1.5em [body-content-start] minmax(450px,calc(1100px - 3em)) [body-content-end] 1.5em [body-end] 50px [body-end-outset] minmax(0px,200px) [page-end-inset] 35px [page-end] 5fr [screen-end-inset] 1.5em [screen-end] !important;
        }
        </style>
---

# Why This Workflow Exists {#sec-why}

## The Problem

If you've ever done serious academic work --- built lecture slides, drafted a research paper, run a data analysis pipeline --- you know the pain:

- **Context loss between sessions.** You pick up where you left off, but Claude doesn't remember *why* you chose that notation, *what* the instructor approved, or *which* bugs were fixed last time.
- **Quality is inconsistent.** One slide has perfect spacing; the next overflows. One regression table has proper formatting; the next is missing standard errors. Citations compile in Overleaf but break locally.
- **Review is manual and exhausting.** You proofread 140 slides by hand. You re-read your paper for the fifth time looking for the same kinds of errors. You miss a typo in an equation. A student or referee catches it.
- **No one checks the math.** Grammar checkers catch "teh" but not a flipped sign in a decomposition theorem, a misspecified regression, or a broken replication.

This workflow solves all of these problems. You describe what you want --- "translate Lecture 5 to Quarto," "review my paper before submission," or "analyze this dataset and produce publication-ready tables" --- and Claude handles the rest: plans the approach, implements it, runs [specialized reviewers](#sec-system), fixes issues, verifies quality, and presents results. Like a contractor who manages the entire job.

## What Makes Claude Code Different

Claude Code runs on your computer with full access to your file system, terminal, and git. It works as a **CLI tool**, a **VS Code extension**, or through the **Claude Desktop app** --- same capabilities, same configuration, different interface. Here is what that enables:

| Capability | What It Means for You |
|-----------|----------------------|
| Read & edit your files | Surgical edits to `.tex`, `.qmd`, `.R` files in place |
| Run shell commands | Compile LaTeX, run R scripts, render Quarto --- directly |
| Access git history | Commits, PRs, branches --- all from the conversation |
| Persistent memory | CLAUDE.md + MEMORY.md survive across sessions |
| Orchestrator runtime | Specific skills (`/qa-quarto`, `/review-paper --adversarial`, `/create-lecture`, …) run a real fan-out → reduce → judge → loop-until-dry runtime internally |
| Multi-agent workflows | 18 specialized agents for proofreading, layout, pedagogy, code review, fact-checking, AI-voice auditing, simulation + R-package review |
| Quality review | Advisory scoring inside `/commit` (halt + ask to override); targets: 80 commit, 90 PR, 95 excellence |
| CLI/headless mode | Run from scripts: `claude -p "compile all lectures"` |
| Browser bridge | Continue sessions on your phone via `/remote-control` |

::: {.callout-tip}
## Case Study: Econ 730 at Emory

This workflow was developed over 6+ sessions building a PhD course on Causal Panel Data. The result: 6 complete lectures (140+ slides each), with Beamer + Quarto versions, interactive Plotly charts, TikZ diagrams, and R replication scripts --- all managed by the orchestrator and reviewed by a suite of specialized agents across 5 quality dimensions.

While this case study centers on slides, every component --- agents, orchestrator, quality gates --- works identically for research papers, data analysis, and proposals.
:::

## How It All Works Together

Before diving into setup, here is the key insight: **skills hide most of the mechanics**. You describe what you want in plain English, Claude figures out which skill fits, and the skill runs the right agents and checks. There is no repo-wide daemon watching for plan approvals — the work happens *inside* the skill you invoke.

### What You Do vs What the Skill Does

| You Do | The Skill Does (once invoked) |
|--------|-------------------------------|
| Describe what you want | Claude selects and runs the right skill |
| Approve plans | The skill runs the orchestrator pattern internally |
| Review final output | Hooks fire on events (edit, save, compact) |
| Say "commit" when ready | Rules load based on files you touch |

### Example: "Fix my slides before tomorrow"

```
You: "Review my lecture slides and fix all issues before tomorrow's class"
     ↓
Claude invokes /slide-excellence, which internally:
  → Runs /proofread (grammar, typos, consistency)
  → Runs /visual-audit (overflow, layout, spacing)
  → Runs /pedagogy-review (narrative flow, notation clarity)
  → Synthesizes findings into prioritized fix list
  → Applies fixes (critical → major → minor)
  → Re-verifies everything compiles
  → Scores against quality gates
     ↓
You see: "Done. Fixed 12 issues. Score: 88/100. Ready to commit?"
You: "Yes"
     ↓
Claude runs /commit (only because you explicitly approved)
```

*One skill (`/slide-excellence`) runs the loop. There is no repo-wide orchestrator picking sub-skills à la carte; the orchestration lives inside the invoked skill.*

::: {.panel-tabset}

### Paper Review

```
You: "Review my paper draft and prepare it for submission"
     ↓
Claude invokes /review-paper, which internally:
  → Runs the substantive review (argument structure, methods, citations)
  → Spawns /proofread (grammar, consistency, formatting)
  → Spawns /validate-bib (cross-reference citations)
  → Synthesizes findings into prioritized fix list
  → Applies fixes (critical → major → minor)
  → Re-verifies everything compiles
  → Scores against quality gates
     ↓
You see: "Done. Fixed 18 issues. Score: 91/100. Ready to commit?"
```

### Data Analysis

```
You: "Analyze this dataset and produce publication-ready output"
     ↓
Claude invokes /data-analysis, which internally:
  → Explores, models, builds tables and figures
  → Spawns /review-r (code quality, reproducibility)
  → Produces R script, tables, and figures
  → Scores against quality gates
     ↓
You see: "Analysis complete. 3 tables, 4 figures. Score: 85/100."
```

:::

### What You Never Touch Directly

- **Agents** --- Specialized reviewers called by skills, not by you
- **Hooks** --- Fire automatically on events (you never run them)
- **Rules** --- Load automatically based on file paths

### Skills: The Only Commands You Might Type

Skills like `/proofread` or `/compile-latex` can be invoked two ways:

1. **Explicitly** --- You type `/proofread MySlides.tex`
2. **Automatically** --- Claude invokes them when relevant to your request

Most of the time, you just describe what you want and Claude handles the rest. Explicit skill invocation is there when you want precise control.

::: {.callout-important}
## The Bottom Line

**You talk, Claude orchestrates.** The 18 agents, 52 skills, and 32 rules exist so you don't have to think about them. Describe your goal, approve the plan, and let the system work.
:::

::: {.callout-note}
## You Don't Need All of This on Day One

This guide describes the full system --- 18 agents, 52 skills, 32 rules. That is the ceiling, not the floor. **Start with just CLAUDE.md and 2--3 skills** (`/compile-latex`, `/proofread`, `/commit`). Add rules and agents as you discover what you need. The template is designed for progressive adoption: fork it, fill in the placeholders, and start working. Everything else is there when you're ready.
:::

---

# Getting Started {#sec-setup}

You need three things: install Claude Code, fork the repo, and paste a prompt. Claude handles everything else.

## Prerequisites {#sec-prerequisites}

| Requirement | What It Is | How to Get It |
|-------------|-----------|---------------|
| **Claude Code** | The AI tool that powers this workflow | `curl -fsSL https://claude.ai/install.sh | bash` ([docs](https://code.claude.com/docs/en/overview)) |
| **Node.js 18+** | Required to run Claude Code | [nodejs.org](https://nodejs.org) |
| **Claude account** | Authentication for Claude | [Claude Pro or Max subscription](https://claude.ai) or [Anthropic API key](https://console.anthropic.com) (pay per token) |
| **git** | Version control (for fork/clone) | Pre-installed on Mac; `brew install git` or [git-scm.com](https://git-scm.com) |

**Optional** (install only what your project uses):

| Tool | Required For | Install |
|------|-------------|---------|
| XeLaTeX | LaTeX slides | [TeX Live](https://tug.org/texlive/) or [MacTeX](https://tug.org/mactex/) |
| [Quarto](https://quarto.org) | Web slides | [quarto.org/docs/get-started](https://quarto.org/docs/get-started/) |
| R | Figures & data analysis | [r-project.org](https://www.r-project.org/) |
| [gh CLI](https://cli.github.com/) | PR workflow | `brew install gh` (macOS) |

::: {.callout-note}
## What Does This Cost?

**Claude Pro or Max subscription**: Includes Claude Code usage with generous limits. Check [claude.ai](https://claude.ai) for current pricing and tier details. Best for most academics.

**API access** (pay per token): For heavy users or CI/CD. Use [effort levels](#sec-effort) and the [multi-model strategy](#multi-model-strategy-cost-vs-quality) to control costs.

Claude Code itself is free and open source. You pay only for the Claude model usage.
:::

::: {.callout-tip}
## Day 1 Checklist

- [ ] Install Claude Code: `curl -fsSL https://claude.ai/install.sh | bash`
- [ ] Fork the repo and clone it locally
- [ ] Run `claude` in the project directory (first run will prompt for authentication)
- [ ] Paste the starter prompt (fill in your project details)
- [ ] Wait for Claude to customize `CLAUDE.md` for your project
- [ ] Approve the configuration plan
- [ ] Ask Claude to do something: *"Review my slides"* or *"Create a lecture on [topic]"*
- [ ] Approve the task plan, watch it work, review the output

That's it. Everything else — agents, hooks, rules — runs automatically in the background.
:::

::: {.callout-tip collapse="true"}
## Trouble on Day 1?

**"command not found: claude":** Install Claude Code first: `curl -fsSL https://claude.ai/install.sh | bash`. Requires Node.js 18+ (`node --version` to check).

**Claude seems to ignore the configuration files:** Make sure you ran `claude` from inside the project directory (not a parent folder). Claude reads `.claude/` and `CLAUDE.md` from the current working directory.

**Hooks not firing (no notifications, no reminders):** Check that Python 3 is installed (`python3 --version`) and hook files are executable (`chmod +x .claude/hooks/*`).

**"What does plan approval look like?"** Claude presents a numbered plan and asks for your input. Say "approved", "looks good", or "revise step 3". That's it --- no special commands needed.

For more, see [Troubleshooting](#troubleshooting) in the Appendix.
:::

## Step 1: Fork & Clone

```bash
# Fork this repo on GitHub (click "Fork" on the repo page), then:
git clone https://github.com/YOUR_USERNAME/claude-code-my-workflow.git my-project
cd my-project
```

Replace `YOUR_USERNAME` with your GitHub username.

## Step 2: Start Claude Code and Paste This Prompt {#sec-first-session}

Open your terminal in the project directory, run `claude`, and paste the following. Fill in the **bolded placeholders** with your project details:

::: {.callout-note collapse="true"}
## Using VS Code or Claude Desktop instead of the terminal?

Everything in this guide works the same in any Claude Code interface. In **VS Code**, open the Claude Code panel (click the Claude icon in the sidebar or press Cmd+Shift+P → "Claude Code: Open"). In **Claude Desktop**, open your project folder and start a local session. Then paste the starter prompt below.

The guide shows terminal commands because they are the most universal way to explain things, but every skill, agent, hook, and rule works identically regardless of which interface you use.
:::

::: {.callout-tip appearance="simple"}
## Starter Prompt

I am starting to work on **[PROJECT NAME]** in this repo. **[Describe your project in 2--3 sentences --- what you're building, who it's for, what tools you use (e.g., LaTeX/Beamer, R, Quarto).]**

I want our collaboration to be structured, precise, and rigorous --- even if it takes more time. When creating visuals, everything must be polished and publication-ready. I don't want to repeat myself, so our workflow should be smart about remembering decisions and learning from corrections.

I've set up the Claude Code academic workflow (forked from `pedrohcgs/claude-code-my-workflow`). The configuration files are already in this repo (`.claude/`, `CLAUDE.md`, templates, scripts). Please read them, understand the workflow, and then **update all configuration files to fit my project** --- fill in placeholders in `CLAUDE.md`, adjust rules if needed, and propose any customizations specific to my use case.

After that, use the plan-first workflow for all non-trivial tasks. Once I approve a plan, switch to contractor mode --- coordinate everything autonomously and only come back to me when there's ambiguity or a decision to make. For our first few sessions, check in with me a bit more often so I can learn how the workflow operates.

Enter plan mode and start by adapting the workflow configuration for this project.
:::

**What this does:** Claude will read `CLAUDE.md` and all the rules, fill in your project name, institution, Beamer environments, CSS classes, and project state table, then propose any rule adjustments for your specific use case. You approve the plan, and Claude handles the rest. From there, you just describe what you want to build.

## Optional: Manual Setup

If you prefer to configure things yourself instead of letting Claude handle it:

::: {.callout-note collapse="true"}
## Manual Configuration Steps (click to expand)

**Customize CLAUDE.md** --- Open `CLAUDE.md` and replace all `[BRACKETED PLACEHOLDERS]`:

1. **Project name and institution**
2. **Folder structure** (adjust to your layout)
3. **Current project state** (your lectures/papers)
4. **Beamer environments** (your custom LaTeX environments)
5. **CSS classes** (your Quarto theme classes)

**Create your knowledge base** --- Open `.claude/rules/knowledge-base-template.md` and fill in:

1. **Notation registry** --- every symbol you use, where it's introduced, and anti-patterns
2. **Applications database** --- datasets, papers, and R packages you reference
3. **Design principles** --- what you've approved and what you've overridden

**Configure permissions** --- Review `.claude/settings.json`. The template includes permissions for git, LaTeX, Quarto, R, and utility scripts. Add any additional tools you use.

**Test it:**

```bash
# In Claude Code, type:
/compile-latex MyFirstLecture
/proofread Slides/MyFirstLecture.tex
python scripts/quality_score.py Slides/MyFirstLecture.tex
```
:::

You don't need to fill everything in upfront. Start with 5--10 notation entries and add more as you develop lectures. The starter prompt will set up the essentials --- you can always refine later.

## Requirements Specification (For Complex Tasks) {#sec-spec-then-plan}

For complex or ambiguous tasks, Claude may ask 3-5 clarifying questions to create a requirements specification before planning. This catches ambiguity early and reduces rework.

::: {.panel-tabset}

### Slide Creation
```
You: "Improve my lecture on hypothesis testing"

Claude: "Let me clarify:
1. What needs improvement (clarity, examples, pacing)?
2. Any student feedback to address?
3. Constraints (time, notation changes)?
4. Update which outputs (slides, web version, both)?"

[Creates spec with MUST/SHOULD/MAY priorities]
[You approve]
[Then enters plan mode]
```

### Data Analysis
```
You: "Analyze the survey data"

Claude: "Let me clarify:
1. What's the research question?
2. Expected output format (tables, plots, report)?
3. Any replication targets or baselines?
4. Computational constraints (runtime, memory)?"
```

### Code Refactoring
```
You: "Clean up my analysis scripts"

Claude: "Let me clarify:
1. What's the pain point (speed, readability, bugs)?
2. Breaking changes okay or preserve compatibility?
3. Testing infrastructure available?
4. Refactor scope (one file, whole project)?"
```

:::

After 3-5 questions, Claude creates a specification document in `quality_reports/specs/` with:

- **MUST** have (non-negotiable requirements)
- **SHOULD** have (preferred features)
- **MAY** have (optional enhancements)
- **Clarity status** (CLEAR/ASSUMED/BLOCKED for each aspect)

You approve the spec, then Claude plans implementation. This reduces mid-plan pivots by 30-50%.

**Template:** `templates/requirements-spec.md`

---

# The System in Action {#sec-system}

With setup covered, here is what the system actually *does*. This section walks through the three core mechanisms that make the workflow powerful: specialized agents, adversarial QA, and automatic quality scoring.

## Why Specialized Agents Beat One-Size-Fits-All

Consider proofreading a 140-slide lecture deck. You could ask Claude:

> "Review these slides for grammar, layout, math correctness, code quality, and pedagogical flow."

Claude will skim everything and catch some issues. But it will miss:

- The equation on slide 42 where a subscript changed from $m_t^{d=0}$ to $m_t^0$
- The TikZ diagram where two labels overlap at presentation resolution
- The R script that uses `k=10` covariates but the slide says `k=5`

Now compare with specialized agents:

| Agent | Focus | What It Catches |
|-------|-------|-----------------|
| `proofreader` | Grammar only | "principle" vs "principal" |
| `slide-auditor` | Layout only | Text overflow on slide 37 |
| `pedagogy-reviewer` | Flow only | Missing framing sentence before Theorem 3.1 |
| `r-reviewer` | Code only | Missing `set.seed()` |
| `domain-reviewer` | Substance | Slide says 10,000 MC reps, code runs 1,000 |

Each agent reads the same file but examines a different dimension with full attention. The `/slide-excellence` skill runs them all in parallel.

## The Adversarial Pattern: Critic + Fixer {#the-adversarial-pattern-critic-fixer}

The single most powerful pattern in this system is the **adversarial QA loop**:

```
+------------------+
|  quarto-critic   |  "I found 12 issues. 3 Critical."
|  (READ-ONLY)     |
+--------+---------+
         |
    +----v----+
    | Verdict |
    +----+----+
     /       \
APPROVED   NEEDS WORK
    |          |
  Done    +----v---------+
          | quarto-fixer |  "Fixed 12/12 issues."
          | (READ-WRITE) |
          +----+---------+
               |
          +----v----------+
          | quarto-critic |  "Re-audit: 2 remaining."
          | (Round 2)     |
          +----+----------+
               |
          ... (loop-until-dry: converge after 2 dry rounds; 5-round cap is a fallback)
```

**Why it works:** The critic can't fix files (read-only), so it has no incentive to downplay issues. The fixer can't approve itself (the critic re-audits). This prevents the common failure of Claude saying "looks good" about its own work.

::: {.callout-tip}
## Real Example

In Econ 730 Lecture 6, the critic caught that the Quarto version used `\cdots` (a placeholder) where the Beamer version had the full Hajek weight formula. The fixer replaced it. On re-audit, the critic found 8 more instances of missing `(X)` arguments on outcome models. After 4 rounds, the Quarto slides matched the Beamer source exactly.
:::

::: {.callout-note}
## Closing the visual loop with Computer Use (research preview, Apr 2026)

The critic-fixer loop above is text-only — it compares LaTeX source to Quarto source. It can't see the *rendered* slides. Anthropic's **Computer Use** (research preview, Mar/Apr 2026 Week 14) lets Claude open a PDF/HTML in a real viewer, click through, and verify visually. If you want closed-loop visual QA — "does the rendered slide actually look right?" — Computer Use closes the gap.

Optional, not required: `/qa-quarto` and `/visual-audit` already catch most issues without it. Treat Computer Use as an extra rung when text-level audits aren't enough (e.g., suspecting a TikZ render glitch that the source code looks fine for).
:::

## The Orchestrator: A Runtime, Not a Daemon

Individual agents are specialists. Skills like `/slide-excellence` and `/qa-quarto` coordinate a few agents for specific tasks. In day-to-day work, you don't have to think about which agents to run — the right skill runs the right agents for you.

The **orchestrator protocol** (`.claude/rules/orchestrator-protocol.md`) is a **real runtime**, built on the `Task` subagent primitive every Claude Code session has: skills fan out to forked reviewers, reduce their typed findings through a deterministic gate, judge with a post-judge hallucination guard, and loop until dry. What is **not** automatic is the *trigger*: nothing launches this loop on its own, and there is no background daemon — plan approval does NOT auto-trigger it. You invoke a skill (e.g., `/create-lecture`, `/qa-quarto`, `/review-paper --adversarial`) and the skill runs the runtime within its own scope. The human is the auditor of the disagreements the loop surfaces; this is explicitly not an autonomous daemon.

What's mechanically implemented today: `/commit` (verifier + quality_score), `/qa-quarto` (critic-fixer loop), `/review-paper --adversarial` (critic-fixer loop), `/slide-excellence` (multi-agent fanout), `/review-paper --peer` (editor + 2 referees + cross-artifact). See [Pattern 2](#pattern-2-contractor-mode-orchestrator) for the complete workflow.

## Quality Review: The 80/90/95 System {#sec-quality}

The [quality-gates rule](#sec-blocks) (`quality-gates.md`) defines scoring thresholds that `/commit` and review skills apply. Thresholds are **advisory** — enforced inside specific skills **and**, once you run `./scripts/install-hooks.sh`, by a real git pre-commit hook (`.githooks/pre-commit`) that runs the surface-sync + quality (≥80) gates on every commit. Bypass it sparingly with `SKIP_QUALITY_GATE=1` or `--no-verify`. Every file gets a quality score from 0 to 100:

| Score | Threshold | Meaning | Action |
|-------|-----------|---------|--------|
| **80+** | Commit | Safe to save progress | `git commit` allowed |
| **90+** | PR | Ready for deployment | `gh pr create` encouraged |
| **95+** | Excellence | Exceptional quality | Aspirational target |
| **< 80** | Blocked | Critical issues exist | Must fix before committing |

### How Scores Are Calculated

Points are deducted for issues:

| Issue | Deduction | Why Critical |
|-------|-----------|-------------|
| Equation overflow | -20 | Math cut off = unusable |
| Broken citation | -15 | Academic integrity |
| Equation typo | -10 | Teaches wrong content |
| Text overflow | -5 | Content cut off |
| Label overlap | -5 | Diagram illegible |
| Notation inconsistency | -3 | Student confusion |

### Mandatory Verification

The verification protocol (`.claude/rules/verification-protocol.md`) requires that Claude compile, render, or otherwise verify every output before reporting a task as complete. Skills that implement the orchestrator pattern enforce this as Step 2: VERIFY. This means Claude **cannot** say "done" from within those skills without actually checking the output.

::: {.callout-warning}
## Don't Skip Verification

In Econ 730, verification caught unverified TikZ diagrams that would have deployed with overlapping labels, broken SVGs in Quarto slides that wouldn't display, and R scripts with missing intercept terms that produced silently wrong estimates.
:::

::: {.callout-note}
## Model quality can regress — verification is the only durable defence

Anthropic publicly acknowledged a model-quality regression in [their Apr 23, 2026 engineering post "An update on recent Claude Code quality reports"](https://www.anthropic.com/engineering). The post identifies three contributing changes and is unusually candid about the limits of internal evals. Implication for our workflow: do not treat any given model checkpoint as a stable baseline.

The defences in this template all assume **model quality drifts**:

- **`/verify-claims`** with the Chain-of-Verification forked-verifier (the verifier cannot self-confirm even if the orchestrator's checkpoint regressed).
- **`/audit-reproducibility`** with `passport.yaml` (numeric claims are anchored to specific script output values, not to the model's recall of the values).
- **The cross-artifact review rule** (a paper's claims are checked against the code that produced them, not against the model's intuition about whether they're "plausible").
- **HIGH-WARN gate-refuse on `/commit`** (Pass 3A I) — a fabricated citation or numerical contradiction blocks the commit even if the model "feels confident."

Anthropic's post is also a useful reminder that running `/review-paper --variance N` (Pass 2C E) is the empirical answer to "should I trust this output?" — a single point estimate of model quality on a single task hides variance that the template's adversarial-review patterns surface.
:::

### Submission-readiness: stacking the verification lenses

For a paper headed to a journal, three orthogonal lenses run together — each catches a different class of failure:

| Lens | Skill | What it catches | Block-`/commit` on failure? |
|---|---|---|---|
| **Grammar / overflow** | [`/proofread`](#all-skills) | typos, search-and-replace artifacts, overfull `\hbox`, citation-format inconsistency | No (advisory) |
| **AI-voice tells** (v1.9.0) | [`/humanize`](#all-skills) | boilerplate transitions ("Moreover", "It is important to note"), AI-cliché lexicon ("delve", "navigate the complexities"), hedging stacking, sycophancy | No (advisory; author edits manually) |
| **Factual claims** | [`/verify-claims`](#all-skills) | fabricated citations, numerical contradictions, directional contradictions | **Yes — HIGH-WARN gate-refuses** (v1.9.0) |
| **Numeric provenance** | [`/audit-reproducibility`](#all-skills) | manuscript value ≠ script output value within tolerance | Yes via `passport.yaml` (v1.9.0) |

These are *complementary*, not redundant. A paper can pass `/proofread` (clean grammar) and fail `/humanize` (the prose reads as AI-drafted). It can pass `/humanize` (your own voice) and fail `/verify-claims` (citation fabricated). It can pass `/verify-claims` (citations real) and fail `/audit-reproducibility` (Table 2 doesn't match the code). Run all four before submission; reach for `/review-paper --variance N` for the simulated peer-review verdict on top.

**`/humanize` design choice**: detect-only, no `--rewrite` mode. Auto-rewriting AI tells degrades prose quality (cross-vendor research finding) and introduces new tells. The author reads the report and edits — that manual step is the price of preserving voice. If the report flags 8+ HIGH-severity tells per 1000 words, rewrite the affected paragraph from scratch rather than patching tell-by-tell.

## Creating Your Own Domain Reviewer {#sec-domain-reviewer}

The template includes `domain-reviewer.md` --- a skeleton for building a substance reviewer specific to your field. For example, in Econ 730, the domain reviewer caught that a slide claimed "$\hat{\beta}$ is consistent under parallel trends" while the cited paper (Callaway and Sant'Anna, 2021) actually requires a *conditional* parallel trends assumption --- a subtle but critical distinction that no grammar or layout checker would flag.

### The 5-Lens Framework

Every domain can benefit from these five review lenses:

| Lens | What It Checks | Example (Economics) | Example (Political Science) | Example (Physics) |
|------|---------------|--------------------|--------------------|--------------------|
| **Assumption Audit** | Are stated assumptions sufficient? | Is overlap required for ATT? | Is ignorability defensible given the observed covariates? | Is the adiabatic approximation valid here? |
| **Derivation Check** | Does the math check out? | Do decomposition terms sum? | Do conjoint AMCEs identify under Hainmueller–Hopkins–Yamamoto assumptions? | Do the units balance? |
| **Citation Fidelity** | Do slides match cited papers? | Is the theorem from the right paper? | Is the manipulation-check threshold cited from the original validation study? | Is the experimental setup correctly described? |
| **Code-Theory Alignment** | Does code implement the formula? | R script matches the slide equation? | `cjoint`/`survey::svyglm` weights match the design? | Simulation parameters match theory? |
| **Logic Chain** | Does the reasoning flow? | Can a PhD student follow backwards? | Does the causal claim survive the standard counterfactual challenge? | Are prerequisites established? |

The template ships **two concrete domain-reviewer customizations** in `.claude/agents/domain-reviewer.md`: an econometrics example (assumptions, identification, R/Stata code-theory alignment) and a political-science example (ignorability, conjoint AMCEs, `cjoint`/`survey` package defaults). Both follow the 5-lens structure; either is a viable starting point for your own field.

To customize, open `.claude/agents/domain-reviewer.md` and fill in:

1. Your domain's common assumption types
2. Typical derivation patterns to verify
3. Key papers and their correct attributions
4. Code-theory alignment checks for your tools
5. Logic chain requirements for your audience

---

# The Building Blocks {#sec-blocks}

Understanding the configuration layers helps you customize the workflow and debug when things go wrong. Claude Code's power comes from five configuration layers that work together --- think of them as the operating system for your academic project.

## CLAUDE.md --- Your Project's Constitution

`CLAUDE.md` is the single most important file. Claude reads it at the start of every session. But here is the critical insight: **Claude reliably follows about 100--150 custom instructions.** Your system prompt already uses ~50, leaving ~100--150 for your project. CLAUDE.md and always-on rules share this budget.

This means CLAUDE.md should be a **slim constitution** --- short directives and pointers, not comprehensive documentation. Aim for ~120 lines:

- **Core principles** --- 4--5 bullets (plan-first, verify-after, quality gates, LEARN tags)
- **Folder structure** --- where everything lives
- **Commands** --- compilation, deployment, key tools
- **Customization tables** --- Beamer environments, CSS classes
- **Current state** --- what's done, what's in progress
- **Skill quick reference** --- table of available slash commands

Move everything else into `.claude/rules/` files (with path-scoping so they only load when relevant).

```markdown
# CLAUDE.MD --- My Course Development

**Project:** Econ 730 --- Causal Panel Data
**Institution:** Emory University

## Core Principles
1. **Plan-first** — enter plan mode before non-trivial tasks
2. **Verify-after** — compile/render and check before reporting done
3. **Quality gates** — 80 to commit, 90 for PR, 95 for excellence
4. **LEARN tags** — persist corrections in MEMORY.md
5. **Single source of truth** — Beamer is authoritative; derive, don't duplicate

## Quick Reference
| Command | What It Does |
|---------|-------------|
| `/compile-latex [file]` | 3-pass XeLaTeX compilation |
| `/proofread [file]` | Grammar/typo review |
| `/deploy [Lecture]` | Render and deploy to GitHub Pages |
```

::: {.callout-important}
## Keep It Lean

CLAUDE.md loads every session. If it exceeds ~150 lines, Claude starts ignoring rules silently. Put detailed standards in path-scoped rules (`.claude/rules/`) instead --- they only load when Claude works on matching files, so they don't compete for attention.
:::

## Rules --- Domain Knowledge That Auto-Loads {#rules---domain-knowledge-that-auto-loads}

Rules are markdown files in `.claude/rules/` that Claude loads automatically. They encode your project's standards. The key design principle is **path-scoping**: rules with a `paths:` YAML frontmatter only load when Claude works on matching files.

**Always-on rules** (no `paths:` frontmatter) load every session. Keep these few and focused:

```
.claude/rules/
├── plan-first-workflow.md       # ~83 lines — plan before you build
├── orchestrator-protocol.md     # ~93 lines — review-fix runtime (fan-out → reduce → judge → loop-until-dry)
├── session-logging.md           # ~23 lines — three logging triggers
├── prompt-shaping.md            # ~32 lines — shape informal asks (ambient; replaces /prompt)
└── meta-governance.md           # ~251 lines — template vs working project
```

**Path-scoped rules** load only when relevant:

```
.claude/rules/
├── r-code-conventions.md        # paths: ["**/*.R"] — R standards
├── quality-gates.md             # paths: ["*.tex", "*.qmd", "*.R"] — scoring
├── verification-protocol.md     # paths: ["*.tex", "*.qmd", "docs/"] — verify before done
├── replication-protocol.md      # paths: ["scripts/**/*.R"] — replicate first
├── exploration-folder-protocol.md  # paths: ["explorations/**"] — sandbox rules
├── orchestrator-research.md     # paths: ["scripts/**/*.R", "explorations/**"] — simple loop
└── ...27 path-scoped rules total
```

The always-on rules are deliberately compact — together they fit well within the budget Claude reads reliably each session. `meta-governance` is a reference document for the template's dual nature (working project vs. public template) and loads passively. Path-scoped rules add rich, domain-specific guidance exactly when Claude needs it.

**Sync vs. translate:** The `beamer-quarto-sync` rule handles incremental edits --- fix a typo in Beamer, same fix goes to Quarto. The `/translate-to-quarto` skill is for full initial translation of a new lecture. Translate once, sync thereafter.

**Why rules matter:** Without them, Claude will use generic defaults. With them, Claude follows *your* standards consistently across sessions.

### Example: Path-Scoped R Code Conventions Rule

```yaml
---
paths:
  - "**/*.R"
  - "Figures/**/*.R"
  - "scripts/**/*.R"
---
```

```markdown
# R Code Standards

## Reproducibility
- set.seed() called ONCE at top (YYYYMMDD format)
- All packages loaded at top via library()
- All paths relative to repository root

## Visual Identity
primary_blue  <- "#012169"
primary_gold  <- "#f2a900"
```

The `paths:` block means this rule only loads when Claude reads or edits an `.R` file. When Claude works on a `.tex` file, this rule doesn't consume any of the instruction budget.

## Constitutional Governance (Optional)

As your project grows, some decisions become non-negotiable (to maintain quality, reproducibility, or collaboration standards). Others remain flexible.

The `templates/constitutional-governance.md` template helps you distinguish between:

- **Immutable principles** (Articles I-V): Non-negotiable rules that ensure consistency
- **User preferences**: Flexible patterns that can vary by context

### Example Articles You Might Define

- **Article I: Primary Artifact** — Which file is authoritative (e.g., `.tex` vs `.qmd`, `.Rmd` vs `.html`, notebook vs script)
- **Article II: Plan-First Threshold** — When to enter plan mode (e.g., >3 files, >30 min, multi-step workflows)
- **Article III: Quality Gate** — Minimum score to commit (e.g., 80/100, all tests passing)
- **Article IV: Verification Standard** — What must pass before commit (e.g., compile, tests, render)
- **Article V: File Organization** — Where different file types live (prevents scattering)

The template includes examples for LaTeX, R, Python, Jupyter, and multi-language workflows.

Use constitutional governance **after** you've established 3-7 recurring patterns that you want to enforce consistently. Don't create it on day one --- let patterns emerge first, then codify them. Skip it for solo projects with evolving standards, or when you prefer case-by-case decisions.

**Template:** `templates/constitutional-governance.md`

## Skills --- Reusable Slash Commands {#skills---reusable-slash-commands}

Skills are multi-step workflows invoked with `/command`. Each skill lives in `.claude/skills/[name]/SKILL.md`:

```yaml
---
name: compile-latex
description: Compile LaTeX with 3-pass XeLaTeX + bibtex
argument-hint: "[filename without .tex extension]"
---

# Steps:
1. cd to Slides/
2. Run xelatex pass 1
3. Run bibtex
4. Run xelatex pass 2
5. Run xelatex pass 3
6. Check for errors
7. Report results
```

**Skills you get in the template:**

| Skill | Purpose | When to Use |
|-------|---------|------------|
| `/compile-latex` | Build PDF from .tex | After any Beamer edit |
| `/deploy` | Render Quarto + sync to docs/ | Before pushing to GitHub Pages |
| `/proofread` | Grammar and consistency check | Before every commit |
| `/qa-quarto` | Adversarial Quarto QA | After translating Beamer to Quarto |
| `/slide-excellence` | Full multi-agent review | Before major milestones |
| `/create-lecture` | New lecture from scratch | Starting a new topic |
| `/commit` | Stage, commit, PR, merge | After any completed task |

::: {.callout-note}
## Built-In Skills

Claude Code ships with built-in skills beyond this template's 52: `/batch` orchestrates parallel refactoring across your codebase (using git worktrees for isolation), `/simplify` runs 3-agent code review and applies fixes, and `/debug` helps troubleshoot sessions. These complement the academic skills above.
:::

## Agents --- Specialized Reviewers {#agents---specialized-reviewers}

Agents are the real power of this system. Each agent is an expert in one dimension of quality:

```
.claude/agents/
+-- proofreader.md        # Grammar, typos, consistency
+-- slide-auditor.md      # Visual layout, overflow, spacing
+-- pedagogy-reviewer.md  # Narrative arc, notation clarity, pacing
+-- r-reviewer.md         # R code quality and reproducibility
+-- tikz-reviewer.md      # TikZ diagram visual quality
+-- quarto-critic.md      # Adversarial Quarto vs Beamer comparison
+-- quarto-fixer.md       # Applies critic's fixes
+-- beamer-translator.md  # Beamer -> Quarto translation
+-- verifier.md           # Task completion verification
+-- domain-reviewer.md    # YOUR domain-specific substance review
```

### Agent Anatomy

Each agent file has YAML frontmatter + detailed instructions:

```markdown
---
name: proofreader
description: Reviews slides for grammar, typos, and consistency
---

# Proofreader Agent

## Role
You are an expert academic proofreader reviewing lecture slides.

## What to Check
1. Grammar and spelling errors
2. Inconsistent notation
3. Missing or broken citations
4. Content overflow (text exceeding slide bounds)

## Report Format
Save findings to: quality_reports/[FILENAME]_report.md

## Severity Levels
- **Critical:** Math errors, broken citations
- **Major:** Grammar errors, overflow
- **Minor:** Style inconsistencies
```

::: {.callout-note}
## Why Specialized Agents?

A single Claude prompt trying to check grammar, layout, math, and code simultaneously will do a mediocre job at all of them. Specialized agents focus on one dimension and do it thoroughly. The `/slide-excellence` skill runs them all in parallel, then synthesizes results.

Claude Code also offers experimental **Agent Teams** --- multiple independent sessions that coordinate, share findings, and challenge each other's approaches. This is a research preview feature; the orchestrator + subagent pattern described here is more mature for academic workflows.
:::

### Multi-Model Strategy: Cost vs. Quality {#multi-model-strategy-cost-vs-quality}

::: {.callout-note}
## Current Anthropic lineup (verified 2026-06-10)

**Fable 5** (`claude-fable-5`, alias `fable`; opt-in via `/model fable` or the `best` alias) is the most capable Claude Code model — Mythos-class, GA 2026-06-09, \$10/\$50 per MTok, 1M context (128k max output), built for long-horizon agentic work; needs Claude Code ≥ 2.1.170 and falls back to Opus 4.8 on flagged content. **Opus 4.8** (`claude-opus-4-8`) is the API/account default and this template's routed high-judgment tier (GA 2026-05-28, \$5/\$25 per MTok, 1M context, defaults to `high` effort) — see the routing rule for why the fleet deliberately stays on it. **Opus 4.7** is the prior generation. **Sonnet 4.6** is the workhorse mid-tier (1M context). **Haiku 4.5** is the cost-efficient fast model. *Verified against Anthropic docs 2026-06-10.*

**Retirement notice:** Sonnet 4 and the original Opus 4 retire on **2026-06-15**. If your environment pins one of these (`ANTHROPIC_MODEL` env, hard-coded model IDs in CI, etc.), migrate before then. See [TROUBLESHOOTING.md](../TROUBLESHOOTING.md) for the migration checklist.
:::

Not all agents need the same model. Each agent file has a `model:` field in its YAML frontmatter. In v2.0 all 18 agents are **pinned** to an explicit model + effort tier (no longer `inherit`), following the 70/20/10 routing pattern below. You can re-tune any agent to optimize cost:

| Task Type | Recommended Model | Why | Examples |
|-----------|-------------------|-----|----------|
| Complex translation | `model: opus` | Needs deep understanding of both formats | beamer-translator, quarto-critic |
| Fast, constrained work | `model: sonnet` | Speed matters more than depth | r-reviewer, quarto-fixer |
| Mechanical default | `model: haiku` | Bounded, fast work | proofreader, slide-auditor |

**The principle:** Use Opus for tasks that require holding two large documents in mind simultaneously (translation, adversarial comparison). Use Sonnet for tasks with clear, bounded scope (fix these 12 issues, check this R script). Use Haiku for mechanical work. In v2.0 every agent is pinned explicitly rather than inheriting — see `agent-fleet.md` for the full fleet + tiers.

To change an agent's model, edit its YAML frontmatter:

```yaml
---
name: quarto-critic
model: opus   # pinned per agent-fleet.md (v2.0: no agent inherits)
---
```

::: {.callout-tip}
## Cost Savings

If you configure model-per-agent, a typical Beamer-to-Quarto translation runs the critic on Opus (2--4 rounds) while the fixer runs on Sonnet (same rounds). This can save roughly 40--60% compared to running everything on Opus, with no quality loss on the fixing step.
:::

### Advanced Agent Configuration {#sec-agent-config}

Beyond model selection, agent definitions support several configuration fields:

| Field | Purpose | Example |
|-------|---------|---------|
| `model` | Force a specific model | `haiku`, `sonnet`, `opus` |
| `maxTurns` | Limit agent iterations | `10` (prevents runaway loops) |
| `isolation` | Run in a git worktree | `worktree` (see [Pattern 12](#pattern-12-branch-isolation)) |
| `effort` | Override reasoning effort | `high` |
| `permissionMode` | Restrict permissions | `plan` (read-only agent) |
| `tools` | Whitelist specific tools | `["Read", "Grep", "Glob"]` |
| `disallowedTools` | Blacklist specific tools | `["Write", "Edit"]` |
| `skills` | Make specific skills available | `["compile-latex"]` |
| `background` | Run concurrently | `true` |

Example: a read-only proofreader that can't edit files:

```yaml
---
name: proofreader
model: sonnet
maxTurns: 15
tools: ["Read", "Grep", "Glob"]
---
```

Use `maxTurns` to prevent review agents from looping indefinitely, and `tools` to enforce read-only behavior for agents that should only produce reports.

### Cost-Conscious Composition: Caching, Routing, and Diagnostics {#sec-cost}

Cost is invisible until you look at the monthly invoice. Three levers, in order of impact:

**1. Prompt caching.** Anthropic's prompt cache lets repeated prefix tokens (system prompt, CLAUDE.md, large context blobs) hit a cached path at a fraction of the input price. Two things forkers should know:

- **The default TTL dropped from 60 min to 5 min** in early 2026. A long `/review-paper --peer` pipeline that took 12 minutes between turns now starts the second turn with a cold cache. For long pipelines on API / Bedrock / Vertex / Foundry plans, the opt-in `ENABLE_PROMPT_CACHING_1H` environment variable restores 1-hour TTL. On Claude Pro / Max subscriptions, Claude Code requests the 1-hour TTL automatically at no extra cost.
- **`cache_miss_reason`** (Anthropic public beta, 2026-05-13) is now exposed on Messages requests. Use it to diagnose why a long-running pipeline isn't getting cache hits (most often: a hook injected a timestamp that broke the prefix; or system-prompt drift between turns).

The Apr 2026 [TTL change cost analysis](https://dev.to/whoffagents/claude-prompt-caching-in-2026-the-5-minute-ttl-change-thats-costing-you-money-4363) estimates a 30–60% effective cost increase for long-running pipelines that don't opt into the 1-hour TTL. Worth a Saturday hour to instrument your most expensive skill (`/review-paper --peer` is typically the worst offender).

**2. Per-agent model routing.** The Multi-Model Strategy table above lists the principle; the **70/20/10 pattern** is the operational form:

| Model | Share of subagent calls | Use for |
|---|---|---|
| **Haiku 4.5** | ~70% | Mechanical work: TikZ extraction, citation reformatting, bib validation, proofread fixes, simple file lookups |
| **Sonnet 4.6** | ~20% | Review and critique: r-reviewer, slide-auditor, proofreader, quarto-fixer |
| **Opus 4.8** | ~10% | High-judgment work: editor, domain-referee, methods-referee, claim-verifier, manuscript review |

Set per-agent via `model:` in `.claude/agents/<name>.md` frontmatter. Typical savings vs. all-Opus: **50–80% on routed skills**, no quality loss on the mechanical tier. The community-converged ratio is documented in [Augment Code's routing data](https://augmentcode.com) and aligns with Aider's architect/editor split; we cite Anthropic's [Apr 8 2026 "Decoupling brain from hands"](https://www.anthropic.com/engineering) as the primary-source endorsement of the pattern.

**3. Effort budgeting.** The Effort Levels section earlier covered the `low | medium | high | xhigh | max` ladder. **Opus 4.8 defaults to `high`** — and its `high` does roughly what 4.7's `xhigh` did, for fewer tokens. So: let `high` be the default; drop to `medium`/`low` to save cost on mechanical work; reach for `xhigh` only for extended exploration (deep search, big refactors, the hardest `/review-paper` runs); `ultracode` (xhigh + dynamic workflows) for repo-scale autonomous tasks.

::: {.callout-tip}
## Monitoring: `/cost` and `/usage`

- **`/cost`** (Apr 2026 Week 15) — current session breakdown by model and cache hit-rate.
- **`/usage`** (Apr 2026 Week 16) — month-to-date totals + per-plan-tier remaining quota.

Run `/cost` after any `/review-paper --peer` pipeline. If your cache hit-rate is under 60% for the second/third turn, you're almost certainly being bitten by the 5-min TTL.
:::

::: {.callout-warning}
## Agent SDK credit-pool split — 2026-06-15

Starting 2026-06-15, `claude -p` headless subprocess calls (used by `/coarse-review` and any script that calls Claude Code in `-p` mode) draw from a **separate monthly Agent SDK credit pool**, decoupled from interactive credits. If `/coarse-review` starts failing after the cutover with credit-exhaustion errors even though your interactive session works, the Agent SDK pool is what's empty. See [TROUBLESHOOTING.md](../TROUBLESHOOTING.md) for the migration details.
:::

## Settings --- Permissions and Hooks {#settings---permissions-and-hooks}

`.claude/settings.json` controls what Claude is allowed to do. Here is a simplified excerpt --- the template includes additional permission entries for git, GitHub CLI, PDF tools, and more:

```json
{
  "permissions": {
    "allow": [
      "Bash(git status *)",
      "Bash(xelatex *)",
      "Bash(Rscript *)",
      "Bash(quarto render *)",
      "Bash(./scripts/sync_to_docs.sh *)"
    ]
  },
  "hooks": {
    "Stop": [
      {
        "hooks": [{
          "type": "command",
          "command": "python3 \"$CLAUDE_PROJECT_DIR\"/.claude/hooks/log-reminder.py",
          "timeout": 10
        }]
      }
    ]
  }
}
```

**Permission modes.** Claude Code has five permission modes that control how much autonomy Claude gets:

| Mode | Internal Name | Behavior | When to Use |
|------|--------------|----------|-------------|
| **Normal** | `default` | Asks before risky actions | Day-to-day work --- approve each edit |
| **Auto-accept edits** | `acceptEdits` | Auto-approves file edits | Trusted batch operations (rename across 20 files) |
| **Don't ask** | `dontAsk` | Auto-denies tools unless pre-approved in allowlist | Restricted environments where only allowlisted tools run |
| **Plan** | `plan` | Read-only --- no edits allowed | Exploring code, reviewing before acting |
| **Auto** | `auto` | Classifier-gated; everything runs unless flagged risky. On Team / Enterprise / API and rolling out to Max; needs Opus 4.6+ or Sonnet 4.6 (Mar 2026 Week 13; `--enable-auto-mode` flag retired Apr 2026 Week 16) | Long autonomous tasks with safety net --- the recommended mode for trusted repos when bypass is too permissive |
| **Bypass** | `bypassPermissions` | Skips all permission prompts | CI/CD pipelines, headless scripts (still prompts on protected paths: `.git`, `.vscode`, `.idea`, `.husky`, `.claude` minus carve-outs `commands`/`agents`/`skills`/`worktrees`) |

Set via CLI flag (`claude --permission-mode plan`), the `/config` command, or `permissions.defaultMode` in `settings.json`.

### The Six-Layer Permission Stack

Permission mode is not resolved from a single file. Claude Code honors **six layers**, with later layers overriding earlier ones:

| # | Layer | Location | Key |
|---|---|---|---|
| 1 | VSCode user | `~/Library/Application Support/Code/User/settings.json` (macOS), `~/.config/Code/User/settings.json` (Linux), `%APPDATA%/Code/User/settings.json` (Windows) | `claudeCode.initialPermissionMode` |
| 2 | VSCode workspace | `<repo>/.vscode/settings.json` | `claudeCode.initialPermissionMode` |
| 3 | CLI user | `~/.claude/settings.json` | `permissions.defaultMode` |
| 4 | CLI project | `<repo>/.claude/settings.json` | `permissions.defaultMode` |
| 5 | CLI project-local (gitignored) | `<repo>/.claude/settings.local.json` | `permissions.defaultMode` |
| 6 | **In-session runtime** | (ephemeral) | toggled via `Shift+Tab` / `/permission-mode` |

**Layer 6 is authoritative** and catches most users off-guard. `initialPermissionMode` only fires at **session start** --- if you (or `Shift+Tab`) change modes mid-session, every file-level layer is ignored until the session ends.

### Troubleshooting: Prompts Fire Despite `bypassPermissions`

This is the single most common source of confusion. Work through the checklist in order:

1. **Look at the status line** at the top of the Claude Code panel. With this repo's `statusLine` configured, it prints `[BYPASS]`, `[PLAN]`, `[AUTO-EDIT]`, or `[PROMPT]` for the four standard modes. Any other mode Claude Code reports (e.g., `dontAsk`) is shown as a bracketed raw name like `[dontAsk]`. If it doesn't say `[BYPASS]`, you have an in-session override --- press `Shift+Tab` to cycle modes until you land on bypass.
2. **Run `/permission-check`** to see every layer's value, the resolved merged state, and any drift (e.g., project says bypass but project-local says default).
3. **Check for stale sessions.** If settings changed recently but the session predates the change, it still runs under the old mode. Reload the window (`Cmd+Shift+P` → "Developer: Reload Window") and start a new session.
4. **Check `deny` lists.** A match in any layer's `deny` blocks the tool regardless of `allow` entries elsewhere.
5. **VSCode vs CLI split.** If the VSCode layers say bypass but no CLI layer does, a terminal-launched Claude Code will still prompt. Align them.

### The Plan → Bypass Handoff (Recommended Daily Driver)

Plan mode and bypass permissions sound like opposites, but they chain into a single workflow that gives you a **review-before-execute convenience**: you see the approach before any edits happen, then execution runs without per-tool prompts.

::: {.callout-warning}
## Plan approval is not an enforcement boundary

Approving a plan via `ExitPlanMode` releases the session to your `defaultMode` — typically `bypassPermissions`. Once there, any subsequent tool call (Edit, Write, Bash) executes under the full allowlist in your `settings.json`, not a scope derived from the plan. A mistaken implementation can still edit unrelated files or run destructive shell commands with no second checkpoint.

Treat this flow as a convenience pattern, not a security control. If you need a hard enforcement boundary, keep `defaultMode: "default"` and approve each high-risk tool individually, or run the whole session in `plan` mode and copy actions out manually.
:::

The flow:

```
Start session in plan mode  (Shift+Tab at startup, or claude --permission-mode plan)
     |
     | Read-only exploration + planning
     |   Claude can Read, Grep, run Bash readonly, spawn Explore/Plan agents
     |   Claude CANNOT edit files (except the plan file itself)
     |
     v
Plan drafted, saved to quality_reports/plans/YYYY-MM-DD_description.md
     |
     v
User approves via ExitPlanMode UI
     |
     | Claude Code returns the session to defaultMode.
     | If defaultMode = bypassPermissions, execution now runs
     | without approval prompts.
     v
Orchestrator executes the plan end-to-end --- no prompts.
```

**Why this is the recommended daily flow:**

- You always see the approach before any edits happen (plan mode is read-only).
- Once you approve, every downstream action --- edits, bash, multi-file refactors --- runs without interruption.
- No need to remember to toggle bypass mid-session. The handoff is automatic.
- Fits cleanly with the plan-first rule enforced by this repo.

**Prerequisite:** your `defaultMode` must be `bypassPermissions` in at least one CLI layer (typically the project or project-local layer). Without that, exiting plan mode returns you to `default` and you're back to per-tool prompts.

### Session Management {#sec-session-management}

A handful of recent Mar–Apr 2026 commands cut friction in the actual editing loop. Worth knowing before you reach for them in a panic:

| Command / shortcut | What it does | When to reach for it |
|---|---|---|
| `/btw <question>` | Asks a side question whose answer appears in a dismissible overlay --- never enters conversation history | Quick "what does X do?" / "is this version compatible?" questions you don't want bloating context |
| `Esc Esc` or `/rewind` | Opens the rewind menu --- restore conversation, code, or both to a prior checkpoint | Tried something risky, want to undo cleanly without `git reset` (checkpoints are NOT git --- only Claude-made changes are tracked) |
| `/clear` | Resets the conversation context entirely | Switching to an unrelated task; long session with cluttered context |
| `/compact <instruction>` | Guided summarization of the current conversation | "Compact, focusing on the API changes" --- selective preservation before continuing on the same task |
| `Ctrl+G` (in plan mode) | Opens the in-progress plan file in `$EDITOR` for direct editing before approval | You want to surgically tweak the plan without typing instructions back to Claude |
| `claude --continue` / `claude --resume` | Resume the most recent conversation (`--continue`) or pick from recent (`--resume`); rename with `/rename` | Picking up a multi-day project --- treat sessions like branches |
| `/checkpoint <slug>` | Writes a structured state snapshot to `quality_reports/checkpoints/` (this template, not Anthropic's) | Before stopping or handing off --- companion to the narrative session log |
| `/goal <verifiable condition>` | Sets an end-state condition; Claude keeps working across turns until a fast model confirms it holds (Apr 2026 Week 20, v2.1.139) | "All R scripts pass without errors", "Figure 3 renders to PDF without overflow" --- pair with `/commit` quality gates for verified-end-state runs |

**Three patterns that compose well:**

- **Side question without polluting context:** `` /btw why does Quarto need ::: for callouts? `` --- get the answer, dismiss, keep working.
- **Long session, want to switch tasks:** `/checkpoint current-work` then `/clear` then start the new task. Resume the first with `claude --resume`.
- **Plan mid-edit:** During plan mode, `Ctrl+G` to edit the plan file directly --- faster than dictating revisions back to Claude.

::: {.callout-warning}
## Plans Directory

By default, Claude saves plans to a global directory (`~/.claude/plans/`), not your project. To keep plans with your project (and in git), add this to `.claude/settings.json`:

```json
{
  "plansDirectory": "quality_reports/plans"
}
```
:::

The **Stop hook** runs a fast Python script after every response. No LLM call, no latency. It checks whether the session log is current and reminds Claude to update it if not. Behavioral rules like verification and Beamer-Quarto sync are enforced via auto-loaded rules in `.claude/rules/`, which is the right tool for nuanced judgment that Claude can evaluate in-context.

## Effort Levels --- Cost vs. Thoroughness {#sec-effort}

Claude Code lets you control how deeply it reasons about each task. Higher effort means more "thinking tokens" and better results --- but higher cost. On **Opus 4.8 the default is `high`** --- its `high` reasoning now delivers what 4.7's `xhigh` did, so you rarely need to bump up (see [Cost-Conscious Composition](#sec-cost)).

| Level | Thinking Budget | Academic Use Case | Relative Cost |
|-------|----------------|-------------------|---------------|
| `low` | Minimal | Quick formatting, grep, file renames | $ |
| `medium` | Standard | Mechanical work; drop here from `high` to save cost | $$ |
| `high` | ~10k tokens | Complex derivations, paper reviews (**Opus 4.8 default**) | $$$ |
| `xhigh` | ~20k tokens | Extended exploration / hardest runs; **Opus 4.8 defaults to `high`**, so reserve `xhigh` for genuinely hard work (introduced Apr 2026 Week 16) | $$$$ |
| `max` / ultrathink | ~32k tokens | Deep proofs, multi-step analysis | $$$$$ |

**How to set effort:**

- **Per-session:** Type `/effort high` (the Opus 4.8 default) or `/effort xhigh` for the hardest runs. Typing `/effort` on its own opens an **interactive slider** (Apr 2026 Week 16).
- **Per-skill:** Add `effort: high` to skill frontmatter (see [Skill Frontmatter Reference](#skill-frontmatter))
- **Keyboard toggle:** `Option+T` (Mac) / `Alt+T` (Windows/Linux) toggles extended thinking
- **In prompts:** Include "ultrathink" in your prompt to enable extended thinking for that turn. Note: phrases like "think hard" are treated as regular instructions and do *not* allocate extra thinking tokens
- **Environment variable:** `CLAUDE_CODE_EFFORT_LEVEL=high` for all sessions
- **Hooks can read it:** As of Apr 2026 Week 19, hook input includes `effort.level` and `$CLAUDE_EFFORT` is set in Bash subprocess env --- useful for skipping expensive verification on low-effort runs

::: {.callout-tip}
## Composing Effort with Model Choice

Effort levels compose with model selection for fine-grained cost control. For example, `Haiku + high effort` costs less than `Opus + low effort` but may produce comparable results for bounded tasks like formatting. Use `Opus + max` only for tasks that genuinely require deep multi-step reasoning --- complex proofs, intricate data pipeline debugging, or comprehensive paper critique.
:::

## Memory --- Cross-Session Persistence {#memory---cross-session-persistence}

Claude Code has an auto-memory system at `~/.claude/projects/[project]/memory/MEMORY.md`. This file persists across sessions and is loaded into every conversation.

Use it for:
- Key project facts that never change
- Corrections you don't want repeated (`[LEARN:tag]` format)
- Current plan status

```markdown
# Auto Memory

## Key Facts
- Project uses XeLaTeX, not pdflatex
- Bibliography file: Bibliography_base.bib

## Corrections Log
- [LEARN:r-code] Package X drops obs silently when covariate is missing
- [LEARN:citation] Post-LASSO is Belloni (2013), NOT Belloni (2014)
- [LEARN:workflow] Every Beamer edit must auto-sync to Quarto
```

#### Two-tier memory architecture (`MEMORY.md` vs `personal-memory.md`)

The template splits memory into two tiers (see [`meta-governance.md`](.claude/rules/meta-governance.md)):

- **`MEMORY.md`** (committed, ≤ 200 lines) — generic learnings that help all forkers: workflow patterns, design principles, documentation standards, quality thresholds that transfer across domains.
- **`.claude/state/personal-memory.md`** (gitignored, no size cap) — machine-specific and user-specific learnings: TeX install quirks, file paths, personal effort preferences, tool-version workarounds.

When a fork user does `git clone`, they get the generic `MEMORY.md`. Their own `personal-memory.md` builds up locally as they work.

#### `/promote-memory` — graduating learnings (v1.9.0)

The two-tier split poses one question: *who decides which `[LEARN]` entries graduate from `personal-memory.md` to `MEMORY.md`?* The answer is a **five-critic council**.

`/promote-memory [filter]` runs five critics in parallel, each reviewing one dimension:

1. **Generality** — would a non-econ forker benefit?
2. **Staleness** — does this contradict current code (`grep` the referenced files)?
3. **Redundancy** — is it already in MEMORY.md, CLAUDE.md, or a rule?
4. **Evidence** — does it cite the originating incident / file / why?
5. **Format** — does it follow `[LEARN:category] wrong → right`?

Majority (3+ of 5 YES) recommends promotion; the user approves the final move. Critics run in *isolated forked contexts* — they cannot see each other's votes — so dimensions are reviewed independently, no groupthink. Critics use Haiku (per [model-routing.md](.claude/rules/model-routing.md)) since the review is mechanical-ish.

When to run: monthly as memory-maintenance, before sharing a fork, after a paper or course cycle ships, or wired as a `/loop` task.

### Plans --- Compression-Resistant Task Memory

While MEMORY.md stores long-lived project facts, **plans** store task-specific strategy. Every non-trivial plan is saved to `quality_reports/plans/` with a timestamp. This means:

- Plans survive auto-compression (they are on disk, not just in context)
- Plans survive session boundaries (readable in any future session)
- Plans create an audit trail of design decisions

See Pattern 1 in [Workflow Patterns](#sec-patterns) for the full protocol.

### Session Logs --- Why-Not-Just-What History (auto-written)

Git commits record what changed, but not *why*. Session logs fill this gap. Claude writes to `quality_reports/session_logs/` at three points: right after plan approval, incrementally during implementation (as decisions happen), and at session end. This means the log captures reasoning *as it happens*, before auto-compression can discard it.

Because relying on instructions alone is fragile (Claude forgets during long sessions), a **Stop hook** (`.claude/hooks/log-reminder.py`) fires after every response. In v2.0 it no longer merely nags — it **auto-writes the session log** for every meaningful change-set, so the why-history is captured without depending on Claude remembering to do it.

New sessions can read these logs to understand not just the current state of the project, but the reasoning behind it. See Pattern 1 in [Workflow Patterns](#sec-patterns) for the full protocol.

### How It All Fits Together

With CLAUDE.md, MEMORY.md, plans, and session logs, the system has four distinct memory layers. Here is what each one does and when it matters:

| Layer | File | Survives Compression? | Updated When | Purpose |
|-------|------|----------------------|--------------|---------|
| Project context | `CLAUDE.md` | Yes (on disk) | Rarely | Project rules, folder structure, commands |
| Corrections | `MEMORY.md` | Yes (on disk) | On `[LEARN]` tag | Prevent repeating past mistakes |
| Task strategy | `quality_reports/plans/` | Yes (on disk) | Once per task | Plan survives planning-to-implementation handoff |
| Decision reasoning | `quality_reports/session_logs/` | Yes (on disk) | Incrementally | Record *why* decisions were made |
| Conversation | Claude's context window | **No** (compressed) | Every response | Current working memory |

The first four layers are your safety net. Anything written to disk survives indefinitely. The conversation context is ephemeral --- auto-compression will eventually discard details. The workflow's design ensures that anything worth keeping is written to one of the four persistent layers before compression can erase it.

### Hooks --- Automated Enforcement {#hooks---automated-enforcement}

The session log reminder above is one example of a broader pattern: using **hooks** to enforce rules that Claude might otherwise forget during long sessions. Rules live in context and can be compressed away. Hooks live in `.claude/settings.json` and fire every time, regardless of context state.

The template includes 7 hooks for logging, notifications, context survival, and git safety (plus a real git pre-commit hook, `.githooks/pre-commit`, installed via `./scripts/install-hooks.sh`):

| Hook | Event | What It Does |
|------|-------|-------------|
| Session log reminder | `Stop` | Reminds about session logs after every response |
| Desktop notification | `Notification` | Desktop alert when Claude needs attention (macOS/Linux) |
| Context state capture | `PreCompact` | Saves plan state before auto-compaction |
| Context restoration | `SessionStart[compact|resume]` | Restores context after compaction or resume |
| Context monitor | `PostToolUse[Bash|Task]` | Progressive warnings at 40%/55%/65%/80%/90% context |
| Git guardrails | `PreToolUse[Bash]` | Blocks destructive git (`reset --hard`, `clean -f`, `push --force`, `add -A`) |
| Claim reconcile | `PostToolUse[Edit|Write]` | Flags stale numeric claims when analysis scripts change |

Verification and Beamer-Quarto sync are enforced via auto-loaded rules, which are the right tool for nuanced judgment. Hooks are reserved for enforcement that *must* survive context compression.

**Hook handler types.** The examples above use `command` hooks (shell scripts), but Claude Code supports four handler types:

| Type | How It Works | Best For |
|------|-------------|----------|
| **`command`** | Runs a shell script. Exit 0 = allow, exit 2 = block (PreToolUse only) | File protection, state capture, notifications |
| **`prompt`** | Injects text into Claude's conversation --- no script needed | Soft reminders: "Check that equations compile before saving" |
| **`http`** | POSTs to an external endpoint | CI/CD integration, logging to external services |
| **`agent`** | Spawns a subagent that can use tools to verify conditions | Complex validation requiring multi-step checks |

**PreToolUse input modification.** PreToolUse hooks can now **modify tool inputs**, not just block or allow. Your hook script can return modified JSON to rewrite parameters before the tool executes --- for example, auto-correcting file paths or enforcing naming conventions.

::: {.callout-tip}
## Hook Design Principle
Use **command hooks** for fast, mechanical checks (file exists? counter threshold?). Use **prompt hooks** for soft guidance that doesn't need a script. Use **rules** for nuanced judgment (did Claude verify correctly?). Avoid prompt hooks that fire on high-frequency events --- the injected text adds up in context.
:::

### Context Survival System (Advanced) {#context-survival-system-advanced}

When context compaction happens, Claude loses working memory. The **context survival system** ensures you can recover seamlessly.

#### How It Works

Two hooks work together to preserve and restore state:

```
Session running → context fills up → PreCompact fires
                                           ↓
                                    pre-compact.py saves:
                                    • Active plan path
                                    • Current task
                                    • Recent decisions
                                           ↓
                                    Auto-compaction happens
                                           ↓
                                    SessionStart(compact|resume) fires
                                           ↓
                                    post-compact-restore.py:
                                    • Reads saved state
                                    • Prints context summary
                                    • Claude knows where it left off
```

#### What Gets Saved

| State | Location | Purpose |
|-------|----------|---------|
| Plan path | Session cache | So Claude can read the plan file |
| Current task | Session cache | First unchecked `- [ ]` item |
| Recent decisions | Session cache | Last 3 decision-like entries from session log |
| Compaction note | Session log | Timestamp marker for reference |

#### Context Monitoring

The `context-monitor.py` hook tracks approximate context usage and provides progressive warnings:

| Threshold | Message | Purpose |
|-----------|---------|---------|
| 40%, 55%, 65% | Suggest `/learn` | Capture non-obvious discoveries before compaction |
| 80% | Info message | Auto-compact approaching, no rush |
| 90% | Caution | Complete current task with full quality |

Use `/context-status` to check current session health at any time.

Note: the monitor uses tool call count as a proxy for context usage, so warnings may appear earlier or later than actual compaction.

#### Recovery After Compaction

If compaction happens mid-task, Claude will automatically see:

1. **Restoration message** --- what plan was active, what task was in progress
2. **Recovery actions** --- read the plan, check git status, continue

You can also manually point Claude to the right context:

> "We just had compaction. Read `quality_reports/plans/2026-02-06_translate-lecture5.md` and continue from where we left off."

#### Distil before compaction: `/compress-session` (v1.9.0)

Auto-compaction is *lossy* — it keeps recent turns and drops earlier ones, with no preservation of *what was decided* mid-session. For long pipelines (long debug sessions, multi-decision refactors, end-of-working-day handoffs), `/compress-session` is the **distil-not-truncate** alternative: structured note with Active state, Decisions made, Files touched, Open questions, Next actions, and explicitly **Discarded as noise** (failed hypotheses that should NOT carry forward).

`/compress-session` and `/checkpoint` are companions, not substitutes:

| | `/checkpoint` | `/compress-session` |
|---|---|---|
| **When** | Natural stop-points (end of day, model switch, collaborator handoff) | Forced compression (long pipeline, accumulated noise, approaching auto-compact) |
| **What's preserved** | Active plan, decisions, file pointers, next actions | Same, plus explicit "discarded as noise" line |
| **Output** | `quality_reports/checkpoints/` | `quality_reports/session_logs/YYYY-MM-DD_compression_<slug>.md` |
| **`[LEARN]` proposals** | Optional | Always proposes (distillation is when lessons surface) |

The "Discarded as noise" section is the novel contribution: failed hypotheses and dead-end debugging paths are listed explicitly so they do NOT ghost-haunt future sessions. This defends against [Drew Breunig's "context poisoning"](https://www.dbreunig.com/2025/06/22/how-contexts-fail-and-how-to-fix-them.html) failure mode — hallucinated or wrong content from early turns getting quoted by later turns.

::: {.callout-note}
## 2026 Feature Coverage

Now that you understand the building blocks, here's what's new: Claude Code has added [effort levels](#sec-effort) for cost control, [expanded hook events](#hooks---automated-enforcement), [skill frontmatter fields](#skill-frontmatter) for fine-grained skill configuration, [permission modes](#settings---permissions-and-hooks) for controlling Claude's autonomy, [advanced agent configuration](#sec-agent-config), plugins, `/batch` for parallel refactoring, and headless CLI mode. Each is covered in its respective section above.
:::

---

# Workflow Patterns {#sec-patterns}

The first two patterns are **meta-patterns** --- they govern how every task flows. Learn these first, then the specific workflows make more sense.

## Pattern 1: Plan-First Development {#pattern-1-plan-first-development}

The plan-first pattern ensures that non-trivial tasks begin with thinking, not typing.

### Why Planning Matters

The most common failure mode in AI-assisted development is not bad code --- it is solving the wrong problem, or solving the right problem in a fragile order. Plan-first development forces an explicit design step before any file is touched. Plans are saved to `quality_reports/plans/` on disk, so they survive [context compaction](#context-survival-system-advanced).

Without a plan:

- Claude starts editing immediately, discovers a dependency on slide 3 that changes the approach, and has to undo work
- Context compression discards the reasoning behind a design choice, and Claude makes a contradictory decision later
- The user and Claude have different mental models of what "done" looks like

With a plan:

- The approach is agreed upon before any edits happen
- The plan is saved to disk, so it survives compression and session boundaries
- Implementation has a checklist to follow, reducing drift

### The Protocol

```
Non-trivial task arrives
  |
  +-- Step 1: Claude enters plan mode (automatic, or say "plan this first")
  +-- Step 2: Draft plan (approach, files, verification)
  +-- Step 3: Save to quality_reports/plans/YYYY-MM-DD_description.md
  +-- Step 4: Present plan to user
  +-- Step 5: User approves (or revises)
  +-- Step 6: Save initial session log (capture context while fresh)
  +-- Step 7: Orchestrator takes over (see Pattern 2)
  +-- Step 8: Update session log + plan status to COMPLETED
```

### Context Preservation

Plans are saved to disk specifically so they survive context compression. The rule: **avoid `/clear`** --- prefer auto-compression. Use `/clear` only when context is genuinely polluted.

For details on how the system automatically preserves and restores context during compaction, see [Context Survival System](#context-survival-system-advanced) in the Building Blocks section.

### Session Logging

Session logs (`quality_reports/session_logs/YYYY-MM-DD_description.md`) are a running record of *why* things happened. They have **three distinct behaviors**, each solving a different problem:

**After plan approval** --- create the log with the goal, plan summary, and rationale for the chosen approach (including rejected alternatives). This captures decisions while context is richest. If you wait, auto-compression may discard the reasoning.

**During implementation** --- append to the log as you work. Every time a design decision is made, a problem is discovered, or the approach deviates from the plan, write a 1-3 line entry immediately. This is the most important behavior: context gets compressed as the session progresses, and decisions that live only in the conversation will be lost.

**At session end** --- add a final section with what was accomplished, open questions, and unresolved issues.

::: {.callout-note collapse="true"}
## Why Session Logs Matter

**Git records what; session logs record why.** A commit message says "Update Lecture 5 TikZ diagrams." A session log says "Redesigned the TWFE decomposition diagram because the DA challenge revealed students couldn't trace the path from weights to bias. Considered a table format but chose a flow diagram because it shows directionality."

**Incremental logging is the key.** A 4-hour session that only logs at the start and end loses everything in the middle. Appending decisions as they happen means auto-compression can never erase them --- they are already on disk.
:::

Claude writes all three log entries automatically --- no need to ask.

::: {.callout-tip collapse="true"}
## Weekly Reviews

For multi-project academics, start each week by asking Claude to read all session logs from the past week and synthesize a status report with priorities and open questions. The session log infrastructure already captures what you need --- the weekly review is just a synthesis prompt: *"Read all session logs from this week. Summarize: what was accomplished, what's blocked, what should I prioritize next?"*
:::

## Pattern 2: Contractor Mode (Orchestrator) {#pattern-2-contractor-mode-orchestrator}

Once a plan is approved, the orchestrator takes over. It is the natural continuation of Pattern 1: the plan says *what*, the orchestrator handles *how* --- autonomously.

### The Mental Model

Think of the orchestrator as a **general contractor**. You are the client. You describe what you want. The plan-first protocol is the blueprint phase. Once you approve the blueprint, the contractor takes over: hires the right specialists (agents), inspects their work (verification), sends them back to fix issues (review-fix loop), and only calls you when the job passes inspection (quality gates).

### The Loop

```
User: "Translate Lecture 5 to Quarto"
  |
  |-- Plan-first (Pattern 1): draft plan, save to disk, get approval
  |
  |-- User: "Approved"
  |
  +-- Orchestrator activates:
        |
        Step 1: IMPLEMENT
        |  Execute plan steps (create QMD, translate content, etc.)
        |
        Step 2: VERIFY
        |  Run verifier: render Quarto, check HTML output
        |  If render fails -> fix -> re-render
        |
        Step 3: REVIEW (agents selected by file type)
        |  +--- proofreader ------+
        |  +--- slide-auditor ----+  (parallel)
        |  +--- pedagogy-reviewer +
        |  +--- quarto-critic ----+  (needs others first)
        |
        Step 4: FIX
        |  Apply fixes: Critical -> Major -> Minor
        |  For quarto-critic issues: invoke quarto-fixer
        |
        Step 5: RE-VERIFY
        |  Render again, confirm fixes are clean
        |
        Step 6: SCORE
        |  Apply quality-gates rubric
        |
        +-- Converged? (a round adds 0 new Critical/Major)
              YES -> Present summary to user
              NO  -> Loop to Step 3 in fresh context
                     (loop-until-dry; 5-round cap is a fallback only)
```

### Agent Selection

The orchestrator selects agents based on which files were touched:

| Files Modified | Agents Selected |
|---------------|----------------|
| `.tex` only | proofreader + slide-auditor + pedagogy-reviewer |
| `.qmd` only | proofreader + slide-auditor + pedagogy-reviewer |
| `.qmd` with matching `.tex` | Above + quarto-critic (parity check) |
| `.R` scripts | r-reviewer |
| TikZ diagrams present | tikz-reviewer |
| Domain content | domain-reviewer (if configured) |
| Multiple formats | verifier for cross-format parity |

Agents that are independent of each other run in parallel. The quarto-critic runs after other agents because it may need their context.

### "Just Do It" Mode

Sometimes you do not want to approve the final result --- you just want it done:

> "Translate Lecture 5 to Quarto. Just do it."

In this mode, the orchestrator still runs the full fan-out → reduce → judge → loop-until-dry runtime (quality is non-negotiable) and skips the final approval pause for the current skill. It does **not** auto-commit: "just do it" is never commit authorization — commits require an explicit `/commit` or unambiguous request. It still presents the summary so you can see what was done.

### Relationship to Existing Skills

The orchestrator does NOT replace skills. It coordinates them:

- `/qa-quarto` remains available as a standalone adversarial QA loop
- `/slide-excellence` remains available for comprehensive multi-agent review
- `/create-lecture` remains available as a guided creation workflow

The difference: when you invoke a skill directly, it runs its specific workflow. The orchestrator runtime lives *inside* each skill — there is no repo-wide orchestrator that activates on its own or chains skills together. A skill is always user- or skill-initiated; nothing fires the runtime unattended.

::: {.callout-tip collapse="true"}
## When to Use Skills vs. the Orchestrator

**Natural-language task** → Claude picks a skill: "Translate Lecture 5 to Quarto" → Claude invokes `/translate-to-quarto`, and that skill runs the orchestrator pattern (translate → verify → review → fix → score) internally.

**Explicit skill call:** `/qa-quarto Lecture5` — you specifically want the adversarial critic-fixer loop, nothing else.

Both are valid. The natural-language path is the "I trust you, pick the skill" path. Explicit skill calls are the "I know exactly which loop I want" path. Either way, the orchestrator pattern runs *inside* the invoked skill — there is no auto-trigger outside a skill.
:::

## Pattern 3: Creating a New Lecture {#pattern-3-creating-a-new-lecture}

The `/create-lecture` skill guides you through a structured lecture creation workflow --- from gathering source material to deploying polished slides:

```
/create-lecture
  |
  +-- Phase 1: Gather materials (papers, outlines)
  +-- Phase 2: Design slide structure
  +-- Phase 3: Draft Beamer slides
  +-- Phase 4: Generate R figures
  +-- Phase 5: Polish and verify
  |     +-- /slide-excellence (domain + visual + pedagogy)
  |     +-- /proofread (grammar/typos)
  |     +-- /visual-audit (layout)
  +-- Phase 6: Deploy
        +-- /translate-to-quarto (optional)
        +-- /deploy
```

::: {.callout-tip}
## TikZ diagrams: start from the gallery, not from scratch

Writing TikZ from a blank page reliably produces label-over-arrow collisions because the compiler doesn't warn about them. The template ships three reinforcing layers:

- **[`templates/tikz-snippets/`](https://github.com/pedrohcgs/claude-code-my-workflow/tree/main/templates/tikz-snippets)** — 8 production-ready standalone diagrams (DAG basic, DAG mediation, two-period DiD, event study, timeline, regression scatter, 3-step flowchart, supply-demand). Each embeds the prevention rules (explicit node dimensions, coordinate map, directional edge labels) by construction.
- **Rules `tikz-prevention.md` + `tikz-measurement.md`** — Upstream authoring rules (P1–P6) and the six-pass collision protocol with formulas (Bézier depth, character widths, 0.4 cm boundary clearance). Adapted from Scott Cunningham's [MixtapeTools](https://github.com/scunning1975/MixtapeTools).
- **[`/new-diagram`](#all-skills) skill** — Scaffolds from the gallery, runs the P3/P4 grep pre-check before compiling, invokes `tikz-reviewer` with measurement citations, loops until APPROVED.

For existing diagrams in a Beamer deck, `/extract-tikz` runs the same pre-check plus the SVG pipeline.
:::

## Pattern 4: Translating Beamer to Quarto {#pattern-4-translating-beamer-to-quarto}

Translation preserves all content while adapting format, converting TikZ to SVG and ggplot to interactive Plotly charts:

```
/translate-to-quarto Lecture5_Topic.tex
  |
  +-- Phase 1-3: Environment mapping + content translation
  +-- Phase 4-5: Figure conversion (TikZ -> SVG)
  +-- Phase 6-7: Interactive charts (ggplot -> plotly)
  +-- Phase 8-9: Render + verify
  +-- Phase 10-11: /qa-quarto adversarial QA
        +-- Critic: finds issues
        +-- Fixer: applies fixes
        +-- Critic: re-audits
        +-- ... (loop-until-dry: converge after 2 dry rounds; 5-round cap is a fallback)
```

## Pattern 5: Replication-First Coding {#pattern-5-replication-first-coding}

When working with papers that have replication packages:

```
Phase 1: Inventory original code
  +-- Record "gold standard" numbers (Table X, Column Y = Z.ZZ)

Phase 2: Translate (e.g., Stata -> R)
  +-- Match original specification EXACTLY (same covariates, same clustering)

Phase 3: Verify match
  +-- Compare every target: paper value vs. our value
  +-- Tolerance: < 0.01 for estimates, < 0.05 for SEs
  +-- If mismatch: STOP. Investigate before proceeding.

Phase 4: Only then extend
  +-- New estimators, new specifications, course-specific figures
```

::: {.callout-important}
## Never Skip Replication

In one course, we discovered that a widely-used R package silently produced **incorrect estimates** due to a subtle specification issue. This bug was caught 3 times in different scripts. Without the replication-first protocol, these wrong numbers would have been taught to PhD students.
:::

**Source-language coverage:** The pattern is language-agnostic. The template ships [`/data-analysis`](#all-skills) for R-first projects and [`/stata-replication`](#all-skills) (v1.9.0) for Stata-first projects (mirrors `/data-analysis` exactly; same numbered-pipeline shape, different language; executes via the `stata-mcp` MCP server). Python-first projects follow the same convention with the path `scripts/python/_outputs/`. For Stata users, [`stata-code-conventions.md`](.claude/rules/stata-code-conventions.md) (v1.9.0) codifies the header (`version 18`, `clear all`, `set seed`/`set sortseed`), numbered pipeline (00–99), `esttab` for `\input{}` tables, clustering discipline (`reghdfe`), balance via `iebaltab`, and AEA Data Editor compliance.

::: {.callout-note}
## Claims provenance via `passport.yaml` (v1.9.0)

Replication-first verifies the *current* state. A separate question: how do we keep manuscript and code in sync over the lifetime of a paper, especially during R&R?

The answer is a per-paper `quality_reports/passports/<paper-slug>.yaml` that records, for each numeric claim in the manuscript, the script + line + output that produced it. Schema includes `tolerance`, `last_verified_on`, `status` (PASS / FAIL / STALE / UNVERIFIED). [`/audit-reproducibility`](#all-skills) reads and rewrites the passport in place; [`/commit`](#all-skills) reads it to block commits when a load-bearing claim is FAIL or STALE.

Starter file: [`templates/passport-template.yaml`](templates/passport-template.yaml). Copy once per paper. Pattern attributed to [Imbad0202/academic-research-skills](https://github.com/Imbad0202/academic-research-skills) "Material Passport" concept (scope-reduced for this template: numeric claims only).
:::

## Pattern 6: Multi-Agent Review {#pattern-6-multi-agent-review}

The `/slide-excellence` skill runs up to 6 [specialized agents](#agents---specialized-reviewers) in parallel:

```
/slide-excellence Lecture5_Topic.tex
  |
  +-- Agent 1: Visual Audit (slide-auditor)
  +-- Agent 2: Pedagogical Review (pedagogy-reviewer)
  +-- Agent 3: Proofreading (proofreader)
  +-- Agent 4: TikZ Review (tikz-reviewer, if applicable)
  +-- Agent 5: Content Parity (if Quarto version exists)
  +-- Agent 6: Substance Review (domain-reviewer)
  |
  +-- Synthesize: Combined quality score + prioritized fix list
```

## Pattern 7: Self-Improvement Loop {#pattern-7-self-improvement-loop}

There are two levels of self-improvement: **quick corrections** via `[LEARN]` tags and **full skill extraction** via `/learn`.

### Quick Corrections: [LEARN] Tags

Every correction gets tagged for future reference in MEMORY.md:

```markdown
## Corrections Log
- [LEARN:notation] T_t = 1{t=2} is deterministic -> use T_i in {1,2}
- [LEARN:citation] Post-LASSO is Belloni (2013), NOT Belloni (2014)
- [LEARN:r-code] Package X: ALWAYS include intercept in design matrix
- [LEARN:workflow] Every Beamer edit must auto-sync to Quarto
```

These tags are searchable and persist across sessions. When Claude encounters a similar situation, it checks memory first.

### Automated Skill Capture: /learn

For discoveries that deserve more than a one-line tag, use `/learn` to create a full skill:

```
/learn fixest-missing-covariate-handling
```

The `/learn` skill guides you through a 4-phase workflow:

```
Phase 1: EVALUATE
  "Was this non-obvious? Would future-me benefit?"
  → If YES to any, continue
         ↓
Phase 2: CHECK EXISTING
  Search .claude/skills/ for related skills
  → Nothing related? Create new. Overlap? Update existing.
         ↓
Phase 3: CREATE SKILL
  Write to .claude/skills/[name]/SKILL.md
  • Problem statement
  • Trigger conditions (exact errors, symptoms)
  • Step-by-step solution
  • Verification steps
         ↓
Phase 4: QUALITY GATE
  • Description has specific triggers?
  • Solution verified to work?
  • Specific enough to be actionable?
  • General enough to be reusable?
```

#### When to Use /learn

The context monitor suggests `/learn` at 40%, 55%, and 65% context usage. Consider extracting a skill when you encounter:

| Trigger | Example |
|---------|---------|
| Non-obvious debugging | 10+ minute investigation not in docs |
| Misleading errors | Error message was wrong, found real cause |
| Workarounds | Found limitation with creative solution |
| Undocumented APIs | Tool integration not in official docs |
| Trial-and-error | Multiple attempts before success |
| Repeatable workflows | Multi-step task you'd do again |

#### Skill vs. [LEARN] Tag

| Situation | Use |
|-----------|-----|
| One-liner fix | `[LEARN:category]` tag in MEMORY.md |
| Multi-step workflow | `/learn` to create full skill |
| Error + root cause + solution | `/learn` if reusable, `[LEARN]` if not |
| Package quirk | `/learn` if affects multiple projects |

Skills saved to `.claude/skills/` survive compaction and session boundaries --- if you discover something valuable late in a session, extract it with `/learn` before compaction erases the details.

## Pattern 8: Devil's Advocate {#pattern-8-devils-advocate}

At any design decision, invoke the Devil's Advocate:

> "Create a Devil's Advocate. Have it challenge this slide design with 5-7 specific pedagogical questions. Work through each challenge and tell me what survives."

This catches:

- Unstated assumptions
- Alternative orderings that might work better
- Notation that could confuse students
- Missing intuition before formalism
- Cognitive load issues

::: {.callout-tip collapse="true"}
## Fresh-Context Critique

A stronger variant: when Claude reviews its own work in the same conversation, it suffers **confirmation bias** --- it has internalized its own reasoning and will systematically find the work acceptable. The fix: spawn a new agent via the Task tool with NO access to the original conversation. Give it only the artifact and a critique prompt. The fresh agent has no sunk cost in the work and will be ruthless.

> "Spawn a new agent. Have it read only my paper draft --- not our conversation. Ask it to find the 5 weakest points and suggest how a hostile referee would attack each one."

Like handing your draft to a colleague who wasn't in the room when you wrote it.
:::

## Research Workflows {#sec-research-workflows}

Patterns 1--8 apply broadly, with course materials as the primary example. The next four patterns are designed for **research projects** --- papers, simulations, and empirical analysis --- where the rhythm is different: ideas are uncertain, experiments may fail, and code is often written to answer a question rather than to ship. Patterns 13--14 then extend the foundation to reproducibility standards and presentation rhetoric.

### Pattern 9: Parallel Agents for Research Tasks {#pattern-9-parallel-agents}

Claude Code can spawn **multiple agents simultaneously** using the Task tool. This is not limited to review --- you can use it for any research or analysis task where independent subtasks can run at the same time.

#### When to Use Parallel Agents

| Scenario | Sequential (slow) | Parallel (fast) |
|----------|-------------------|-----------------|
| Reviewing a lecture | Run proofreader, then auditor, then pedagogy | Run all 3 simultaneously |
| Analyzing 3 papers for a new lecture | Read paper 1, then 2, then 3 | Spawn 3 agents, each reading one paper |
| Generating figures | Create plot 1, then plot 2, then plot 3 | Spawn agents for independent plots |
| Comparing estimators | Run simulation 1, then 2, then 3 | Spawn agents for each simulation |
| Debating research design | Consider DiD, then SC, then RDD | 3 agents, each advocating one approach |

#### How It Works

You do not need to manage this manually. Skills that implement the orchestrator pattern (`/create-lecture`, `/review-paper --peer`, `/slide-excellence`, etc.) can recognize independent subtasks within their scope and spawn parallel subagents via `context: fork` --- both during implementation (Step 1) and review (Step 3). For example, when `/slide-excellence` runs on a deck, it spawns the visual / pedagogy / proofread agents in parallel; when `/review-paper --peer` runs, it spawns the two referees in parallel. The parallelism is built into the skill's logic, not into a repo-wide daemon.

You can also request parallelism explicitly:

> "Read these three papers in parallel. For each, extract the key identification assumption, the main estimator, and whether they have a replication package. Summarize in a table."

Either way, Claude spawns up to 3 Task agents, each processing one paper simultaneously, then synthesizes the results.

#### Long-running tasks: the Monitor tool (Apr 2026)

For genuinely long jobs --- a 30-minute R fit, a `/audit-reproducibility` batch over many tables, a Quarto render of a 200-slide deck --- the **Monitor tool** (Apr 2026 Week 15) lets Claude tail a background process's stdout in real time and react when something interesting happens. The pattern: launch the long job in the background (Bash with `run_in_background: true`), then ask Claude to monitor until a condition fires (error, milestone, finish). No polling loop, no sleep cycles. Useful inside `/data-analysis` for the regression step and inside `/audit-reproducibility` when re-running the whole script suite.

#### Watching parallel agents: `claude agents` (May 2026)

When several review agents run in parallel (the `/review-paper --peer` editor + 2 referees, or `/slide-excellence`'s visual + pedagogy + proofread fan-out), use **`claude agents`** (Week 20, v2.1.139) to watch them on a single screen. Replaces the old workflow of opening one terminal per agent. See the Anthropic Utilities section below for the full description.

#### Agent Debates

A powerful variant: give each parallel agent a **distinct methodological perspective** and have them argue. Instead of asking "which estimator should I use?", spawn 3 agents --- one advocates for DiD, one for synthetic control, one for RDD --- each arguing why their approach fits your research question best and critiquing the others. Synthesize the debate into a decision matrix. This produces genuinely diverse perspectives that a single conversation cannot, because each agent commits fully to its position.

#### Practical Limits

- **3 agents** is the sweet spot. More than that increases overhead without proportional speedup.
- Agents are **independent** --- they cannot see each other's work. If task B depends on task A's output, they must run sequentially.
- Each agent consumes its own context window. For very large files, sequential processing may be more reliable.

::: {.callout-tip}
## Cost-Conscious Parallelism

Parallel agents multiply token usage. For cost-sensitive tasks, run the expensive work (Opus agents) sequentially and the cheap work (Sonnet agents) in parallel. The orchestrator already does this: it runs Sonnet-level reviewers in parallel, then the Opus-level critic sequentially.
:::

### Pattern 10: Research Exploration Workflow {#pattern-10-exploration}

The **exploration workflow** provides a structured sandbox for experimental work.

#### The Problem

Without structure, experimental code scatters across the repository: analysis scripts in `scripts/`, test files in root, comparison documents in `quality_reports/`. After a week of exploration, the repo is cluttered with files that may or may not be useful, and nobody remembers which version was the good one.

#### The Solution: Exploration Folder

All experimental work goes into `explorations/` first:

```
explorations/
├── [active-project]/
│   ├── README.md           # Goal, hypotheses, status
│   ├── R/                  # Code iterations (_v1, _v2)
│   ├── scripts/            # Test scripts
│   └── output/             # Results
└── ARCHIVE/
    ├── completed_[name]/   # Graduated to production
    └── abandoned_[name]/   # Documented why stopped
```

#### Fast-Track vs. Plan-First

The decision tree is simple:

| Question | Answer | Workflow |
|----------|--------|----------|
| "Will this ship?" | YES | Plan-First (80/100 quality) |
| "Am I testing an idea?" | YES | Fast-Track (60/100 quality) |
| "Does this improve the project?" | NO | Don't build it |

Fast-Track explorations skip formal planning. Instead, a 2-minute **research value check** gates the work: "Does this improve the paper/slides/analysis?" If the answer is "maybe", explore. If "no", skip. If "yes", use Plan-First rigor.

#### The Lifecycle

```
Research value check (2 min)
  ↓
Create explorations/[project]/ (5 min)
  ↓
Code without overhead (60/100 quality)
  ↓
Decision point (1-2 hours):
  ├── Graduate → Move to R/, scripts/, tests/ (upgrade to 80/100)
  ├── Keep exploring → Stay in explorations/
  └── Abandon → Archive with brief explanation
```

The **kill switch** is explicit: at any point, you can stop, archive with a one-paragraph explanation, and move on. No guilt, no sunk cost. See `.claude/rules/exploration-folder-protocol.md` and `.claude/rules/exploration-fast-track.md` for the full protocols.

#### Simplified Orchestrator for Research

The full orchestrator (Pattern 2) is designed for course materials with multi-agent review loops. For research projects, the **simple variant** strips this down to: implement → verify → score → done. No multi-round reviews, no parallel agent spawning. This lives in its own path-scoped rule (`.claude/rules/orchestrator-research.md`) that loads only when working on R scripts or explorations.

#### Merge-Only Quality Reporting

In research projects, commits are frequent and incremental. Generating a quality report for each commit creates noise. Instead, quality reports are generated **only at merge time** --- a permanent snapshot of what was merged and why. Session logs capture the ongoing reasoning. See `.claude/rules/session-logging.md`.

### Pattern 11: Research Skills {#pattern-11-research-skills}

Five skills support the research workflow beyond slide development:

| Skill | What It Does | When to Use |
|-------|-------------|-------------|
| `/lit-review [topic]` | Search, synthesize, and identify gaps in the literature | Starting a new project or section |
| `/research-ideation [topic]` | Generate research questions, hypotheses, and empirical strategies | Brainstorming phase |
| `/interview-me [topic]` | Interactive interview to formalize a vague idea into a concrete specification | When you have an intuition but not a plan |
| `/review-paper [file]` | Full manuscript review with referee objections | Before submission or after a draft |
| `/data-analysis [data]` | End-to-end R analysis: explore, regress, produce publication-ready output | Empirical analysis phase |

These skills produce structured reports saved to `quality_reports/`. The `/data-analysis` skill also generates R scripts (saved to `scripts/R/`) and runs the r-reviewer agent automatically.

::: {.callout-note}
## `/review-paper --peer [journal]` — simulated peer review pipeline

For submission-ready manuscripts, `/review-paper --peer <journal>` runs an **editor + two dispositioned referees + editorial decision**, calibrated to the target journal. Editor calibration reads `.claude/references/journal-profiles.md`; the template ships profiles for **AER, QJE, JPE, ECMA, JoE** (econ) and **APSR, AJPS, JOP** (poli-sci). Other fields: add a profile, ~40 lines each.

The methods-referee is **paper-type-aware** — the same skill picks different sanity checks based on what kind of paper this is:

| Paper type | Methods-referee tilts toward | Sanity checks include |
|---|---|---|
| `reduced-form` | identification credibility, parallel-trends defence, robustness range | DiD pre-trends, IV first-stage, overlap, balance |
| `structural` | model identification, counterfactual credibility, fit | moment-matching, sensitivity to functional form, out-of-sample |
| `theory+empirics` | model-data correspondence | does the empirical estimand identify the theoretical object? |
| `descriptive` | measurement validity, generalisability | sampling frame, missingness, comparator choice |
| `formal-theory` (v1.8.0) | model originality, comparative-static sharpness | equilibrium existence, assumption tractability, robustness to relaxation |
| `survey-experiment` (v1.8.0) | design, sampling, attrition + manipulation checks | balance, manipulation-check pass rate, attrition asymmetry, sampling-frame validity |

R&R continuation is built in: `--r2` / `--r3` for response-to-referees rounds; `--stress` for a hostile-editor stress test. See `.claude/references/discipline-cards.md` for econ + poli-sci defaults (paper-type frequency, dominant journals, preregistration norms, code conventions). Forkers extend for psych / sociology / public-health.
:::

#### The Research Lifecycle as a Dependency Graph

A research project is not a waterfall --- it is a **dependency graph**. Some phases run in parallel; others are strictly sequential:

```
/research-ideation ─────┐
                        ├──→ /lit-review ──→ /data-analysis ──→ /review-paper
/interview-me ──────────┘         ↑               ↑
                                  │               │
                          (can run in parallel)   │
                                                  │
                          (enter mid-pipeline: ───┘
                           start with data and
                           work backwards)
```

**Enter mid-pipeline.** You do not have to start from ideation. If you already have data, start with `/data-analysis` and work backwards to the research question. If you already have a draft, start with `/review-paper`. The skills are modular --- use what you need, skip what you don't.

::: {.callout-note collapse="true"}
## For a Production-Grade Paper Pipeline

For a production-grade paper pipeline, a dedicated fork takes these same skills and wraps them in full research infrastructure: 6 worker-critic agent pairs plus specialized agents (data-engineer, referees, verifier), simulated blind peer review, weighted aggregate scoring, journal targeting, and R&R response routing. If your primary output is research papers, see [The Ecosystem](#sec-ecosystem) for details.
:::

### Pattern 12: Branch Isolation with Git Worktrees (Advanced) {#pattern-12-branch-isolation}

::: {.callout-note}
## Advanced Pattern
This pattern is optional and primarily useful for major translations, risky refactors, or multi-day projects. Most day-to-day work doesn't need it.
:::

Git worktrees create a **separate working directory** linked to the same repository. Each directory has its own branch but shares commit history. Subagents can use worktrees via the `isolation: worktree` field (see [Advanced Agent Configuration](#sec-agent-config)).

```
your-project/                     ← main branch (stays clean)
.worktrees/lecture-06-quarto/     ← isolated branch (Claude works here)
```

#### Why Use Worktrees?

| Benefit | Example |
|---------|---------|
| **Safe experimentation** | Translate Lecture 6 to Quarto --- if it fails, main is untouched |
| **Clean history** | 50 intermediate commits squash into one clean commit |
| **Easy discard** | Wrong approach? Delete worktree, no trace in main |
| **Multi-session work** | Resume worktree next day, no context loss |
| **Parallel work** | Work on slides (main) while Claude translates (worktree) |

#### The Workflow

```
1. CREATE WORKTREE
   git worktree add .worktrees/lecture-06-quarto -b quarto/lecture-06
   cd .worktrees/lecture-06-quarto
         ↓
2. IMPLEMENT
   All changes happen in the worktree
   Commit frequently (intermediate commits are OK)
         ↓
3. VERIFY
   Run tests, render, review against worktree only
         ↓
4. SYNC TO MAIN (when ready)
   git checkout main
   git merge --squash quarto/lecture-06
   git commit -m "feat: add Lecture 6 Quarto version"
         ↓
5. CLEANUP
   git worktree remove .worktrees/lecture-06-quarto
   git branch -d quarto/lecture-06
```

#### Commands Reference

```bash
# Create a worktree with new branch
git worktree add .worktrees/[name] -b [branch-name]

# List active worktrees
git worktree list

# Remove a worktree (after merging or abandoning)
git worktree remove .worktrees/[name]

# Delete the branch (after removal)
git branch -d [branch-name]

# Squash-merge into main
git checkout main
git merge --squash [branch-name]
git commit -m "feat: description of changes"
```

::: {.callout-note}
## `worktree.baseRef` (Apr 2026 Week 19)

Claude Code's `EnterWorktree` tool branches fresh worktrees from a configurable base ref via the `worktree.baseRef` setting in `.claude/settings.json`:

- `fresh` (default) --- branch from the **remote default branch** (typically `origin/main`). Safest for clean experimentation.
- `head` --- branch from local `HEAD`. Use when you have uncommitted local work the worktree should inherit.

The default surprises users with uncommitted in-flight edits: a `fresh` worktree won't see those changes. If your workflow assumes "branch off whatever I'm looking at now," set `"worktree.baseRef": "head"`.
:::

#### When to Use

| Situation | Use Worktree? |
|-----------|---------------|
| Quick fix to one file | No --- just edit main |
| New lecture creation | Maybe --- if multi-session |
| Beamer → Quarto translation | Yes --- many intermediate states |
| Major refactor | Yes --- safe rollback |
| Experimenting with new approach | Yes --- easy discard |

For example, translating Lecture 5 from Beamer to Quarto involves extracting TikZ diagrams, converting ggplot to plotly, and rewriting environments --- dozens of intermediate files over multiple sessions. A worktree keeps main clean while you iterate.

#### Complexity Cost

- Adds ~3 commands to learn
- Adds mental model: "Where am I working?"
- Requires discipline to sync/discard, not leave orphan worktrees

For most novice users, working directly on main with frequent commits is simpler and sufficient. Use worktrees when the benefits of isolation outweigh the added complexity.

## Advanced Patterns: Reproducibility and Presentation Design {#sec-beyond-slides}

The patterns above use slides as the primary example, but the infrastructure is domain-agnostic. The next two patterns address dimensions no existing pattern covers: reproducibility standards and presentation rhetoric.

### Pattern 13: Reproducibility & Replication Compliance {#pattern-13-reproducibility}

Pattern 5 covers matching *someone else's* results before extending them. This pattern is the complement: packaging *your own* work so that others --- and journal data editors --- can verify it.

#### The AEA Data Editor Standard

The [Template README for Social Science Replication Packages](https://social-science-data-editors.github.io/template_README/) is the compliance standard for the AEA, Review of Economic Studies, Economic Journal, and other major journals. It requires eight structured sections:

| Section | What It Covers |
|---------|---------------|
| Overview | What the code does, data sources, software, runtime |
| Data Availability Statements | Provenance, access rights, redistribution permissions for every data source |
| Dataset List | Every data file: source, format, whether provided |
| Computational Requirements | Software versions, packages, random seeds, memory, runtime |
| Description of Programs | Directory structure, execution order, dependencies |
| Instructions to Replicators | Numbered steps --- ideally one command |
| Table/Figure Mapping | Every exhibit mapped to the specific program and line that generates it |
| References | Proper bibliographic citations for all data sources |

The **Table/Figure Mapping** row is exactly what `passport.yaml` (v1.9.0) machine-encodes: each numeric claim → script + line + output file + tolerance + verified-on timestamp. The AEA requires the *spreadsheet-style* version; the passport is the *programmatic* version. They're complementary — generate the AEA spreadsheet from the passport when you submit.

#### Pre-Submission Checklist

::: {.callout-note collapse="true"}
## Replication Package Checklist

**Documentation:**

- [ ] README follows the [template](https://social-science-data-editors.github.io/template_README/) with all 8 sections
- [ ] PDF version of README included in root directory
- [ ] Data citations appear in both README and manuscript
- [ ] LICENSE.txt specifies code license (MIT/BSD) and data license (CC-BY)

**Code:**

- [ ] All software listed with exact version numbers
- [ ] Setup script installs all dependencies (`0_setup.R`, `requirements.txt`, etc.)
- [ ] Random seeds set deterministically (not timestamps)
- [ ] Master script runs everything without manual intervention
- [ ] Each table and figure produced by an identifiable, separate script

**Data:**

- [ ] Data Availability Statement for every data source, including confidential data
- [ ] Rights certifications: legitimate access + redistribution permission
- [ ] Directory structure separates raw, derived, and output data

**Verification:**

- [ ] Package re-executed in a clean environment
- [ ] Results numerically identical to manuscript
- [ ] Runtime and hardware requirements documented
:::

#### Recommended Directory Structure

```
project/
├── README.pdf              # Following AEA template
├── LICENSE.txt             # Code: MIT/BSD; Data: CC-BY
├── data/
│   ├── raw/                # Source data (untouched)
│   └── derived/            # Processed/analysis data
├── code/
│   ├── 00_setup.R          # Install dependencies
│   ├── 01_dataprep/        # Data cleaning
│   ├── 02_analysis/        # Main results
│   └── 03_appendix/        # Appendix results
└── results/                # Output tables, figures
```

These standards load automatically via the path-scoped rule mechanism: when Claude edits files matching `replication-protocol.md`'s path globs, the rule is injected into context without any manual invocation. Ask Claude to *"prepare a replication package"* and the rule's directory structure and checklist above guide the work from the first file touched.

::: {.callout-tip collapse="true"}
## Reproducibility as Architecture

A key principle that maps directly to this workflow: **separate scientific reasoning from computational execution.** Humans design diagnostic templates (what to measure); AI handles execution (how to run it).

This is the template-executor architecture --- and you are already using it:

- **Your spec** (requirements specification) = the template. It says *what* must be true.
- **The orchestrator** = the executor. It handles *how* to make it true.
- **Plans** = why decisions were made (audit trail)
- **Session logs** = reasoning documentation
- **Git** = what changed and when
- **MEMORY.md** = corrections and accumulated learning

The `/learn` skill already implements version-controlled knowledge accumulation: each discovery saved as a SKILL.md file with problem, solution, and verification steps --- the same pattern sometimes called "structured knowledge bases."

Key insight: *"For a fixed pipeline version and fixed inputs, the workflow produces identical numerical outputs and retains a complete audit trail of intermediate artifacts and logs."*
:::

### Pattern 14: The Rhetoric of Decks {#pattern-14-rhetoric-of-decks}

The slide-auditor checks *technical* quality (overflow, spacing). The pedagogy-reviewer checks *teaching* quality (notation density, prerequisites). Neither addresses *rhetorical* quality --- whether the slides persuade, whether the argument flows, whether beauty serves function.

The [Rhetoric of Decks](https://github.com/scunning1975/MixtapeTools/tree/main/presentations) framework fills this gap.

#### The Three Laws

**Law 1: Beauty is function.** Beautiful slides are not decorated slides. Beauty is clarity made visible. Every element earns its presence. Nothing distracts from the point. "Decoration without function is noise."

**Law 2: Cognitive load is the enemy.** One idea per slide. ONE. This is not a guideline --- this is the law. The audience has limited working memory. Every unnecessary word, data point, or "just in case" inclusion steals bandwidth from the actual message.

**Law 3: The slide serves the spoken word.** "If your slides can be understood without you speaking, you have written a document and called it a presentation." The slide is a visual anchor for speech --- a focal point for attention, a memory hook for retention.

#### The MB/MC Equivalence

The most original contribution of this framework --- applying marginal analysis to slide design:

> Optimal rhetoric equalizes the marginal benefit to marginal cost ratio across all slides: MB₁/MC₁ = MB₂/MC₂ = ... = MBₙ/MCₙ

**What this means in practice:**

- **Overloaded slides** (MB/MC too low): text running into footer, competing ideas, audience gives up
- **Underloaded slides** (MB/MC too high): wasted opportunity, attention captured but unused
- **The goal is smoothness** --- consistent cognitive load throughout --- not maximum density
- **Exception**: deliberate "jump scares" --- intentional spikes for rhetorical effect (a striking statistic, a provocative claim)

#### Actionable Principles

| Principle | Why | Anti-Pattern |
|-----------|-----|-------------|
| Titles are assertions | "Treatment increased distance by 61 miles" carries the argument | "Results" tells the audience nothing |
| Bullets are defeat | A list says "I couldn't find the structure" | Find the sequence, contrast, hierarchy, or causal chain |
| White space signals confidence | Crowded slides signal fear --- fear of silence, fear of forgetting | Filling every pixel with text |
| Direct labels, not legends | Legends force the eye to travel; labels stay with the data | Color-coded legends requiring a key |
| One message per chart | If you can't explain it in one sentence, it's too complex | Multi-panel figures with competing stories |
| Min 24pt body, max 2 fonts | Sans-serif for projection; test from the back row | 12pt text, decorative fonts |

#### How Existing Agents Support This

The `/slide-excellence` skill already invokes the pedagogy-reviewer and slide-auditor, which enforce many of these principles automatically. To enforce *all* of them --- including title-as-assertion and MB/MC smoothness --- customize the **domain-reviewer** agent (`.claude/agents/domain-reviewer.md`) with rhetoric-of-decks lenses. The orchestrator will then apply them during every review cycle without manual invocation.

::: {.callout-note collapse="true"}
## The Full Framework

For the complete philosophical treatment --- from Aristotle's three modes of persuasion through neuroaesthetics and the Netflix analogy --- see [The Rhetoric of Decks](https://github.com/scunning1975/MixtapeTools/tree/main/presentations). The repository includes a full essay, example Beamer decks with professional color palettes, a `theme_rhetoric()` ggplot2 theme, and a tested deck generation prompt for Claude Code.
:::

### Pattern 15: Sequential Adversarial Audits {#pattern-15-sequential-audits}

**Principle:** Run N independent audit passes, each focused on ONE dimension. Each auditor sees only the artifact --- not previous audits --- to prevent groupthink and anchoring bias.

This pattern differs from the parallel multi-agent review in [Pattern 6](#pattern-6-multi-agent-review). There, agents run simultaneously and findings are merged. Here, audits run **sequentially**, each producing an independent report. The independence is the point: a citation auditor shouldn't be influenced by what the prose auditor flagged.

#### The Seven-Audit Protocol (for Papers)

Inspired by [ClaudeCodeTools "The Editor"](https://github.com/aspi6246/ClaudeCodeTools), this protocol runs seven sequential passes before submission:

1. **Abstract audit** --- Does the abstract accurately reflect findings? Is it a compelling "storefront"?
2. **Introduction structure** --- Does the intro follow a recognized template (classic, puzzle-first, contribution-first)?
3. **Section-by-section audit** --- Data description, identification, results, robustness --- each checked independently
4. **Argumentation audit** --- Logical gaps, alternative explanations, missing qualifications
5. **Prose quality** --- Passive voice, hedging, jargon density, paragraph flow
6. **Citation fidelity** --- Every claim has a citation? Every citation is real and correctly referenced?
7. **"So What" test** --- Five questions: What's the question? Why does it matter? What did you find? How do you know? What does it mean?

#### How to Implement

Use `/review-paper` for a comprehensive single-pass review. When you need deeper, independent audits (e.g., before journal submission), run each audit as a separate skill invocation with `context: fork` to ensure isolation:

```
You: "Run the seven-audit protocol on my paper"
Claude: [Runs 7 sequential forked reviews, each blind to the others]
       → Produces 7 independent reports
       → Synthesizes into prioritized revision checklist
```

**Adapting for other artifacts:** The same principle works for replication packages (7 passes: code, data, documentation, licensing, runtime, outputs, README) or grant proposals (significance, approach, innovation, environment, budget).

**For the R&R stage (after referee comments arrive):** Use `/respond-to-referees [report] [revised-manuscript]`. It parses each concern, classifies coverage (addressed / partially / deferred / disagreement), points to specific revisions, and drafts the response document using `templates/response-to-referees.md`.

### Pattern 16: Preregistration and Submission Discipline {#pattern-16-preregistration}

**Principle:** Lock in your hypotheses, design, and analysis plan **before** you see the realised data. Preregistration is the strongest defence against p-hacking, HARKing, and forking-paths, and it's increasingly mandatory for credibility in social-science venues. Pair it with `/checkpoint` for a verifiable trail of what you committed to and when.

#### When preregistration matters

- **Before launching an experiment** (lab, field, or survey) — the canonical case.
- **Before analysing observational data** on a target population for a specific RQ. "I have the data but haven't looked at the outcome variable yet" is the right moment.
- **During R&R** when a referee asks for a written preanalysis plan covering robustness specifications.
- **Funding** — NSF, NIH, OSF, AEA grants increasingly require a PAP at submission.

#### Choosing a registry

The template ships three styles via `/preregister --style`:

| Registry | Style flag | Field | Length | Editable later? |
|---|---|---|---|---|
| **OSF** ([osf.io/registries](https://osf.io/registries)) | `osf` | Broad social science (default for psych, poli-sci, sociology) | Long-form, ~10–20 pages | Yes, with versioning |
| **AsPredicted** ([aspredicted.org](https://aspredicted.org)) | `aspredicted` | Behavioural / experimental short-form | 9 questions, ~2 pages | Locked once submitted |
| **AEA RCT Registry** ([socialscienceregistry.org](https://socialscienceregistry.org)) | `aea-rct` | Economics field experiments (mandatory for AEA journals since 2018) | Structured fields, ~3–5 pages | Limited fields editable |

For **public health / clinical trials**, use ClinicalTrials.gov or ISRCTN directly — this template's `/preregister` doesn't cover those formats. They're on the v2.0-backlog.

#### The workflow

```
/interview-me                       /preregister --style osf
   ↓                                   ↓
research-spec.md  ─────────────→  preregistration-draft.md
   ↓                                   ↓
(quality_reports/specs/)         (quality_reports/preregistrations/)
                                       ↓
                                  user reviews,
                                  uploads to OSF,
                                  receives registration ID
                                       ↓
                                  /checkpoint preregistration-submitted
                                       ↓
                                  data collection begins
```

`/preregister` reads your `/interview-me` spec frontmatter (the `paper_type:` field flows in from there if you set it) and produces a registry-formatted draft with **MUST / SHOULD / MAY** annotations on every section. Pre-flight checks: directional hypothesis declared, named estimator, ex-ante exclusion rules, sample-size stopping rule.

#### Mandatory fields per registry style

The `--style` flag determines the mandatory section list. The template enforces these via the pre-flight check:

| Field | OSF | AsPredicted | AEA RCT |
|---|:---:|:---:|:---:|
| Directional hypothesis (with sign) | MUST | MUST | MUST |
| Sampling frame + recruitment | MUST | SHOULD | MUST |
| Sample-size / stopping rule | MUST | MUST | MUST |
| Named primary estimator | MUST | MUST | MUST |
| Pre-specified covariate set | SHOULD | MAY | MUST |
| Multiple-comparison adjustment plan | SHOULD | SHOULD | MUST |
| Ex-ante exclusion rules | MUST | MUST | MUST |
| Robustness specifications (named in advance) | SHOULD | MAY | SHOULD |
| Data-sharing plan | SHOULD | MAY | MUST |
| Intervention description (RCTs) | --- | --- | MUST |

`/preregister` refuses to draft a "retrospective preregistration" — if your description contains realised results or post-hoc reasoning, the skill halts and explains why. That refusal is the point.

#### Pairing with `/checkpoint`

`/checkpoint` is the structured companion to the narrative session-log workflow. For preregistration specifically:

- **Before submitting** to the registry: `/checkpoint preregistration-pre-submit` snapshots the draft state, the spec it derives from, and the next-action ("upload to OSF and record registration ID").
- **After submission**: `/checkpoint preregistration-submitted [registration-id]` records the registry ID and the date in the structured snapshot. The plan and session log link to it.
- **On data arrival**: `/checkpoint data-arrived` marks the boundary between "things I could legitimately commit to" and "things I learned from looking." Anything that follows is exploratory unless explicitly anchored in the preregistered plan.

`/checkpoint` files live at `quality_reports/checkpoints/YYYY-MM-DD_<slug>.md` (gitignored — they're session-state, not version-controlled artifacts). Optional `--no-memory` flag suppresses the auto-proposal of `[LEARN]` entries to MEMORY.md.

#### Post-flight verification

Any cited literature in the preregistration runs through `/verify-claims` (Chain-of-Verification, forked-verifier context, fresh) before the draft is considered ready. Hallucinated citations are the most common preregistration failure mode and the hardest to fix after submission — gate-refusing them at draft time pays back many-fold.

#### What this pattern protects against

- **HARKing** (Hypothesising After Results are Known) — the preregistered hypothesis pins the directional claim before observation.
- **p-hacking** — the named estimator + named multiple-comparison plan removes the discretion that produces inflated false-positive rates.
- **Forking paths** — every data-dependent choice is either declared MUST or disclosed as exploratory.
- **Selective reporting** — the data-sharing plan + named robustness specifications make selective reporting visible to referees.

For econometrics, see Christensen & Miguel (2018) on transparency in development economics. For political science, see [Monogan (2015)](https://www.cambridge.org/core/journals/ps-political-science-and-politics/article/research-preregistration-in-political-science/) on the political-science case. For psychology, see the OSF Preregistration Guide.

---

# The Ecosystem: What Others Have Built {#sec-ecosystem}

This repository provides the foundation --- the infrastructure patterns (plan-first, orchestrator, quality gates, adversarial review, context survival) that work for any academic task. Others have taken these patterns further, building specialized workflows for specific needs. Here are the principles these projects share and how to apply them:

| Principle | Source | How to Implement Here |
|-----------|--------|----------------------|
| Adversarial review (not self-review) | All | Use fresh-context critique ([Pattern 8](#pattern-8-devils-advocate)) or worker-critic pairs |
| Structured intermediate files | Xu & Yang | Save every computed object to disk; agents communicate via files |
| Phase-appropriate rigor | clo-author | Light review for exploration (60/100), full adversarial for submission (95/100) |
| Voice preservation | claudeblattman | Maintain a reference doc with your writing style; load as context |
| Template-executor separation | Xu & Yang | Spec = what to measure, orchestrator = how to execute |
| Self-improving configuration | claudeblattman | Use `/learn` to capture discoveries; review MEMORY.md periodically |
| Human judgment, AI execution | Xu & Yang | You design the diagnostic; Claude runs it |
| Beauty is function | MixtapeTools | Every visual element earns its presence; decoration without function is noise |
| Constraint-based autonomy | autoresearch | Define boundaries in Markdown (what CAN/CANNOT change); let Claude explore within |
| Sequential independent audits | ClaudeCodeTools | Run N blind audit passes; independence prevents groupthink ([Pattern 15](#pattern-15-sequential-audits)) |

::: {.callout-tip}
## Which Ecosystem Project Should I Start With?

If you write **papers**: start with clo-author (adversarial review pairs) or ClaudeCodeTools (seven-audit protocol, see [Pattern 15](#pattern-15-sequential-audits)). If you give **presentations**: MixtapeTools. If you run **computational experiments**: autoresearch. If you're a **non-technical academic**: claudeblattman. All of them build on the same foundation patterns from this template — the [orchestrator](#sec-system), [quality gates](#sec-quality), and [adversarial review](#the-adversarial-pattern-critic-fixer).
:::

Here is what each project does and when you should use it.

## clo-author: Paper-Centric Research Workflows

**Repository:** [hugosantanna/clo-author](https://github.com/hugosantanna/clo-author)
**Author:** Hugo Sant'Anna (UAB)
**Built on:** Fork of this repository

clo-author reorients the entire workflow from slides to **research papers**. The paper (`Paper/main.tex`) becomes the single source of truth; talks and supplements derive from it. The key architectural innovation is **adversarial worker-critic agent pairs**: every creative agent is paired with a dedicated critic agent, with strict separation of powers (critics never create, creators never self-score).

**What it adds:**

- **17 specialized agents** organized as 6 worker-critic pairs (Librarian, Explorer, Strategist, Coder, Writer, Storyteller --- each with a dedicated critic) plus standalone agents (data-engineer, domain-referee, methods-referee, orchestrator, verifier)
- **Phase-based severity gradient** --- critics are encouraging during Discovery, constructive during Strategy, strict during Execution, and adversarial during Peer Review
- **Weighted aggregate scoring** with component minimums: Literature 10%, Data 10%, Identification 25%, Code 15%, Paper 25%, Polish 10%, Replication 5%. Submission gate (≥ 95) requires every component independently ≥ 80
- **Simulated blind peer review** --- two independent Referee agents plus an Editor making an editorial decision (Accept / Minor / Major / Reject)
- **Humanizer pass** --- identifies and strips 24 AI writing patterns across four categories (structural tics, lexical tells, rhetorical patterns, formatting tells)
- **Domain profile system** --- configurable field-specific calibration file read by all agents
- **Full submission pipeline** --- journal targeting, R&R response routing (classifies referee comments as NEW ANALYSIS / CLARIFICATION / DISAGREE / MINOR), AEA replication compliance, pre-analysis plans, cover letter generation

**When to use it:** Your primary output is research papers and you want production-grade infrastructure for the full lifecycle --- from literature review through journal submission and revise-and-resubmit.

::: {.callout-note}
## clo-author v26.05 (May 2026)

clo-author has shipped substantial post-v4 architecture. The current release (v26.05, 2026-05-10) adds:

- **MAS v2** --- second-generation multi-agent system with clearer worker/critic boundaries and phase-aware severity gradients
- **Skill-Centric Restructure** --- repository reorganised around 13 skills + 18 agents (up from 17 in the v4.x line)
- **HTML Dashboard** --- self-contained visual interface for tracking pipeline state across phases (no server required)

Patterns like `/checkpoint` (originally adapted with permission from clo-author v4.2.0) trace to the earlier line; if you're forking clo-author directly today, you get the MAS v2 / skill-centric layout.
:::

## claudeblattman: Workflows for Non-Technical Academics

**Website:** [claudeblattman.com](https://claudeblattman.com)
**Repository:** [chrisblattman/claudeblattman](https://github.com/chrisblattman/claudeblattman)
**Author:** Chris Blattman (University of Chicago)

claudeblattman is a comprehensive guide for academics who do not write code, built by a political economist who describes himself as someone who "has never written a line of code." It demonstrates that Claude Code workflows extend far beyond technical tasks into daily academic life.

**What it adds:**

- **Executive assistant workflows** --- morning briefings (weather, calendar, inbox, VIP tracking), smart email triage with 14 phases, daily check-in ritual, schedule queries, todo management
- **Proposal writing** --- donor profiles, voice packs (maintain consistent writing style across documents), template gates, resubmission handling with reviewer comment categorization
- **Fresh-context critique** --- the intellectual centerpiece: spin up a fresh-context agent to review your work without self-bias (see Pattern 8)
- **Agent debates** --- multiple agents with distinct identities argue about research design, producing genuinely novel perspectives (see Pattern 9)
- **Tips pipeline** --- self-improving system: capture tips by emailing yourself, `/tips-curate` quality-filters them, `/tips-integrate` converts them into concrete configuration changes
- **Depth calibration** --- Light/Standard/Deep thoroughness levels that prevent over-engineering simple requests
- **Graceful degradation** --- every skill works with partial infrastructure. Missing MCP integrations produce explanations, not errors
- **Writing style rules** --- numbers over adjectives, topic sentences make claims, no throat-clearing, hedge only with a reason or number

**When to use it:** You are new to Claude Code, want practical daily workflows beyond coding, or want to see how an academic non-programmer built a sophisticated system.

## Xu & Yang (2026): Reproducibility as Architecture

**Paper:** Yiqing Xu (Stanford) and Leo Yang Yang (HKBU), "[Scaling Reproducibility: An AI-Assisted Workflow for Large-Scale Reanalysis](https://yiqingxu.org/papers/2026_ai/AI_reproducibility.pdf)," 2026.

This paper formalizes many principles that this workflow uses intuitively. It demonstrates an AI-assisted pipeline that achieved **100% reproducibility** across 92 papers (215 specifications) --- conditional on accessible data and code --- with each paper processed in under four minutes.

**Key principles:**

- **Template-executor separation** --- humans design diagnostic templates (what to measure), AI handles execution (how to run it). Maps to our spec-then-plan workflow.
- **Three-layer architecture** --- LLM orchestrator (coordination) → skill descriptions and knowledge bases (contracts and accumulated experience) → deterministic agent code (numerical work). Maps to our orchestrator → skills/rules → agents.
- **Structured intermediate files** --- agents communicate through standardized files on disk (JSON, CSV, logs), not hidden state. Ensures every step is inspectable and rerunnable.
- **Version-controlled knowledge accumulation** --- SKILL.md files with Context/Problem/Fix/Impact format. Maps to our `/learn` skill.
- **Adaptation between runs, not during runs** --- fixes are incorporated as version-controlled updates between sessions, never as ad hoc patches within a session. This ensures reproducibility.

**When to reference it:** You are designing a reproducibility workflow, building a replication package, or want to formalize the principles underlying this guide's architecture.

## MixtapeTools: The Rhetoric of Decks

**Repository:** [scunning1975/MixtapeTools](https://github.com/scunning1975/MixtapeTools)
**Author:** Scott Cunningham (Baylor University), author of *Causal Inference: The Mixtape*

MixtapeTools provides the philosophical and practical framework for academic presentation design (see Pattern 14). Beyond the Rhetoric of Decks, it includes:

- **Referee 2** --- a systematic 5-audit adversarial protocol for reviewing and replicating empirical work
- **Deck generation prompt** --- a tested, customizable multi-agent prompt for creating Beamer decks (builder → rhetoric reviewer → graphics specialist)
- **Example decks** with professional color palettes, custom ggplot2 themes (`theme_rhetoric()`), and complete Beamer templates
- **Zero-warning compilation standard** --- even 0.5pt overfull hbox must be fixed

**When to use it:** You want to make your presentations genuinely beautiful and rhetorically effective, or you want a tested deck generation workflow for Claude Code.

## AEA Data Editor Template

**Website:** [social-science-data-editors.github.io/template_README](https://social-science-data-editors.github.io/template_README/)
**Repository:** [social-science-data-editors/template_README](https://github.com/social-science-data-editors/template_README)
**Maintainer:** Lars Vilhuber (Cornell University) and editors from REStat, EJ, CJE

The compliance standard for replication packages at 5+ major economics journals (see Pattern 13). Available in Markdown, Word, LaTeX, and PDF formats.

**When to use it:** You are preparing a replication package for journal submission and need the exact template that data editors will check against.

## autoresearch: Constraint-Based Autonomous Research

**Repository:** [karpathy/autoresearch](https://github.com/karpathy/autoresearch)
**Author:** Andrej Karpathy

An autonomous research agent that runs continuous experiments --- modifying code, training models, and evaluating results --- without human intervention. The key insight for academic workflows:

- **`program.md` as a constitutional document** --- a single Markdown file defines what the agent CAN modify (architecture, hyperparameters), what it CANNOT (data pipeline, evaluation metric), and what success looks like (validation metric, lower is better)
- **Structured results logging** --- every experiment is recorded in a TSV file with branch name, metric, and status
- **Time-budgeted iterations** --- fixed training windows make experiments comparable

**When to use it:** You are running iterative computational experiments (Monte Carlo simulations, hyperparameter searches, model comparisons) and want Claude to explore the space semi-autonomously within defined constraints.

**Example:** Adapting the `program.md` pattern for a Monte Carlo study:

```markdown
# program.md — Monte Carlo Experiment Constraints

## What You CAN Modify
- DGP parameters (sample sizes, effect sizes, correlation structures)
- Estimator implementations (new methods, tuning parameters)
- Number of replications (up to 10,000)

## What You CANNOT Modify
- prepare_data.R (data generation is frozen)
- evaluation metric (RMSE of ATT, lower is better)
- Output format (results.tsv with columns: method, n, rmse, coverage)

## Success Metric
RMSE of ATT estimate. Lower is better. Report coverage rate alongside.
```

## stata-mcp: MCP server for Stata execution

**Repository:** [SepineTam/stata-mcp](https://github.com/SepineTam/stata-mcp)
**Author:** SepineTam (171+ stars, 91 releases, v1.17.3 as of May 2026)

A mature MCP server that lets Claude Code execute Stata `.do` files via a command-guarded interface — refuses destructive shell ops (`!/shell/erase` etc.), monitors RAM, and pairs with the Stata Language Server. **Install once per user:** `claude mcp add stata-mcp --scope user -- uvx stata-mcp` (requires `uv` and a local Stata install).

**Why it matters for this template:** v1.9.0 added [`/stata-replication`](#sec-appendix) for Stata-first projects, which depends on this MCP server. R-first projects (the original template focus) continue to use [`/data-analysis`](#sec-appendix); the two skills are parallel — same pipeline shape, different source language. AEA submissions where the original replication package is in Stata are the canonical use case.

For end-to-end Stata workflows, see [`.claude/rules/stata-code-conventions.md`](.claude/rules/stata-code-conventions.md) (header scaffold, numbered pipeline, esttab tables, clustering discipline, AEA Data Editor compliance).

## ClaudeCodeTools: The Editor Persona

**Repository:** [aspi6246/ClaudeCodeTools](https://github.com/aspi6246/ClaudeCodeTools)

A collection of Claude Code personas, including "The Editor" --- a deeply structured academic paper reviewer that runs seven sequential audit passes (see [Pattern 15](#pattern-15-sequential-audits)). Notable features:

- **R&R mode** --- tracks referee reports and cross-references each concern against revisions
- **Blunt, specific feedback** --- "This paragraph is incoherent" not "might benefit from clarity"
- **"So What" litmus test** --- five questions every paper must answer clearly

**When to use it:** You want a structured pre-submission paper review, or you're responding to referee reports and need systematic tracking of which concerns have been addressed.

## Anthropic-Shipped Apr 2026 Utilities

These are first-party Claude Code commands you can invoke directly without forking anything. Worth knowing because they fill gaps this template intentionally doesn't try to fill:

- **`/team-onboarding`** (Week 15) --- packages your local Claude Code setup (CLAUDE.md, skills, agents, hooks, settings) into a replayable guide. Useful for lab groups: a PI configures the workflow once, the rest of the lab runs `/team-onboarding` and inherits a working copy. Complements but doesn't replace this template's "fork + customize" model.
- **`/autofix-pr`** (Week 15) --- runs Claude Code on a GitHub PR, applying typical CI-style fixes (lint, types, simple test failures). Pairs well with our `/commit` flow if you push a PR and want a follow-up auto-cleanup pass before review.
- **`/powerup`** (Mar/Apr 2026 Week 14) --- interactive lessons that teach Claude Code features (hooks, skills, MCP, plugins) with animated demos. Recommend this to new forkers who want to understand the *primitives* underneath the template's customizations.
- **Ultraplan** (Week 15) --- draft a plan in the cloud from your CLI, review and comment on it in a web editor, then run it remotely or pull it back local. Useful for plans that need stakeholder review (e.g., a co-author signing off on an analysis approach before the actual run).
- **`/loop` self-pacing** (Apr 2026 Week 15) --- run a prompt or slash command on a recurring interval, or omit the interval to let the model self-pace until a stopping condition is met. Useful for status-polling tasks ("check the deploy every 5 minutes") that pair with the Monitor tool above. The alias `/proactive` was added in Week 16.
- **`/goal <verifiable condition>`** (May 2026 Week 20, v2.1.139) --- the "keep working until X holds" command. Claude continues across turns until a fast model confirms the condition is satisfied. Distinct from `/loop` (which is interval-based) and from plan mode (which approves a strategy rather than enforcing an outcome). Pairs naturally with `/commit`'s quality gates: `/goal "all sections pass /verify-claims with no HIGH-WARN findings"` then commit. Works in interactive, `claude -p`, and Remote Control.
- **`claude agents`** (May 2026 Week 20, v2.1.139) --- one-screen dashboard for all background sessions. Replaces the multi-terminal pattern for parallel review work. Directly aligned with our `/review-paper --peer` and `/qa-quarto` parallel-reviewer setup; you can launch the referees and watch their progress from a single view.
- **`/fewer-permission-prompts`** (Apr 2026 Week 16) --- scans recent transcripts for read-only Bash and MCP calls and proposes a project-local allowlist. Sibling to our `/permission-check`: `/permission-check` *diagnoses* the prompt-fatigue source, `/fewer-permission-prompts` *remediates* it.

These are external to this template --- invoke directly, no installation needed. Mention them as off-ramps when this template's scope doesn't fit.

## Community Adoption {#sec-community}

As of March 2026, **15+ research groups** across multiple disciplines have forked and adapted this workflow for their own projects:

- **Economics** --- China innovation policy, mental health and layoffs, AIGC and stock prices, capital/labor shares in healthcare
- **Energy** --- Nepal and global energy economics, PV module reliability
- **Teaching** --- ECN 152 course development, Econ 730 causal panel data

Each adaptation follows the same pattern: fork the template, fill in `CLAUDE.md` placeholders, customize the domain reviewer, and add field-specific skills. The infrastructure (orchestrator, hooks, quality gates) transfers without modification.

---

# Customizing for Your Domain {#sec-customize}

::: {.callout-tip}
## What ships preloaded vs. what you customize

Two disciplines are already concrete in this template:

- **Economics** --- top-4 + top-field journal profiles (AER, QJE, JPE, ECMA, JoE), R-centric `r-code-conventions.md`, econometrics example in domain-reviewer.md.
- **Political Science** --- APSR, AJPS, JOP journal profiles (v1.8.0), `formal-theory` + `survey-experiment` paper types in methods-referee, poli-sci example in domain-reviewer.md.

Both fields are wired into `.claude/references/discipline-cards.md`, which `/research-ideation`, `/interview-me`, `/preregister`, and the editor agent read when you give them a discipline without a target journal. Cards document paper-type frequency, dominant journals, preregistration norms (OSF / AsPredicted / AEA RCT / ClinicalTrials.gov), significance-stars conventions, SE conventions, and dominant code language (R / Stata / Python).

**Forking for psych, sociology, public health, or other fields:** add ~3 journal profiles, 2–3 paper types, 1 discipline card. The infrastructure (orchestrator, hooks, quality gates, peer-review pipeline) is field-agnostic and transfers without modification. The v2.0 backlog (`.claude/references/v2.0-backlog.md`) lists psychology, sociology, and public-health as candidate next breadth additions.
:::

## Step 1: Build Your Knowledge Base

The knowledge base (`.claude/rules/knowledge-base-template.md`) is the most domain-specific component — it's a [path-scoped rule](#rules---domain-knowledge-that-auto-loads) that loads automatically when Claude works on your content files. It provides skeleton tables for notation conventions, lecture progression, applications, design principles, anti-patterns, and R code pitfalls. Fill them in as you develop your project --- you don't need everything upfront.

### Notation Registry

```markdown
| Symbol | Meaning | Introduced | Anti-Pattern |
|--------|---------|------------|-------------|
| $\beta$ | Regression coefficient | Lecture 1 | Don't use $b$ |
| $\hat{\theta}$ | Estimator | Lecture 2 | Don't use $\hat{\beta}$ for different estimand |
```

### Applications Database

```markdown
| Application | Paper | Dataset | Package | Lecture |
|------------|-------|---------|---------|--------|
| Minimum Wage | Card & Krueger (1994) | NJ/PA fast food | `fixest` | 3 |
```

### Validated Design Principles

```markdown
| Principle | Evidence | Lectures Applied |
|-----------|----------|-----------------|
| Motivation before formalism | DA challenge: "students lost" | All |
| Max 3 new symbols per slide | Pedagogy review caught overload | 2, 4 |
```

## Step 2: Create Your Domain Reviewer

Copy `.claude/agents/domain-reviewer.md` and customize the [5-lens framework](#sec-domain-reviewer) for your field. The template provides the structure; you fill in domain-specific checks.

## Step 3: Adapt Your Theme

The template includes matching LaTeX and Quarto palettes. To customize:

1. Edit `Preambles/header.tex` (Beamer/TikZ) **and** `Quarto/theme-template.scss` (Quarto) together — same color names, matching HEX values.
2. Run `./scripts/check-palette-sync.sh` to confirm they agree. The check is also invoked by `./scripts/validate-setup.sh` after any palette edit.
3. Update CSS class names in the SCSS if needed.
4. Modify the `beamer-translator` environment mapping to match your classes.

**Palette contract.** The core palette names (`primary-blue`, `primary-gold`, `highlight-yellow`, `light-bg`, `jet`) must exist on both surfaces. Snippets in `templates/tikz-snippets/` currently inline their colors for standalone compilation, but real lectures that `\input{header}` inherit the palette automatically. See [`Preambles/README.md`](../Preambles/README.md) for the full contract and TikZ style library.

## Step 4: Creating Custom Skills {#sec-create-skills}

The guide includes 52 [skills](#skills---reusable-slash-commands) for common academic tasks. But if you have repetitive workflows specific to your domain, you can create your own.

### When to Create a Skill

Create a skill when:
- You repeatedly explain the same 3+ step workflow to Claude
- You need domain-specific quality checks (citation style, notation consistency, lab protocols)
- You enforce field-specific output formats (thesis structure, journal templates)
- You coordinate multi-tool workflows (data → analysis → manuscript)

**Don't create a skill for:**
- One-time tasks
- Workflows that change frequently
- Simple 1-2 step operations

### Skill Structure

Each skill is a directory in `.claude/skills/` with a `SKILL.md` file:

```markdown
---
name: your-skill-name
description: [What it does] + [When to use] + [Key capabilities]
argument-hint: "[brief hint for user]"
allowed-tools: ["Read", "Write", "Edit", "Bash", "Task"]
---

# Your Skill Name

## Instructions
Step 1: [First action with details]
Step 2: [Second action]
...

## Examples
Example 1: [Common scenario]
...

## Troubleshooting
Error: [Common error]
Solution: [How to fix]
```

### Complete Frontmatter Reference {#skill-frontmatter}

The YAML frontmatter controls how your skill behaves. The most-used fields:

| Field | Purpose | Example |
|-------|---------|---------|
| `name` | Display name in `/` menu | `compile-latex` |
| `description` | **Most important.** Controls when Claude auto-loads the skill | `Compile Beamer slides...` |
| `argument-hint` | Placeholder shown after `/skill-name` | `<filename>` |
| `allowed-tools` | **Pre-approve** tools (skip permission prompts). NOT a restriction — unlisted tools remain callable through normal permissions | `["Read", "Bash", "Glob"]` |
| `disallowed-tools` | **Remove** tools from Claude's pool while the skill is active — this is the actual restriction mechanism | `["Edit", "Write"]` |
| `paths` | Glob patterns scoping when the skill auto-activates (skill-level analogue of path-scoped rules) | `["scripts/**/*.R"]` |
| `when_to_use` | Extra routing context for auto-invocation | `after a merge conflict` |
| `arguments` | Named positional arguments for `$name` substitution | `[infile, outfile]` |
| `effort` | Override reasoning effort level | `high` |
| `context` | Set to `fork` to run in an isolated subagent | `fork` |
| `agent` | Link to an agent definition in `.claude/agents/` | `proofreader` |
| `hooks` | Skill-specific hooks (same syntax as settings.json) | `{PreToolUse: [...]}` |
| `model` | Force a specific model | `haiku` |
| `disable-model-invocation` | Prevent Claude from auto-triggering | `true` |
| `user-invocable` | Whether it appears in the `/` menu | `true` (default) |

::: {.callout-warning}
## `allowed-tools` does not sandbox

A common (and security-relevant) misreading: omitting `Bash` from `allowed-tools` does **not** make a skill read-only — `allowed-tools` only *pre-approves* the listed tools so they skip permission prompts; everything else stays callable under your normal permission settings. To genuinely remove tools while a skill runs, use `disallowed-tools` (e.g. `["Edit", "Write", "Bash"]` for a read-only audit skill, plus `AskUserQuestion` for anything that runs unattended). See `templates/skill-template.md` for the full pattern.
:::

::: {.callout-note}
## Key Design Choices

- **`effort: high`** is useful for review skills that need deep reasoning (e.g., paper critique). Use `effort: low` for simple formatting skills to save tokens.
- **`context: fork`** runs the skill in a fresh subagent context, protecting your main conversation from large outputs. Good for skills that produce verbose reports.
- **`allowed-tools`** prevents skills from accidentally using destructive tools. A read-only review skill should use `["Read", "Grep", "Glob"]`.
:::

### Dynamic Content in Skills {#skill-dynamic-content}

Skills can include dynamic values using string substitutions and live command output:

**String substitutions:**

| Syntax | Expands To | Example Use |
|--------|-----------|-------------|
| `$ARGUMENTS` | Full argument string after `/skill-name` | `/compile-latex Lecture01` → `$ARGUMENTS` = `Lecture01` |
| `$0`, `$1`, `$N` | Positional arguments (0-based, space-separated) | `/deploy Lecture01 draft` → `$0` = `Lecture01`, `$1` = `draft` |
| `${CLAUDE_SESSION_ID}` | Current session identifier | Unique log file names |
| `${CLAUDE_SKILL_DIR}` | Path to the skill's directory | Reference supporting files bundled with the skill |

**Dynamic context injection** with `` `!command` `` syntax:

```markdown
## Context
Current git status: `!git status --short`
Recent changes: `!git log --oneline -5`
Available lectures: `!ls Slides/*.tex`
```

When Claude loads the skill, it runs these commands and injects the live output into the skill text. This is powerful for skills that need to adapt to the current project state.

### Writing Effective Trigger Descriptions

The `description` field is the single most important thing you write when creating a skill. Claude reads the description of every available skill on every turn and uses it to decide whether to auto-invoke without the user typing a slash command. A vague description means a skill that only runs when the user remembers its name --- defeating the point of auto-invocation.

**The gold-standard pattern has three parts:**

1. **Verb + object** --- what the skill *does*, in one clause. Start with an action verb (Compile, Review, Generate, Translate).
2. **"Use when:" trigger phrases** --- 3--5 phrases the user might *actually* say. Include verbatim quotes (`"proofread"`, `"check the layout"`) and semantic paraphrases (`"does this overflow?"`). Cover both explicit commands and natural-language requests.
3. **Disambiguation from sibling skills** --- if your skill lives near others in the same domain (e.g., `proofread`, `visual-audit`, and `pedagogy-review` all operate on slides), explicitly say what it is *not* for, or point at the alternative. This prevents mis-routing.

**Example: refactoring a weak description into an A-grade one.**

Before (weak --- the skill exists but Claude won't auto-pick it):
```yaml
description: Run the proofreading protocol on lecture files. Checks grammar, typos, overflow, consistency.
```

After (strong --- Claude will match this from cold prompts):
```yaml
description: Read-only proofreading pass over lecture .tex or .qmd files.
  Checks grammar, typos, overflow, terminology consistency, and academic
  writing quality; produces a report without editing. Use when user says
  "proofread", "check for typos", "look for grammar issues", "copy-edit
  this", "any writing errors?", or before a lecture release.
```

**The test:** imagine a teammate who has never seen your skill list types `"can you look for writing errors in Lecture 3?"`. Does your description contain enough lexical overlap that Claude would match it against competing skills? If not, add more trigger phrases.

**Another good example (disambiguation):**
```yaml
description: Interactive interview that formalizes a fuzzy research idea into
  a structured spec (RQ, hypotheses, identification, data needs, empirical
  strategy). Use when user says "interview me", "help me think through this
  idea", "I have a half-baked idea". Multi-turn Q&A; saves spec to disk.
  NOT for lit review (/lit-review) or ideation from scratch (/research-ideation).
```

The final sentence --- "NOT for X, use /Y instead" --- is the disambiguation clause. Two skills with overlapping descriptions will split Claude's routing probability; the explicit "not for" resolves the tie.

**Bad (too vague --- will never auto-invoke):**
```yaml
description: Helps with citations
```

**Checklist before shipping a new skill:**

- [ ] Starts with a verb + object.
- [ ] Has a "Use when:" clause with at least 3 trigger phrases.
- [ ] Includes at least one verbatim quote a user might literally type.
- [ ] Disambiguates from any sibling skills in the same domain.
- [ ] Fits in roughly 2--4 lines (longer descriptions get truncated in Claude's skill index).

### Domain-Specific Examples

::: {.panel-tabset}

#### Econometrics

**Regression Output Formatter**

Converts R regression outputs to publication-ready LaTeX tables with proper formatting (standard errors in parentheses, significance stars, fixed effects rows).

**Trigger:** User runs regressions and says "make a table", "format results", "export to LaTeX"

**Tools:** `Read`, `Write`, `Bash` (to run R scripts)

#### Experimental Sciences

**Protocol Validator**

Validates lab protocols against safety and reproducibility standards. Checks for: required sections (materials, procedure, safety), quantitative specifications, controls, and replication details.

**Trigger:** User provides protocol documents, asks "check protocol", "validate procedure"

**Tools:** `Read`, `Write`

#### Literature Review

**Citation Cross-Reference Checker**

Cross-references in-text citations against bibliography entries. Identifies missing entries, unused references, and formatting inconsistencies.

**Trigger:** User asks "check citations", "validate references", when working on manuscripts

**Tools:** `Read`, `Grep`, `Glob`, `Write`

:::

### Quick Start

1. **Copy the template:**
   ```bash
   mkdir -p .claude/skills/your-skill-name
   cp templates/skill-template.md .claude/skills/your-skill-name/SKILL.md
   ```

2. **Customize for your domain:**
   - Replace trigger phrases with your field's terminology
   - Add domain-specific file types and tools
   - Include field conventions and common errors

3. **Test the skill:**
   - Skills hot-reload automatically --- changes are detected without restarting
   - Use one of your trigger phrases
   - Verify the skill loads and produces correct output

4. **Iterate:**
   - If skill doesn't trigger: Revise description with more specific phrases
   - If instructions unclear: Add more examples
   - If output wrong: Add validation steps

**Full template:** See `templates/skill-template.md` for comprehensive examples from biology, economics, and physics.

::: {.callout-tip}
## Real Example: /deep-audit Was Created with /learn

The `/deep-audit` skill was itself extracted from a repeating workflow using `/learn`. After running 7 rounds of manual consistency audits --- each time launching 4 parallel agents to check guide accuracy, hook code quality, skills/rules consistency, and cross-document counts --- the pattern was codified into a skill. Now `/deep-audit` launches those same 4 agents, triages findings, applies fixes, and loops until clean (loop-until-dry: converges after 2 dry rounds, with a fallback cap). It also encodes a table of known bug patterns from past audits so future rounds catch regressions faster.

This is the `/learn` lifecycle in action: discover a repeating workflow → extract it → never repeat the manual steps again.
:::

## Tips from 6+ Sessions of Iteration

1. **Keep CLAUDE.md under 150 lines.** Claude follows ~150 instructions reliably. A 400-line CLAUDE.md means rules get silently ignored. Use path-scoped rules for detailed standards.
2. **Add rules incrementally.** Don't try to write all rules upfront. Add them when you discover patterns. Use `paths:` frontmatter so they only load when relevant.
3. **Use the [LEARN] format.** Every correction gets tagged and persisted in MEMORY.md. This prevents repeating mistakes across sessions.
4. **Trust the adversarial pattern.** The critic-fixer loop catches things you won't. Let it run.
5. **Verify everything.** The verification rule exists for a reason. Never skip compilation or rendering checks.
6. **Session logs matter.** Document design decisions, not just what changed. Future-you will thank present-you.
7. **Devil's Advocate early.** Challenge slide structure before you've built 50 slides on a shaky foundation.
8. **Progressive disclosure.** Start with CLAUDE.md + 2--3 rules. Add more as your workflow matures. Newcomers should not face all 32 rules on day one.
9. **Use `CLAUDE.local.md` for personal overrides.** This file is automatically gitignored and loaded alongside `CLAUDE.md`. Put machine-specific paths, personal preferences, and local tool versions here --- they won't pollute the shared repo.

::: {.callout-note collapse="true"}
## Extending with MCP Servers

For capabilities beyond file editing and shell commands --- web search during literature review, database queries for replication, or reference manager integration (Zotero, Mendeley) --- Claude Code supports [MCP servers](https://modelcontextprotocol.io). Configure them in `.claude/settings.json` under `"mcpServers"`. Start with skills and agents first; add MCP when you need external integrations.

## Extending with Plugins

Claude Code supports **plugins** --- bundled collections of skills, agents, hooks, and MCP servers that can be installed from git repositories. Use `/plugin` to browse and manage plugins (it has a Discover tab for finding new ones). Plugins are a newer extension point; start with skills and rules (which you control entirely) before adopting third-party plugins.
:::

---

# Appendix: File Reference {#sec-appendix}

## All Agents

| Agent | File | Purpose |
|-------|------|---------|
| Proofreader | `.claude/agents/proofreader.md` | Grammar, typos, consistency |
| Slide Auditor | `.claude/agents/slide-auditor.md` | Visual layout, overflow, spacing |
| Pedagogy Reviewer | `.claude/agents/pedagogy-reviewer.md` | Narrative arc, notation clarity |
| R Reviewer | `.claude/agents/r-reviewer.md` | R code quality, reproducibility |
| TikZ Reviewer | `.claude/agents/tikz-reviewer.md` | Diagram visual quality |
| Beamer Translator | `.claude/agents/beamer-translator.md` | LaTeX to Quarto translation |
| Quarto Critic | `.claude/agents/quarto-critic.md` | Adversarial Quarto QA |
| Quarto Fixer | `.claude/agents/quarto-fixer.md` | Applies critic's fixes |
| Verifier | `.claude/agents/verifier.md` | Task completion verification |
| Domain Reviewer | `.claude/agents/domain-reviewer.md` | Your domain-specific review |
| Claim Verifier | `.claude/agents/claim-verifier.md` | Chain-of-Verification (fresh-context) fact-checker (v1.7.0) |
| Editor | `.claude/agents/editor.md` | Journal editor for `/review-paper --peer` (desk review + referee selection + editorial synthesis, v1.5.0) |
| Domain Referee | `.claude/agents/domain-referee.md` | Disposition-primed substance referee for `/review-paper --peer` (v1.5.0) |
| Methods Referee | `.claude/agents/methods-referee.md` | Paper-type-aware methodology referee for `/review-paper --peer` (v1.5.0; +formal-theory + survey-experiment in v1.8.0) |
| Humanize Auditor | `.claude/agents/humanize-auditor.md` | Read-only auditor for AI-voice tells in academic prose; invoked by `/humanize` (v1.9.0) |
| Promote-Memory Council | `.claude/agents/promote-memory-council.md` | Five-critic council (generality / staleness / redundancy / evidence / format) for `[LEARN]` promotion from personal-memory.md to MEMORY.md; invoked by `/promote-memory` (v1.9.0) |
| Sim Reviewer | `.claude/agents/sim-reviewer.md` | Monte Carlo reviewer — DGP/estimand match, Monte Carlo SE, coverage-vs-truth, claims↔tables parity (v1.10.0) |
| R Package Reviewer | `.claude/agents/r-package-reviewer.md` | R package-source reviewer — DESCRIPTION/NAMESPACE hygiene, roxygen, testthat, CRAN-policy red flags (v1.10.0) |

## All Skills

| Skill | Directory | Purpose |
|-------|-----------|---------|
| `/compile-latex` | `.claude/skills/compile-latex/` | XeLaTeX 3-pass compilation |
| `/deploy` | `.claude/skills/deploy/` | Quarto render + GitHub Pages sync |
| `/extract-tikz` | `.claude/skills/extract-tikz/` | TikZ to SVG conversion |
| `/new-diagram` | `.claude/skills/new-diagram/` | Scaffold a TikZ diagram from the gallery |
| `/proofread` | `.claude/skills/proofread/` | Run proofreading agent |
| `/visual-audit` | `.claude/skills/visual-audit/` | Run layout audit agent |
| `/pedagogy-review` | `.claude/skills/pedagogy-review/` | Run pedagogy review agent |
| `/review-r` | `.claude/skills/review-r/` | Run R code review agent |
| `/qa-quarto` | `.claude/skills/qa-quarto/` | Critic-fixer adversarial loop |
| `/slide-excellence` | `.claude/skills/slide-excellence/` | Combined multi-agent review |
| `/translate-to-quarto` | `.claude/skills/translate-to-quarto/` | Beamer to Quarto translation |
| `/validate-bib` | `.claude/skills/validate-bib/` | Bibliography validation |
| `/devils-advocate` | `.claude/skills/devils-advocate/` | Design challenge questions |
| `/create-lecture` | `.claude/skills/create-lecture/` | Full lecture creation |
| `/commit` | `.claude/skills/commit/` | Stage, commit, PR, and merge |
| `/lit-review` | `.claude/skills/lit-review/` | Literature search and synthesis |
| `/research-ideation` | `.claude/skills/research-ideation/` | Research questions and strategies |
| `/interview-me` | `.claude/skills/interview-me/` | Interactive research interview |
| `/review-paper` | `.claude/skills/review-paper/` | Manuscript review |
| `/respond-to-referees` | `.claude/skills/respond-to-referees/` | R&R cross-reference and response draft |
| `/data-analysis` | `.claude/skills/data-analysis/` | End-to-end R analysis |
| `/audit-reproducibility` | `.claude/skills/audit-reproducibility/` | Enforce replication tolerance thresholds on paper ↔ code |
| `/learn` | `.claude/skills/learn/` | Extract discoveries into persistent skills |
| `/context-status` | `.claude/skills/context-status/` | Show session health and context usage |
| `/deep-audit` | `.claude/skills/deep-audit/` | Repository-wide consistency audit |
| `/seven-pass-review` | `.claude/skills/seven-pass-review/` | Seven-pass adversarial manuscript review (parallel forked subagents) |
| `/permission-check` | `.claude/skills/permission-check/` | Diagnose permission layers (6-tier stack) |
| `/verify-claims` | `.claude/skills/verify-claims/` | Chain-of-Verification fact-check on any draft (v1.7.0) |
| `/checkpoint` | `.claude/skills/checkpoint/` | Structured session-handoff snapshot — companion to narrative session logs (v1.8.0) |
| `/preregister` | `.claude/skills/preregister/` | Generate a preregistration document (OSF / AsPredicted / AEA RCT Registry) from a research spec (v1.8.0) |
| `/humanize` | `.claude/skills/humanize/` | Detect AI-voice tells in academic prose (read-only audit; no rewrite) (v1.9.0) |
| `/compress-session` | `.claude/skills/compress-session/` | Distil the current session into a structured note (decisions, files, open questions, next actions, discarded-as-noise) before auto-compaction (v1.9.0) |
| `/promote-memory` | `.claude/skills/promote-memory/` | Five-critic council that votes on whether candidate `[LEARN]` entries should be promoted from personal-memory.md to MEMORY.md (v1.9.0) |
| `/stata-replication` | `.claude/skills/stata-replication/` | End-to-end Stata pipeline scaffold + execution via the `stata-mcp` MCP server (mirrors `/data-analysis` for R-first projects; v1.9.0) |
| `/simulation-study` | `.claude/skills/simulation-study/` | Reproducible Monte Carlo study — DGP, estimator grid, seeded reps, bias/RMSE/coverage/size/power with Monte Carlo SEs (v1.10.0) |
| `/r-package-check` | `.claude/skills/r-package-check/` | R package release gate — `devtools::document()` + tests + `R CMD check --as-cran` + CRAN-policy triage (v1.10.0) |
| `/replication-package` | `.claude/skills/replication-package/` | Assemble a submission-ready DCAS / openICPSR replication package; calls `/audit-reproducibility` and blocks on FAIL (v2.0) |
| `/capture-environment` | `.claude/skills/capture-environment/` | Snapshot the computational environment (renv.lock / sessionInfo / requirements.txt / uv.lock + optional Dockerfile + seeds) (v2.0) |
| `/did-event-study` | `.claude/skills/did-event-study/` | Staggered DiD / event-study wrapper over canonical packages (Callaway–Sant'Anna `did`, `fixest::sunab`, HonestDiD; Stata `csdid`/`eventstudyinteract`/`honestdid`) (v2.0) |
| `/power-analysis` | `.claude/skills/power-analysis/` | Power / required-N / MDE for study design (RCT, clustered/ICC, multi-arm, or simulation-based) + a methods paragraph for `/preregister` (v2.0) |
| `/disclosure-check` | `.claude/skills/disclosure-check/` | Pre-screen restricted-data outputs for SDL violations (small cells, dominance, PII); gates on any CRITICAL (v2.0) |
| `/grant-proposal` | `.claude/skills/grant-proposal/` | Scaffold a grant proposal (NSF/NIH/ERC/foundation) from an `/interview-me` spec; delegates DMP + facilities; aims↔methods↔budget coherence pass (v2.0) |
| `/data-management-plan` | `.claude/skills/data-management-plan/` | Draft a funder-compliant Data Management Plan (NSF/NIH 2023/ERC/Horizon) (v2.0) |
| `/coauthor-brief` | `.claude/skills/coauthor-brief/` | Generate a collaborator handoff brief: git delta, per-artifact state, open questions, reproduce-locally + restricted-data steps (v2.0) |
| `/triage-inbox` | `.claude/skills/triage-inbox/` | Triage academic email + calendar (Gmail/Calendar MCP) into a prioritized digest + referee-obligations tracker; human-gated actions only (v2.0) |
| `/syllabus` | `.claude/skills/syllabus/` | Build a course syllabus from a topic/reading list (schedule, objectives, assessment + rubric, per-week `/create-lecture` work-list) (v2.0) |
| `/teach-from-paper` | `.claude/skills/teach-from-paper/` | Turn a paper into a lecture outline, teachable results, slide skeleton (→ `/create-lecture`), discussion questions, exercise brief (v2.0) |
| `/respond-to-eval` | `.claude/skills/respond-to-eval/` | Turn student course evaluations into a classified teaching-improvement plan (Keep/Change/Investigate/Out-of-scope) (v2.0) |
| `/scaffold-exercises` | `.claude/skills/scaffold-exercises/` | Scaffold a graded problem set (analytical/empirical/coding) with worked solutions; clean student set + separate solution key (v2.0) |
| `/new-skill` | `.claude/skills/new-skill/` | Scaffold a convention-compliant skill (interview → write `SKILL.md` with gate-passing frontmatter) (v2.0) |

## All Rules

**Always-on** (load every session):

| Rule | File | Purpose |
|------|------|---------|
| Plan-First Workflow | `plan-first-workflow.md` | Plan mode + context preservation |
| Orchestrator Protocol | `orchestrator-protocol.md` | Review runtime: fan-out → reduce → judge (+ hallucination gate) → loop-until-dry (goal-first / gate-enforced; augments contractor mode) |
| Session Logging | `session-logging.md` | Three logging triggers |
| Meta-Governance | `meta-governance.md` | Template vs working project distinctions |
| Prompt Shaping | `prompt-shaping.md` | Ambient prompt-shaping habit (replaces the retired `/prompt` and `/prompt-only` skills) |

**Path-scoped** (load only when working on matching files):

| Rule | File | Triggers On |
|------|------|------------|
| Verification Protocol | `verification-protocol.md` | `.tex`, `.qmd`, `docs/` |
| Single Source of Truth | `single-source-of-truth.md` | `Figures/`, `.tex`, `.qmd` |
| Quality Gates | `quality-gates.md` | `.tex`, `.qmd`, `*.R` |
| R Code Conventions | `r-code-conventions.md` | `Figures/**`, `scripts/**`, `explorations/**` (analysis scripts) |
| TikZ Quality | `tikz-visual-quality.md` | `.tex` |
| TikZ Prevention | `tikz-prevention.md` | `Slides/**`, `Figures/**`, `Preambles/**` |
| TikZ Measurement | `tikz-measurement.md` | `Slides/**`, `Figures/**`, `Preambles/**`, `scripts/**` |
| Beamer-Quarto Sync | `beamer-quarto-sync.md` | `.tex`, `.qmd` |
| PDF Processing | `pdf-processing.md` | `master_supporting_docs/` |
| Proofreading Protocol | `proofreading-protocol.md` | `.tex`, `.qmd`, `quality_reports/` |
| No Pause | `no-pause-beamer.md` | `.tex` |
| Replication Protocol | `replication-protocol.md` | `*.R` |
| Knowledge Base | `knowledge-base-template.md` | `.tex`, `.qmd`, `*.R` |
| Orchestrator Research | `orchestrator-research.md` | `*.R`, `explorations/` |
| Exploration Folder | `exploration-folder-protocol.md` | `explorations/` |
| Exploration Fast-Track | `exploration-fast-track.md` | `explorations/` |
| Content Invariants | `content-invariants.md` | `.tex`, `.qmd`, `Preambles/`, `scripts/R/**` |
| Cross-Artifact Review | `cross-artifact-review.md` | `master_supporting_docs/`, `.tex`, `.qmd` |
| Summary–Body Parity | `summary-parity.md` | `CHANGELOG.md`, `README.md`, `.qmd`, skill/rule/agent `.md` |
| Post-Flight Verification | `post-flight-verification.md` | skills that generate factual claims (`/lit-review`, `/research-ideation`, `/respond-to-referees`, `/review-paper`, `/interview-me`) |
| Model Routing | `model-routing.md` | `.claude/agents/**/*.md`, `.claude/skills/**/SKILL.md` — 70/20/10 architect/editor split, per-agent `model:` field guidance (v1.9.0) |
| Stata Code Conventions | `stata-code-conventions.md` | `**/*.do`, `scripts/stata/**` — header scaffold, numbered pipeline, esttab tables, clustering discipline, AEA compliance (v1.9.0) |
| Simulation Conventions | `simulation-conventions.md` | `**/*simulation*.R`, `**/*_sim.R`, `explorations/**` — Monte Carlo discipline: DGP/estimand, L'Ecuyer seeding, Monte Carlo SE, coverage-vs-truth, raw-result storage (v1.10.0) |
| R Package Conventions | `r-package-conventions.md` | `R/**`, `tests/**`, `DESCRIPTION`, `NAMESPACE`, `man/**` — package-source standards: no `library()` in `R/`, roxygen NAMESPACE, Imports/Suggests, testthat 3e, CRAN policy (v1.10.0) |
| Confidential Data | `confidential-data.md` | restricted/confidential data paths — no raw confidential data in git, disclosure-avoidance discipline, used by `/disclosure-check` / `/replication-package` / `/data-management-plan` (v2.0) |

## Hooks

| Hook | Type | Configuration |
|------|------|--------------|
| Session log auto-writer | Stop (command) | `.claude/hooks/log-reminder.py` — auto-writes the session log on every meaningful change-set (no longer merely a reminder) |
| Desktop notification | Notification (command) | `.claude/hooks/notify.sh` |
| Context state capture | PreCompact (command) | `.claude/hooks/pre-compact.py` — DRAFT-block default is ON |
| Context restoration | SessionStart[compact\|resume] (command) | `.claude/hooks/post-compact-restore.py` |
| Context monitor | PostToolUse[Bash\|Task] (command) | `.claude/hooks/context-monitor.py` |
| Git guardrails | PreToolUse (command) | `.claude/hooks/git-guardrails.py` — blocks `reset --hard` / `clean -f` / `push --force` / `add -A` |
| Claim reconcile | PostToolUse (command) | `.claude/hooks/claim-reconcile.py` — flags stale numeric claims when scripts change |

**Additional hook events** available in Claude Code (not used in this template but available for custom hooks):

| Event | When It Fires | Use Case |
|-------|--------------|----------|
| `UserPromptSubmit` | Before user message is processed | Input validation, auto-routing |
| `PermissionRequest` | When permission dialog appears | Auto-approve patterns, logging |
| `PostToolUseFailure` | When a tool call fails | Error tracking, retry logic |
| `SubagentStart` | When a subagent spawns | Resource tracking |
| `SubagentStop` | When a subagent completes | Result aggregation |
| `PostCompact` | After context compaction | Post-compaction cleanup |
| `SessionEnd` | When session closes | Final state saving, cleanup |
| `WorktreeCreate` | When a git worktree is created | Branch tracking |
| `WorktreeRemove` | When a git worktree is removed | Cleanup verification |
| `TaskCompleted` | When a background task finishes | Progress notifications |
| `ConfigChange` | When settings are modified | Audit logging |

## Troubleshooting {#troubleshooting}

### LaTeX Won't Compile

**Symptom:** `xelatex` errors or missing packages.

**Fix:**
1. Check you have XeLaTeX installed: `which xelatex`
2. Ensure `TEXINPUTS` includes `Preambles/`: the `/compile-latex` skill handles this
3. Missing package? Install via TeX Live: `tlmgr install [package]`

### Quarto Won't Render

**Symptom:** `quarto render` fails or produces broken HTML.

**Fix:**
1. Check Quarto version: `quarto --version` (need 1.3+)
2. Check for syntax errors in YAML frontmatter
3. Missing TikZ SVGs? Run `/extract-tikz` first

### Hooks Not Firing

**Symptom:** No context warnings, no auto-written session log, no git guardrails firing.

**Fix:**
1. Check hooks are configured: `cat .claude/settings.json | grep hooks`
2. Ensure Python 3 is available: `which python3`
3. Check hook file permissions: `ls -la .claude/hooks/`

### Claude Ignores Rules

**Symptom:** Claude doesn't follow conventions in `.claude/rules/`.

**Fix:**
1. Rules use `paths:` frontmatter — check the path matches your files
2. Too many rules? Claude follows ~150 instructions reliably. Consolidate.
3. Try: *"Read `.claude/rules/[rule].md` and follow it for this task"*

### Context Lost After Compaction

**Symptom:** Claude forgets what you were working on.

**Fix:**
1. Point Claude to the plan: *"Read `quality_reports/plans/[latest].md`"*
2. Check session log: *"Read `quality_reports/session_logs/[latest].md`"*
3. The `post-compact-restore.py` hook should print recovery info automatically

### Quality Score Too Low

**Symptom:** Score stuck below 80, can't commit.

**Fix:**
1. Run `/slide-excellence` to get detailed issue breakdown
2. Fix critical issues first (they cost -10 to -20 points each)
3. Ask Claude: *"What are the remaining critical issues?"*

### Skills Not Auto-Invoked

**Symptom:** Claude doesn't use skills when you describe a task.

**Fix:**
1. Be explicit in your request: *"Review my slides for grammar and layout issues"*
2. Check skill has auto-invocation enabled (no `disable-model-invocation: true`)
3. Skill descriptions help Claude know when to use them — check they're clear

### Plans Saved to Wrong Directory

**Symptom:** Plans save to `~/.claude/plans/` instead of your project directory. Can't track plans in git.

**Fix:**
Add to `.claude/settings.json`:

```json
{
  "plansDirectory": "quality_reports/plans"
}
```

This tells Claude Code to save plans inside your project where they can be version-controlled.

---

# Standing on Shoulders {#sec-acknowledgments}

This guide builds on the work of many. We are grateful to these projects and their authors.

**Core Infrastructure:**

- [Claude Code](https://code.claude.com/docs/en/overview) by Anthropic --- the CLI tool, VS Code extension, and Desktop app that makes all of this possible

**Research Workflows:**

- [clo-author](https://github.com/hugosantanna/clo-author) by Hugo Sant'Anna (UAB) --- paper-centric research workflows with adversarial agent pairs, simulated peer review, and full research lifecycle management
- [claudeblattman](https://github.com/chrisblattman/claudeblattman) by Chris Blattman (University of Chicago) --- comprehensive workflows for non-technical academics: executive assistant, proposal writing, project management, and the fresh-context critique pattern

**Reproducibility & Data Management:**

- Yiqing Xu (Stanford) and Leo Yang Yang (HKBU), "[Scaling Reproducibility: An AI-Assisted Workflow for Large-Scale Reanalysis](https://yiqingxu.org/papers/2026_ai/AI_reproducibility.pdf)," 2026 --- the template-executor architecture and principles of reproducible AI-assisted research
- [Template README for Social Science Replication Packages](https://social-science-data-editors.github.io/template_README/) by Lars Vilhuber et al. (Cornell) --- the AEA Data Editor compliance standard adopted by major economics journals

**Presentation Design & Tools:**

- [MixtapeTools / The Rhetoric of Decks](https://github.com/scunning1975/MixtapeTools/tree/main/presentations) by Scott Cunningham (Baylor) --- the philosophical and practical framework for beautiful, rhetorically effective academic presentations
- Scott Cunningham, *[Causal Inference: The Mixtape](https://mixtape.scunning.com)* --- the textbook whose author developed the presentation framework above
- [autoresearch](https://github.com/karpathy/autoresearch) by Andrej Karpathy --- constraint-based autonomous research with `program.md` as constitutional document
- [ClaudeCodeTools](https://github.com/aspi6246/ClaudeCodeTools) --- "The Editor" persona for seven-audit sequential paper review

**Origin:**

- This workflow was extracted from **Econ 730: Causal Panel Data** at Emory University, developed by Pedro Sant'Anna. The econometrics origin is one application --- the patterns are domain-agnostic and have been extended by others across fields.
