---
name: paper-explainer
description: >-
  Explain a paper (or a model/architecture release) as a single static
  webpage of hand-built d3 figures whose numbers are transcribed from source and
  asserted in-page. Use when the user says "explain this paper with a webpage",
  "make an explainer site", "turn this tech report into a page", "visual
  walkthrough of the architecture", "build a site for this paper", or asks for an
  interactive figure-driven writeup of a PDF/arXiv/HF model release. Covers the
  whole workflow: paper -> markdown, source-of-truth constants, one scrolling
  page with a glossary and numbered figures, porting the real algorithm to JS,
  seeded numpy fixtures replayed by console.assert, and the browser-based
  verification gate (playwright regression, DOM overlap audit, vision-judged
  screenshots). Worked example: the DeepSeek-V4.1-Flash architecture explainer.
---

# Explaining a paper with a webpage

## What you are building

One static page. No build step, no framework, no CDN — `index.html`, one CSS
file, one data file, one app file, a vendored `d3.v7.min.js`, and the paper's own
figures as PNGs. It opens in a browser from any static file server — this skill
ships one (`scripts/serve.py`), launched the only way that works, under
`proc("start")`; see the verification gate.

The page explains **the mechanism**, not the marketing. Every architectural
decision: what it replaces, what it costs, what the trade is. Benchmarks and eval
tables stay out unless the user explicitly asks for them — they age badly and they
are not explanations.

## The one idea that makes it work

**The page is a program, not a document.**

- Every number on the page lives in `assets/data.js` and nowhere else. Not in the
  HTML, not hardcoded in a chart function.
- Structural constants (dims, layer counts, head counts) are typed **once**, in a
  single top-level config object, and every shape on the page is computed from it.
- Where the paper describes an algorithm, the page **runs it**: the real algorithm
  ported to JS, over a seeded fixture, with `console.assert` comparing the JS
  result to a numpy transcription of the same input.
- The test suite is a browser. `console.assert` failures surface as console
  messages of type `assert`, which the regression script collects. One command
  tells you whether the page is true.

A figure that draws a number is a claim. A figure that *computes* the number and
asserts it against an independent transcription is evidence. That difference is
the whole skill.

## Workflow

### Phase 0 — get the sources, then map them

1. **The paper as markdown.** Convert the PDF (docling is in the `use-uv`
   sandbox: `docling` on the CLI). Keep it beside the site as `report.md` — the
   page's prose and figcaptions cite it by section and line.
2. **The code, if there is any.** An HF model release gives you `config.json`,
   `model.py`, the kernel file, the tokenizer. Clone it next to the site and
   gitignore it. Check whether the weights are real or git-lfs pointers before
   you plan anything that needs tensor *values* — pointer files are 134 bytes and
   there is nothing inside them. `model.safetensors.index.json` still gives you
   every tensor **name**, which is enough to prove claims about what a layer owns.
3. **Pick the source of truth for constants** and write it down. HF repos often
   ship two configs (a flat internal one and a nested HF-style one) with the same
   numbers in different places. Choose one, cite it, and never let a constant
   exist in two spellings.
4. **Build a line map.** For each source file, a list of `symbol → line`. For the
   report, `§ → line`. This is the single highest-leverage artifact of the whole
   project: every later phase is "read these 40 lines, port them". Without it you
   re-read 1300-line files over and over.
5. **Note what is off-limits.** Benchmark sections, eval tables, leaderboard
   numbers. Write the exclusion into the plan so a later phase does not drift.

### Phase 1 — the skeleton

Create the five files and the two conventions that everything else hangs off:

- **Sections** are numbered `00`, `01`, `02`… in `.sec-no`, each with an id like
  `s-vocab`, `s-kv`. Section `00` is always the glossary.
- **Figures** are numbered `Fig 1`, `Fig 2`… in `.fig-title`, in document order.

Section 00 is a `<dl class="defs">` of `.def` cards — every term the page will
use, defined before it is used. This is not decoration: it is the contract. When
a later phase introduces a term, it adds a card, and the card count in the §00
subtitle is updated. A term used on the page with no card is a bug.

Ship the skeleton with two or three real figures so the plumbing (server,
regression script, tooltip, `BUILD` map) is proven before you have 27 of them.

See `references/anatomy.md` for the exact file layout, the HTML templates, and the
CSS class inventory.

### Phase 2..N — one subject per phase

Strictly in order, one phase per subject, each shipped and committed before the
next starts. A phase is:

1. **Read** the source lines for this subject, with the algorithm written out as a
   numbered list in the code's own order *before* you touch the page. If you
   cannot write the list, you do not understand it yet — do not start drawing.
2. **Data.** Add this subject's block to `data.js`: constants (referencing the
   top-level config object, never retyping it), the series, and any fixture.
3. **Port.** If the subject is an algorithm, port it to JS in `app.js` — faithful
   to the source's order, including the parts that look like no-ops (a `relu`, a
   `sort()` after a `topk`, a mask applied before a normalization).
4. **Fixture + assert.** Generate the fixture in numpy from a seeded RNG, store it
   rounded, and `console.assert` the JS replay against it at load. See
   `references/fixtures.md` — this is where most of the trust comes from and where
   most of the subtle bugs live.
5. **Draw.** The figure. `fig-title` (what it is), `fig-why` (why this drawing and
   not a table), the chart div, `figcaption.cap` (provenance: which section, which
   lines, and — critically — **whether this is reported or reconstructed**).
6. **Interact.** A toggle or slider is worth more than three static charts, but
   only if it actually re-runs the computation. See the "cosmetic toggle" trap in
   `references/gotchas.md`.
7. **Prose + glossary.** Grow the section's prose, add the new §00 cards, update
   the card count.
8. **Verify.** The gate below. Judge the screenshot with `vision` — do not ship a
   figure you have not looked at.
9. **Renumber** if you inserted a figure mid-page, then fix the prose
   cross-references by hand.
10. **Commit**, and mark the phase done in the plan with an evidence block.

### Final phase — close the page

Per-phase passes miss whole-page problems. The closing phase is its own work:

- Re-read the whole page in the browser as tall screenshots in thirds, each judged
  by `vision`: sections in order, every figure inside its frame, no overlaps, no
  empty bands, footer last.
- Figure numbers contiguous from 1, section numbers contiguous from 00. List them
  in the commit message.
- Every internal cross-reference (`§3`, "see §08") resolves to a section that
  exists **and says what the reference claims**. Citations of the *paper* keep
  their own decimal form (`§2.3.1`) and must never be confusable with a page ref.
- No orphaned pointer paragraphs; no "Phase", "TODO" or "FIXME" left in the HTML.
- Header chips and `meta[name=description]` still true after everything landed.
- **Consistency sweep:** dump `data.js` from node, diff every constant against the
  source of truth, paste the empty diff into the commit message. Then hunt for
  re-typed structural constants and fold them onto the one config object.

## The verification gate

There is no test suite. The gate is syntax + a real browser + your eyes. Drive it
with `proc`, never with `subprocess` — the reason is at the end of this section
and it cost a kernel reset to learn.

```python
import shutil, time
from pathlib import Path

SK   = Path("~/.agents/skills/paper-explainer").expanduser()
UV   = "uv --project ~/.agents/skills/use-uv run python"
SITE = "/path/to/site"

async def run(cmd, **kw):                    # every step below is then one line
    r = await proc("run", cmd, timeout=240, **kw)
    print(r.text)
    return r

# 0. syntax, after every JS edit — both files
await run("node --check assets/app.js && node --check assets/data.js && echo OK", cwd=SITE)

# 1. serve once per session. proc("start") returns in ~0 ms and the server
#    outlives the cell, the kernel and a reset.
Path("/tmp/siteport.txt").unlink(missing_ok=True)   # a stale portfile lies
srv = await proc("start", f"{UV} {SK}/scripts/serve.py {SITE}")
while not Path("/tmp/siteport.txt").exists():
    time.sleep(0.2)                                 # ~1 s: uv resolves, socket binds
PORT = Path("/tmp/siteport.txt").read_text().strip()

# 2. regression: screenshots + console errors + failed asserts + page height
await run(f"""{UV} {SK}/scripts/regress.py /tmp/shots '{{"walk":"#c-sinkhorn-walk"}}' true""", cwd=SITE)
#    -> ERRORS: []  ASSERTS: []  WARNINGS: []; exit 1 unless the first two are empty

# 3. DOM overlap audit: labels spilling out of a chart or sitting on each other
await run(f"{UV} {SK}/scripts/overlap.py", cwd=SITE)      # -> BAD: []  CONSOLE: []

# 4. read data.js back from node and diff it against the source of truth
await run(f"node {SK}/scripts/dumpdata.js assets/data.js 'KCFG.dim,DS.train.alg'", cwd=SITE)

# 5. renumber figures after a mid-page insertion (--dry reports; no flag rewrites)
await run(f"{UV} {SK}/scripts/renumber.py index.html --dry", cwd=SITE)

await proc("kill", pid=srv.pid)                    # when the session is done
Path("/tmp/siteport.txt").unlink(missing_ok=True)  # a portfile outliving its server is a lie
```

Then `await vision("file", "/tmp/shots/walk.png", "describe this figure; is any
label cut off, overlapping, or outside its frame?")` on every shot you took.

**Why `proc` and not `subprocess`.** `serve.py` stays in the foreground on
purpose — detaching is the launcher's job. Launch it with
`subprocess.run(cmd, capture_output=True)` and the cell never returns: not a
signal problem, a file-descriptor one. `capture_output` waits for EOF on a pipe,
EOF arrives only when *every* holder of the write end closes it, and the server
you just backgrounded is holding it. Measured: `bash -c 'sleep 8 & echo hi'`
under `subprocess.run(..., capture_output=True, timeout=3)` raises
`TimeoutExpired` — bash exited in milliseconds, `communicate()` was still
waiting three seconds later, and with no timeout it waits forever. `nohup`,
`setsid` and `start_new_session=True` do not help; they change signal
disposition and session membership, not descriptors. `proc("start", ...)` points
stdout/stderr at a log file instead of a pipe, which is the actual fix, and
`proc("run", ...)` waits on the *process* and then drains for ≤2 s, so even an
accidental `&` returns with its partial output and a `.note` naming the trap
instead of wedging the kernel.

**Prove the gate can fail.** `BAD: []` from a selector that matched nothing is
indistinguishable from a clean page, so once per site — and any time you touch
the audit scripts — inject a known break and check the gate goes red:

```python
mut = Path("/tmp/mutsite"); shutil.rmtree(mut, ignore_errors=True); mut.mkdir()
(mut/"assets").symlink_to(Path(SITE)/"assets")
h = (Path(SITE)/"index.html").read_text()
(mut/"index.html").write_text(h.replace("</body>", """
<script>setTimeout(function () {
  console.assert(1 === 2, "MUTATION fixture assert must fail");
  console.error("MUTATION deliberate page error");
  var svg = document.querySelector("figure .chart svg");
  var t = document.createElementNS("http://www.w3.org/2000/svg", "text");
  t.setAttribute("x", svg.getBoundingClientRect().width + 200);
  t.setAttribute("y", 20); t.textContent = "MUTATION stray label";
  svg.appendChild(t);
  var u = t.cloneNode(true);                 // same spot: the overlap detector
  u.textContent = "MUTATION second label on the first";
  svg.appendChild(u);
}, 400);</script></body>"""))
m   = await proc("start", f"{UV} {SK}/scripts/serve.py {mut} --portfile /tmp/mutport.txt")
while not Path("/tmp/mutport.txt").exists():
    time.sleep(0.2)                     # spawned is not ready — same rule as step 1
env = {"SITE_PORTFILE": "/tmp/mutport.txt"}
await run(f"""{UV} {SK}/scripts/regress.py /tmp/mutshots '{{}}' false""", env=env)
await run(f"{UV} {SK}/scripts/overlap.py", env=env)
await proc("kill", pid=m.pid)
shutil.rmtree(mut); shutil.rmtree("/tmp/mutshots", ignore_errors=True)
Path("/tmp/mutport.txt").unlink(missing_ok=True)   # never leave a portfile behind
```

Observed on the example site, running the block above verbatim:
`ERRORS: ["MUTATION deliberate page error"]`,
`ASSERTS: ["MUTATION fixture assert must fail"]`, and a `BAD` list of three —
two `overflow` entries (418.1 px and 562.2 px past the frame) plus the
`overlap` between them — with both scripts exiting 1. The same commands against
the real site exit 0 with all five lists empty.

**Know the population an empty result is a claim about.** On the example page
`figure .chart` matches 27 hosts holding 720 `<text>` nodes and 27 `<svg>`s,
none of them empty. If you change the page structure, re-count before trusting
`BAD: []`:

```python
await pg.evaluate("() => [document.querySelectorAll('figure .chart').length,"
                  " document.querySelectorAll('figure .chart text').length]")
```

**Non-negotiables:**

- Launch the server with `proc("start", ...)`, and delete a stale
  `/tmp/siteport.txt` first — a leftover portfile from a dead daemon reads like
  a live server and every script then fails against nothing.
- `add_style_tag("html{scroll-behavior:auto!important}")` in every playwright
  script. Smooth scrolling makes `scroll_into_view_if_needed()` land
  mid-animation and you screenshot a half-drawn chart.
- Wait ~1400 ms after scrolling before screenshotting — d3 transitions take 900.
- `node --check` both JS files after every edit, before you open a browser. A
  syntax error in `data.js` presents as "every chart is empty", not as an error.
- A phase is not done until the regression is clean **and** you have looked at the
  screenshot.

## Honesty rules

These are what separate an explainer from a press release.

- **Cite the line.** Figcaptions name the section and the line range they came
  from. A reader should be able to check you.
- **Label reconstruction as reconstruction.** If the paper says "15 kernels" and
  you had to infer the grouping from the code path, say so in the caption and say
  which parts are not visible in the repo. Do not let your inference wear the
  paper's authority.
- **State scaling honestly.** A demo that runs 12 positions where the real system
  runs 16,384 must say so on the page, in the caption, next to the demo — and
  keep the real number visible somewhere in the same figure.
- **Quote the caveats.** When the paper admits an approximation ("not
  mathematically equivalent", "negligible impact on quality"), that admission goes
  on the page in a `.callout.warn`, in the paper's own words, with the citation.
- **Two things with the same name are two things.** If a model has two different
  Sinkhorn iterations, or two different top-k values, never let a sentence imply
  they are one. Name them separately every time.
- **No tensor values you did not see.** If the weights are lfs pointers, your
  claims are about names and shapes, and they are labelled that way.

## Planning and recording

For anything bigger than three figures, write a `PLAN.md` and a `TODO.md` in the
repo and work them item by item — see the `plan-todo` skill. The shape that works
here:

- One `## Phase N — subject` per subject, with the source lines listed up front.
- Numbered items `**N.1**`, `**N.2**`…, each with an explicit
  `*Verified by:* …` clause stating the observable criterion.
- A phase-level evidence block appended when the phase passes:
  `Evidence, <date>, all K items:` then one bullet per item with what was actually
  observed — counts, pixel heights, assert results, the empty diff.
- `TODO.md` boxes as `- [x] **Title.** (date; details)`.

Write the `*Verified by:*` clause **before** doing the work. "Screenshot judged by
vision" is a criterion; "looks good" is not.

Commit at the end of every phase, `git commit -a -F /tmp/msgN.txt`, with your
session id as a trailer. List the figure and section numbers in the closing
commit's message.

## References

- `references/anatomy.md` — file layout, HTML templates, CSS class inventory, the
  `BUILD` map, chart-function shape.
- `references/fixtures.md` — the fixture discipline end to end: seeded numpy,
  rounding, JS replay, tolerance, and the mutation test that proves the assert
  can fail.
- `references/gotchas.md` — every landmine already paid for, d3 and playwright
  and editing alike.
- `examples/deepseek-v4.1-flash.md` — the worked example: 13 sections, 27
  figures, 58 glossary cards, 35 in-page asserts, and the phase history that
  produced it, with the gate's output re-verified against the live page.
- `scripts/` — the five gate commands, all of them run against the example site:
  `serve.py` (foreground static server, free port, writes the portfile),
  `regress.py` (screenshots + the three console buckets + page height),
  `overlap.py` (the DOM overflow/overlap audit), `dumpdata.js` (read `data.js`
  back from node so you can diff it), `renumber.py` (renumber `Fig N ·` titles
  in document order, `--dry` to report).
