# Latex

> Use when you need to compile a LaTeX document — includes autonomous error resolution, citation audit, and quality scoring.

- **Type:** Skill
- **Install:** `agentstack add skill-flonat-claude-research-latex`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [flonat](https://agentstack.voostack.com/s/flonat)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [flonat](https://github.com/flonat)
- **Source:** https://github.com/flonat/claude-research/tree/main/skills/latex

## Install

```sh
agentstack add skill-flonat-claude-research-latex
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# LaTeX Document Compilation

> Default compilation skill for all LaTeX documents. Compiles with autonomous error detection and resolution (up to 5 iterations), runs a citation audit on clean builds, and produces a quality score.

## When to Use

- **Default method** for all LaTeX compilation
- Any `.tex` file that should compile to PDF
- When compilation fails and you want automatic diagnosis and repair
- When you want a post-compilation citation audit

## When NOT to Use

- Markdown documents — use plain markdown, not LaTeX
- Quick notes or drafts — LaTeX overhead not worth it
- Documents that don't need citations, equations, or precise formatting
- Documents with exotic custom classes that need manual debugging

---

## Quality Scoring

Apply numeric quality scoring using the shared framework and skill-specific rubric:

- **Framework:** [`../shared/quality-scoring.md`](../shared/quality-scoring.md) — severity tiers, thresholds, verdict rules
- **Rubric:** [`references/quality-rubric.md`](references/quality-rubric.md) — issue-to-deduction mappings for this skill

Start at 100, deduct per issue found, apply verdict. Include the Score Block in the final report.

## Critical Rules

1. **Build artifacts go to `out/`, PDF stays in the source directory.** Ensure `.latexmkrc` exists with `$out_dir = 'out'` and an `END {}` block to copy the PDF back (see pre-flight below). For VS Code builds, `.latexmkrc` in subdirectories is **not picked up** — see "VS Code Integration" section for the required `.vscode/settings.json` config.
2. **NEVER write BibTeX entries from memory.** Always verify against web sources (CrossRef, Google Scholar, DOI lookup) before writing. See the `/literature` skill.
3. **Check document class before adding packages.** Some classes load packages internally (e.g., `elsarticle` loads `natbib` — adding `\usepackage{natbib}` causes errors).
4. **Maximum 5 fix iterations.** If the document still has errors after 5 auto-fix cycles, stop and report the unresolved errors to the user.
5. **Never silently swallow errors.** Every fix must be reported: what was wrong, what was changed, and which file was edited.
6. **Preserve user intent.** Auto-fixes should be minimal and conservative. Add packages or overrides — never remove user content.
7. **Citation audit requires clean compilation.** Only run the `\cite{}` vs `.bib` cross-check after zero errors.
8. **Run `/bib-validate` when new citations were added.** The citation audit only checks key cross-references. When `.bib` entries were added or modified since the last validation, also run `/bib-validate` for full metadata quality checks (preprint staleness, DOI presence, required fields, author formatting). This is mandatory.

---

## Protocol

### Phase 1: Pre-flight

1. **Locate the `.tex` file.** Resolve the path (absolute or relative to CWD).
2. **Identify the project directory** — the folder containing the `.tex` file.
3. **Ensure `.latexmkrc` exists** in the project directory with at minimum:
   ```perl
   $out_dir = 'out';
   # Copy PDF back to source directory after build
   END { system("cp $out_dir/*.pdf . 2>/dev/null") if defined $out_dir; }
   ```
   If a `.latexmkrc` already exists, verify it sets `$out_dir = 'out'` and has the `END {}` block. If either is missing, add it. Do not overwrite other settings.
4. **Create `out/` directory** if it doesn't exist: `mkdir -p /out`.
5. **Identify the `.bib` file(s)** referenced in the document (scan for `\bibliography{}`, `\addbibresource{}`, or `\bibinput{}`). Note their paths for Phase 5.

### Phase 2: Compile-Fix Loop

Run up to **5 iterations**. Each iteration:

#### Step 2a — Compile

```bash
cd  && latexmk -interaction=nonstopmode .tex 2>&1
```

Capture the full output. The log file will be at `out/.log`.

#### Step 2b — Read the log

Read `out/.log` in full. Parse for errors and warnings.

#### Step 2c — Classify errors

Check the log against the known error patterns below. If an error matches, apply the fix and go to Step 2a. If no known pattern matches, record the error as **unresolved** and stop the loop.

**Same-error circuit breaker.** Independent of the 5-iteration cap: if the same error (same line family, same pattern signature) survives **3 consecutive fix attempts**, stop the loop early. Continued attempts on a stuck error compound damage rather than resolve it. Report what was tried, quote the log line, and ask the user how to proceed. A common signature: `Illegal parameter number` jumping between line numbers as you edit — that is the diagnostic for a parameterized TikZ style defined inside a Beamer frame; see `skills/shared/tikz-rules.md` Rule 11.

---

### Known Error Patterns & Auto-Fixes

Check the log against these patterns. Full fix instructions: [`references/known-errors.md`](references/known-errors.md)

| # | Pattern | Key log signature |
|---|---------|-------------------|
| 1 | Missing package | `File '.sty' not found` or undefined command from known package |
| 2 | Font/symbol conflicts | `Command \ already defined` |
| 3 | Undefined citation | `Citation '' ... undefined` or biblatex entry not found |
| 4 | Missing image/file | `File '' not found` (pdftex.def or LaTeX) |
| 5 | Stale auxiliary files | Corrupted `.aux`/`.bbl`/`.bcf`, or `no \bibstyle command` |
| 6 | Beamer/enumitem clash | `Option clash for package enumitem` or `\item already defined` |
| 7 | xcolor option conflicts | `Option clash for package xcolor` or undefined `\rowcolor` |
| 8 | TikZ reserved keys | `I do not know the key '/tikz/'` or pgfkeys error |

If an error matches, read the full fix from the reference and apply it. If no pattern matches, record as **unresolved** and stop the loop.

#### 2.4 PDF backup (paper directories only)

**Only run if the compile-fix loop above ended with a successful compilation (PDF exists).**

If the `.tex` file is inside a `paper-{venue}/paper/` structure (where `paper/` is a symlink to Overleaf):

1. **Identify the paper wrapper** — the parent of the `paper/` symlink (e.g., `paper-jbdm/`).
2. **Create the backup directory:** `mkdir -p /backup`
3. **Copy the PDF:**
   ```bash
   cp /paper/.pdf /backup/_vcurrent.pdf
   ```

**Detection logic:**

- The project directory containing the `.tex` file is a symlink named `paper`.
- Its parent directory name starts with `paper-`.
- If either condition is false, skip this sub-step silently.

---

### Phase 3: Final Report

After the loop ends (either clean compilation or max iterations reached), report:

#### Compilation Status

| Field | Value |
|-------|-------|
| **Status** | Clean / Errors remaining |
| **Iterations** | N of 5 |
| **Pages** | (from log: `Output written on ... (N pages)`) |
| **LaTeX/package warnings** | Count of `Warning`-tagged log lines (undefined refs, font subs, package warnings) |
| **Typographic boxes** | Overfull/underfull h/vboxes by severity — see box report below (NOT counted by a `Warning` grep) |
| **Fixes applied** | List each fix: what error, what was changed, which file |
| **Unresolved errors** | List any errors that couldn't be auto-fixed |

#### How to extract page count

```bash
grep -o "Output written on .* ([0-9]* page" out/.log | grep -o "[0-9]* page"
```

#### How to count warnings and boxes

Warnings and typographic boxes are **separate** — box messages are not
`Warning`-tagged, so a single `Warning` grep misses every overfull/underfull box.
Report both, using the recipes in [`../shared/overfull-boxes.md`](../shared/overfull-boxes.md):

```bash
# LaTeX/package warnings (refs, fonts, packages)
grep -c "Warning" out/.log
# Overfull/underfull boxes (the thing the Warning grep cannot see)
grep -cE 'Overfull \\[hv]box \([0-9.]+pt too (wide|high)\)' out/.log
grep -cE 'Underfull \\[hv]box \(badness [0-9]+\)' out/.log
```

#### Box report (typographic quality)

Extract the top offenders by overflow magnitude and report each box `≥ 1 pt` with
its location, width, and a remediation tier per the severity gradient + ladder in
[`../shared/overfull-boxes.md`](../shared/overfull-boxes.md):

```bash
awk -F'[()]' '/Overfull \\[hv]box/ {
    split($2, a, "pt"); w = a[1] + 0;
    loc = $0; sub(/.*too (wide|high)\) */, "", loc);
    printf "%7.1f pt  %s\n", w, loc
}' out/.log | sort -rn | head -20
```

Report only — do not silently reword prose to close a box (`rules/manuscript-edit-budget.md`).
The only safe auto-fix is inserting `\usepackage{microtype}` when genuinely absent.

**Breadcrumb:** Append to `.planning/state.md` (if exists) or `.context/current-focus.md`:
```
### [/latex] Compilation complete [YYYY-MM-DD HH:MM]
- **Done:** [Clean/Errors remaining, N iterations, N pages, N fixes applied]
- **Outputs:** [PDF at ]
- **Next:** [Citation audit (if clean) or manual error resolution]
```

---

### Phase 4: Visual-Fragility Source Lint (clean builds only)

**Only run if Phase 2 ended with zero errors.** Sits between the final report (Phase 3) and the citation audit (Phase 5). Catches LaTeX source patterns that compile clean but produce visually fragile output — the failure class the title-page incident (2026-06-19) exposed.

Full detector catalogue with regex signatures, severity tiers, remediation, and false-positive caveats: [`references/source-pathologies.md`](references/source-pathologies.md).

#### What to run

1. **Nine grep-based source-pathology detectors** against `main.tex` plus any `\input`/`\include`'d files:

   | # | Pattern | Tier |
   |---|---|---|
   | 1 | Spacing hacks fighting global spacing (`\onehalfspacing` + local `\\[-Xcm]` / `\vspace{-…}`) | Major |
   | 2 | Manual vertical-rhythm surgery (repeated `\vspace`/`\vskip`/`\pagebreak` in body) | Moderate–Major |
   | 3 | Line breaks as layout engine (`\\` / `\newline` / `\linebreak` inside `\section`/`\caption`) | Moderate–Major |
   | 4 | Forced-float carpet bombing (`[H]`/`[!h]` pinning, `\FloatBarrier` overuse) | Moderate |
   | 5 | Shrink-to-fit tables/figures (`\resizebox{\textwidth}{!}{…}`, `\adjustbox{width=\textwidth}`) | Major |
   | 6 | Tiny-table typography hacks (`\scriptsize`/`\tiny` in tables; negative `\tabcolsep`; `\arraystretch&1 | grep -v "^$"`. Advisory only — collect warnings; deduct -1 each, capped at -10. Skip if `chktex` not on PATH.

3. **`latexindent -k`** if installed: `latexindent -k main.tex 2>&1; echo "Exit: $?"`. Source-cleanliness smoke test. Non-zero exit → -3 once. Skip if `latexindent` not on PATH.

#### Output

Append a **Source pathologies** subsection to the Phase 3 report:

```markdown
### Source pathologies

| Pattern | Location | Detail | Tier |
|---------|----------|--------|------|
| 1 Spacing-hacks | titlepage, line 56 | `\\[-0.3cm]` under global `\onehalfspacing` (line 43) | Major |
| 9 Label-before-caption | tab:results, line 412 | `\label` at L410 precedes `\caption` at L413 | Major |
```

If no findings: "No source pathologies detected." If `chktex` or `latexindent` ran, note their PASS/N-warnings status.

#### Auto-fix scope

Phase 4 is **report-only**, with one exception: Pattern 1 ("Spacing hacks fighting global spacing") has a deterministic remediation (wrap the affected block in `\begin{singlespace}…\end{singlespace}`, delete the negative kerns). The skill **offers** this as an opt-in fix in the final report; the user accepts or declines per case. Do not auto-apply.

For Patterns 2–9 and tool findings: report only.

#### When to skip

- Compile failed in Phase 2 (pathology lint is meaningless without a build).
- User explicitly invoked `/latex --no-lint`.

---

### Phase 5: Citation Audit (clean builds only)

**Only run this phase if Phase 2 ended with zero errors.**

1. **Extract all `\cite` keys** from the `.tex` file (and any `\input`/`\include` files):
   - Match `\cite{...}`, `\citep{...}`, `\citet{...}`, `\textcite{...}`, `\parencite{...}`, `\autocite{...}`, and multi-key variants like `\cite{key1,key2}`.
2. **Extract all bib entry keys** from the `.bib` file(s): match `@{,`.
3. **Cross-reference:**

| Check | What it finds |
|-------|--------------|
| **Missing in .bib** | Keys cited in `.tex` but absent from `.bib` |
| **Unused in .tex** | Keys defined in `.bib` but never cited |
| **Possible typos** | Near-matches between missing cite keys and existing bib keys |

4. **Report** the results as a table. Do not modify any files during the audit — report only.

---

### Phase 6: Quality Score

After all phases complete, compute the quality score:

1. Read [`references/quality-rubric.md`](references/quality-rubric.md) for deduction mappings.
2. Log every issue from Phases 2-5 (unresolved errors, remaining warnings, overfull/underfull boxes from the Phase 3 box report, citation mismatches). The rubric deducts per box by severity (`>10pt: -5`, `1-10pt: -2`, underfull: `-1`) — feed it the box report, not a `Warning` count.
3. Compute score (100 - total deductions), apply verdict per [`../shared/quality-scoring.md`](../shared/quality-scoring.md).
4. Append the Score Block to the compilation report:

```markdown
## Quality Score

| Metric | Value |
|--------|-------|
| **Score** | XX / 100 |
| **Verdict** | Ship / Ship with notes / Revise / Revise (major) / Blocked |

### Deductions

| # | Issue | Tier | Deduction | Category |
|---|-------|------|-----------|----------|
| 1 | [description] | [tier] | -X | [category] |
| | **Total deductions** | | **-XX** | |
```

#### 6.1 Output verification (before commit)

When the compile produced a PDF (and any backup copy), emit an outputs manifest and run the shared verifier per [`_shared/verify-outputs.md`](../_shared/verify-outputs.md):

1. Write manifest to `/.claude/state/outputs-manifest-.json` listing every file written this invocation (PDF, backup PDF if 2.4 ran, log files).
2. Run:

   ```bash
   python3 "$HOME/.claude/skills/_shared/verify_outputs.py" \
       --manifest "$MANIFEST" \
       --project-root "$PROJECT_ROOT"
   ```

3. If the verifier exits non-zero, **do not commit**. Surface the missing-files list and stop.

Closes the "hallucinated outputs" failure class (commit `b2cff75`, 2026-04-18).

---

## Configuration Reference

### Output Directory

All LaTeX build artifacts (`.aux`, `.log`, `.bbl`, `.fls`, etc.) go to an `out/` subfolder relative to the source file. The **PDF is copied back** to the source directory after each successful build, so it lives alongside the `.tex` file for easy access.

The PDF-copy convention is enforced in **two places** — keep them in sync when making changes:

1. **`.latexmkrc`** (per-project) — Perl `END {}` block copies PDF after terminal/Claude Code builds
2. **VS Code `.vscode/settings.json`** (per-workspace) — explicit latexmk args in LaTeX Workshop tool definition

VS Code integration, engine auto-detection (pdfLaTeX/XeLaTeX/LuaLaTeX), manual override configs, reference checking scripts, and manual compilation commands:

**[references/latex-configs.md](references/latex-configs.md)**

### Overleaf-Synced Projects

When a project is synced to Overleaf (via Dropbox or Git):
- The `out/` directory will sync to Overleaf but Overleaf ignores it — this is fine
- Always use `.latexmkrc` to enforce `out/` — Overleaf ignores this file too
- Overleaf compiles independently on its server; local compilation is for verification only
- The `.bst` file (e.g., `elsarticle-harv.bst`) lives in the source directory, not `out/`

### Local-Only Projects (No Overleaf)

Not all projects sync to Overleaf. For local-only projects:
- The same `out/` and `.latexmkrc` conventions apply — this keeps the working directory clean regardless of sync method
- There is no `paper/` symlink — `.tex` files live directly in the project root or a subdirectory

---

## Templates

See [`references/templates.md`](references/templates.md) for working paper template location, files, citation style toggle, bibliography file naming conventions, and bibliography command reference.

---

## Related Skills

| Situation | Delegate to |
|-----------|-------------|
| Need to find or verify a bibliography entry | `/litera

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [flonat](https://github.com/flonat)
- **Source:** [flonat/claude-research](https://github.com/flonat/claude-research)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-flonat-claude-research-latex
- Seller: https://agentstack.voostack.com/s/flonat
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
