# legible-explainer

Adopt this skill: https://proskills.md/skills/other/futureatoms-karpathy-ladder-skills-legible-explainer

Page: https://proskills.md/skills/other/futureatoms-karpathy-ladder-skills-legible-explainer
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/legible-explainer/SKILL.md
size: 12658
sha: bd08effff18a95477a7fcd5e5051052315ca1f59
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/SKILL.md

````text
---
name: legible-explainer
description: "Explain a subject in the format that is easiest to understand, following Karpathy's output-format ladder: ASD-STE100 Simplified Technical English prose, then a diagram, then a self-contained HTML spec sheet drawn like an engineering drawing, then a narrated explainer video. Use it when the user asks for an explanation as the deliverable: explain a concept, protocol, system, codebase, spec, plan, diff or a long agent-written output; help them understand text they cannot follow or have no time to read; or asks for STE, ASD-STE100, Simplified Technical English, controlled language, 'explain it 80% STE', a diagram to keep open while they work, an explainer page or one-page overview, a cheat sheet or spec sheet, an explanation 'in HTML', or a 3Blue1Brown-style explainer video. Not for production UI, landing pages, dashboards, slide decks, promo videos or diagrams the user wants to edit."
---

# Legible explainer

As agents do more of the work, the human job moves toward oversight and
understanding. The format of an explanation decides how fast a reader
understands it. Karpathy's ladder, from cheapest to richest:

1. **STE prose**: ASD-STE100 rules (short sentences, one meaning for each word,
   active voice, approved verb forms) make text much easier to read. Default to
   about 80% of the way to strict STE, because full STE is stiff.
2. **Diagram**: structure, sequence and state are faster to see than to read.
3. **HTML page**: a dense, self-contained page with several views of the same
   subject. Here it is a "spec sheet" in the visual language of an engineering
   drawing: zone frame, lettered panels, title block.
4. **Explainer video**: narration plus motion, for subjects that unfold in time.

Each tier reuses the one below it. Sheet text is STE. Video scenes come from
sheet panels. A good result at a lower tier is a better answer than a weak
result at a higher tier.

## Pick the tier

An explicit request for a format always wins ("in HTML", "draw", "video",
"in STE"). Otherwise choose the lowest tier that fully serves the reader:

| Signal in the request | Tier | Output |
|---|---|---|
| A direct question, a procedure, a short concept, or "explain in STE" | 1 STE prose | The answer in chat, sized to the question |
| The subject is a sequence, flow, hierarchy, state machine or architecture; "draw", "diagram", "something to keep open" | 2 Diagram | One `.html` page with an inline SVG diagram |
| Several facets (parts, rules, numbers, history, risks); "overview", "one-pager", "explainer page", an explanation "in HTML"; or "help me understand this long output / plan / diff / spec" | 3 Spec sheet | One self-contained `.html` sheet, sized to the subject |
| "Video", "3b1b style", "narrated", "animated explainer" | 4 Video | An `.mp4` with narration: Manim for a 3Blue1Brown look, otherwise the `hyperframes` skill |

Neighbouring skills, when they are installed: a production page, app UI or dashboard belongs to
`frontend-design`; a diagram the user will keep editing belongs to
`excalidraw-diagrams`; a promo or product video belongs to `hyperframes` on
its own. Use this skill when the reader's understanding of a subject is the
product.

**Offer the next tier** in one line only when the subject shows that tier's
signal and the user named no format (a request for STE is a writing style,
not a format): a diagram when the answer has a sequence,
flow or state; a sheet when it has several facets; a video only when the
subject unfolds in time. Do not offer after a short tier 1 answer, after a
video, or a video for a document review.

## Answer first (every tier)

The reader asked a question. Whatever the tier, the first thing they read is
the answer: the difference, the verdict, the cause, in one or two sentences.
Then the support. Answer the topics the user named, at the depth they asked
for; give a side topic one line, or leave it out. A longer answer is not a
better answer.

## Write in STE (every tier)

Read `references/ste-writing.md` before you write the first sentence. The core:

- At most 20 words in an instruction, 25 in a descriptive sentence, 6 sentences in a paragraph, one topic in a paragraph. A number and its unit count as one word.
- One instruction in each sentence. Put a condition first. Start a WARNING or CAUTION with the command, then give the risk.
- Verb forms: imperative, simple present, simple past, simple future, infinitive, and the past participle as an adjective. No -ing verb forms (progressive, gerund, participle) except inside a technical noun. No perfect tenses. No phrasal verbs ("set up", "carry out").
- Active voice. No passive in instructions. In descriptions, the passive only when the agent is not known.
- One word for one meaning, the same word for the same thing every time. Technical nouns and technical verbs of the subject are allowed, each only in its own part of speech. Multi-word nouns of 3 words at most. No semicolons. American spelling.

**The dial.** "80%" (default) keeps all the grammar above and relaxes the word
list: keep a non-STE word when the STE word is clumsy or changes the meaning.
"Strict" (when the user asks for it) also replaces every unapproved word you
know of; when a sentence cannot be both strict and clear, rewrite it, and if
that fails, tell the user which sentence breaks which rule.

**Keep the meaning.** When you simplify a source, keep its certainty
("should" stays an expectation), conditions, negations, attributions, numbers
and units. A simpler sentence that says more or less than the source is wrong.

**House style** (opinionated defaults on top of STE; edit them to taste): no em dashes; never the word
"caveat"; never open with a headcount ("three things to check"), introduce a
list by its subject ("What to check:"); no "X, not Y" framing, state what is
true as its own sentence; no emoji; add an as-of date to a number that can
change.

Lint what you write, with the mode you are writing in:

```bash
python3 <skill-dir>/scripts/ste_lint.py <file> --mode 80          # or --mode strict
printf '%s' "$DRAFT" | python3 <skill-dir>/scripts/ste_lint.py - --mode 80   # a chat answer (stdin is read as Markdown)
```

The linter fails on grammar errors (length, verb forms, voice, semicolons,
dashes, house style) and warns on word-level findings. It knows a short list
of common unapproved words; the STE dictionary is the authority. PASS means
the floor is met: fix every finding that is not a false alarm, and keep an
unapproved word only on purpose. Quote non-STE text on purpose (an "original
text" in a before-and-after, a line from a source document) inside
`data-ste="ignore"` in HTML, or between `<!-- ste-ignore-start -->` and
`<!-- ste-ignore-end -->` in Markdown. Pass technical nouns of the subject with
`--allow word1,word2`.

## Be right before you are clear

A clear explanation of a wrong fact is worse than no explanation.

- Verify facts that can drift (versions, dates, limits, prices) before you write them, and add an as-of date.
- Do not copy a fact from an example or reference image without checking it. Examples can be wrong.
- When you explain a document the user gave you (a plan, a diff, an agent's output), every claim must trace to that source: name the section or line. When the source does not say something, write "Not stated in the source". Then check the document against itself (`references/spec-sheet.md`, "Sheets that explain a document"): the gaps it does not name are what the reader most needs. Keep your own assessment visibly separate from what the source says.
- Do not pad. Each panel, sentence and diagram node must answer a question the reader has.

## Tier workflows

- **Tier 1**: write the answer in STE, in chat. Open with the answer to the question, then the detail for each topic the user named. A question with a few named topics usually needs 500 to 1,000 words; count them before you send. Use a vertical list for steps or parallel items; headings name the subject. Lint the draft through stdin. Write a `.md` file as well only when the user asks for one or the answer is a reference they will keep; the chat still carries the full answer.
- **Tier 2**: read `references/diagram.md`. Hand-draw the SVG (no diagram libraries, no CDN scripts) in the sheet's visual language, with STE labels and numbered steps.
- **Tier 3**: read `references/spec-sheet.md`, then copy `assets/spec-sheet-template.html` and replace all its demo content, including the `<title>`. Plan the panels first: one panel for each question the reader has.
- **Tier 4**: read `references/video.md`. Choose the engine (Manim for a 3Blue1Brown look, hyperframes for other styles) and the voice, plan a title card with a one-line intro, the body and a recap card, write the narration and a scene plan, build at a calm pace with burned-in captions and a quiet music bed, and check the render.

## Deliver

- Write the file into the user's current project: `docs/reports/` when it exists, otherwise the project root, with a short descriptive filename. Do not publish it as an Artifact or upload it anywhere.
- Pages are self-contained: CSS, JavaScript and images inline (images as data URIs). The only network request allowed is Google Fonts, with a real fallback font stack. The file must open from `file://`.
- Check every page before you hand it over. Keep the check output out of the project:

  ```bash
  python3 <skill-dir>/scripts/check_page.py <page.html> --out <scratch-dir>/<page>-check
  python3 <skill-dir>/scripts/ste_lint.py <page.html> --mode 80   # or strict
  ```

  `check_page.py` renders at 1440, 1280, 1024, 800 and 390 px and prints to A4. It fails on network requests, overflow, clipped content, annotation labels that collide or sit on text, SVG labels that collide or leave the SVG, `text-wrap: balance|pretty`, `max-width` on text, one-sided accent marks, dashes, emoji, JavaScript errors, and a sheet that needs more than one A4 page. Fix every error, then read the screenshot tiles it lists at full size. A pass does not prove the page is good: look for text that wraps while space remains, dead space, and labels that point at the wrong thing.
- When the user will print or pin the page, ship the PDFs that `check_page.py` writes: copy `print.pdf` to `<slug>.pdf`, and for a spec sheet also `print-a3.pdf` to `<slug>-A3.pdf` (the A3 sheet has readable type on a wall; the A4 one fits a desk printer with small type). Say which is which.

**The chat reply is the answer.** The user reads the chat first and may never
open the file. For every tier:

1. The answer in one or two sentences (the verdict, the difference, the key fact). For a document review, include what the document proposes, the conditions written as checks the user can make ("Confirm that ..."), the questions to ask the author, and a sentence the user can say at their meeting.
2. The few points that support it, in STE.
3. The file path(s), and one line on what the file adds (the diagram, the full risk table).
4. Only then, and only if they change what the user does: assumptions you made, one at most, and the next-tier offer when the offer rule allows it.

Leave out how you worked: linter results, test widths, tool installs, git
state. One short line ("Checked at five widths and in print.") is enough.
When the user asked for an STE level in a longer answer, end with one line on
what you kept and what you relaxed ("80% STE: the grammar rules kept, a few
non-STE words kept for clarity."). Leave it out of a short answer.
When a shape is the point (a curve over time, a sawtooth), put a small inline
text sketch in the tier 1 answer instead of only offering a diagram. For a reference sheet, the reply gives the few rules or facts
the reader will use most, then the paths.
Do not paste a whole page into chat, but never make the user open a file to
get the answer.

- The STE label is for the user who asked for STE. Write in STE always; put "80% ASD-STE100" in a title block or a reply only when the user asked for STE.

## Files in this skill

- `references/ste-writing.md`: STE rules by section, the dial, substitution table, before-and-after examples.
- `references/diagram.md`: tier 2 diagram rules and SVG patterns.
- `references/spec-sheet.md`: tier 3 layout, panel catalogue, document sheets, design rules.
- `references/video.md`: tier 4 structure (title, body, recap), voice and pace, music, captions, scene plan and hyperframes hand-off.
- `assets/spec-sheet-template.html`: a working sheet with every component (demo topic: HTTP caching).
- `scripts/ste_lint.py`, `scripts/check_page.py`: checkers. Both have `--self-test`.
````

## File: skills/legible-explainer/scripts/check_page.py
size: 29064
sha: 1be784c41f6d22c06c1f8df1a645e607071d56fc
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/scripts/check_page.py

```text
#!/usr/bin/env python3
"""Render an explainer page and check it before it goes to the reader.

Opens the HTML file in headless Chromium at five widths (1440, 1280, 1024,
800 and 390 px), takes screenshots, prints the page to A4, and checks:

errors (the page fails)
  - network requests other than Google Fonts, and local files other than the
    page itself (the page must be self-contained)
  - horizontal page overflow, and content that spills out of or is clipped by
    its box (width or height)
  - annotation labels (.ann-label or [data-no-overlap]) that overlap each
    other, sit on top of the annotated text, or run outside their panel
  - SVG <text> labels that overlap each other or run outside their SVG
  - text-wrap: balance or pretty; max-width that narrows running text
  - one-sided accent marks: a coloured single edge on a box (border, pseudo-
    element bar, hard-stop gradient stripe, inset edge shadow)
  - em dashes, spaced en dashes or emoji in visible text (text inside
    data-ste="ignore", code and pre is exempt)
  - JavaScript errors on load
  - printed text smaller than 4.5 pt (A4) or 6.5 pt (A3)
warnings (look at them)
  - a spec sheet that needs more than one printed page; printed text under
    6.5 pt on A4 (ship the A3 PDF for a sheet that will be pinned up)
  - body paragraphs not justified at desktop width, or justified on a phone
  - <br> inside running text
  - a panel with a large empty area at the bottom
  - <title> that does not match the page's <h1>

Usage:
  check_page.py PAGE.html [--out DIR] [--json]
  check_page.py --self-test
Writes DIR/desktop.png (1440, full page), DIR/mobile.png (390, full page),
readable 2x tiles DIR/mobile-01.png ... and, for tall pages, DIR/desktop-01.png
..., DIR/print.pdf (the page's own print size, A4 by default), DIR/print-a3.pdf
(for a spec sheet: <html data-paper="a3">) and DIR/report.json. DIR defaults to a folder in the system
temp directory, so check output never lands in the user's project.
Exit code 0 pass, 1 fail, 2 the page could not be opened.
"""

from __future__ import annotations

import argparse
import json
import re
import sys
import tempfile
from pathlib import Path
from urllib.parse import unquote, urlparse

PROBE_WIDTHS = [1440, 1280, 1024, 800, 390]
ALLOWED_HOSTS = {"fonts.googleapis.com", "fonts.gstatic.com"}
TILE_H = {"desktop": 1100, "mobile": 800}

PAGE_PROBE = r"""
(viewportName) => {
  const errors = [];
  const warnings = [];
  const vw = window.innerWidth;
  const path = (el) => {
    const parts = [];
    while (el && el.nodeType === 1 && parts.length < 4) {
      let s = el.tagName.toLowerCase();
      if (el.id) { s += '#' + el.id; parts.unshift(s); break; }
      if (el.classList.length) s += '.' + [...el.classList].slice(0, 2).join('.');
      parts.unshift(s);
      el = el.parentElement;
    }
    return parts.join(' > ');
  };
  const hits = (a, b, pad = 1) => a.width && b.width && a.left < b.right - pad && b.left < a.right - pad && a.top < b.bottom - pad && b.top < a.bottom - pad;
  const rgb = (c) => { const m = (c || '').match(/[\d.]+/g); return m ? m.map(Number) : [0, 0, 0, 0]; };
  const coloured = (c) => { const [r, g, b, a = 1] = rgb(c); return a > 0.05 && (Math.max(r, g, b) - Math.min(r, g, b)) > 40; };
  const visible = (c) => { const v = rgb(c); return (v.length < 4 || v[3] > 0.05); };

  const docW = document.documentElement.scrollWidth;
  if (docW > vw + 1) errors.push({rule: 'page-overflow', detail: `page is ${docW}px wide in a ${vw}px viewport`});

  const all = [...document.body.querySelectorAll('*')];
  let spills = 0;
  for (const el of all) {
    const tag = el.tagName.toLowerCase();
    if (el.closest('svg') && tag !== 'svg') continue;
    const cs = getComputedStyle(el);
    if (cs.display === 'none' || cs.visibility === 'hidden') continue;
    const scrollsX = ['auto', 'scroll'].includes(cs.overflowX);
    const scrollsY = ['auto', 'scroll'].includes(cs.overflowY);
    const clips = ['hidden', 'clip'].includes(cs.overflowX) || ['hidden', 'clip'].includes(cs.overflowY);
    const isInline = cs.display === 'inline';
    if (!isInline && !['html', 'body'].includes(tag) && el.clientWidth > 0) {
      let overX = !scrollsX && el.scrollWidth > el.clientWidth + 2;
      if (overX && el.querySelector('.ann-label')) {
        // Annotation labels hang outside their segment by design; measure without them.
        const ls = [...el.querySelectorAll('.ann-label')];
        const prev = ls.map(l => l.style.display);
        ls.forEach(l => { l.style.display = 'none'; });
        overX = el.scrollWidth > el.clientWidth + 2;
        ls.forEach((l, i) => { l.style.display = prev[i]; });
      }
      const overY = clips && !scrollsY && el.scrollHeight > el.clientHeight + 2;
      if (overX || overY) {
        if (spills < 15) errors.push({rule: clips ? 'content-clipped' : 'content-spills',
          detail: `${path(el)}: content ${el.scrollWidth}x${el.scrollHeight}px in a ${el.clientWidth}x${el.clientHeight}px box`});
        spills++;
      }
    }
    const tw = cs.textWrap || cs.textWrapStyle || '';
    const pcs = el.parentElement ? getComputedStyle(el.parentElement) : null;
    const ptw = pcs ? (pcs.textWrap || pcs.textWrapStyle || '') : '';
    if (/balance|pretty/.test(tw) && tw !== ptw) errors.push({rule: 'text-wrap', detail: `${path(el)} uses text-wrap: ${tw}`});
    if (['p', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'figcaption', 'dd', 'blockquote'].includes(tag) && cs.maxWidth !== 'none' && cs.maxWidth !== '100%') {
      const parentW = el.parentElement ? el.parentElement.clientWidth : vw;
      if (parseFloat(cs.maxWidth) < parentW - 2) errors.push({rule: 'text-max-width', detail: `${path(el)} has max-width ${cs.maxWidth}`});
    }
    // One-sided accent marks on the element itself.
    const side = (s) => ({w: parseFloat(cs['border' + s + 'Width']) * (cs['border' + s + 'Style'] === 'none' ? 0 : 1), c: cs['border' + s + 'Color']});
    const S = {Left: side('Left'), Right: side('Right'), Top: side('Top'), Bottom: side('Bottom')};
    const opp = {Left: 'Right', Right: 'Left', Top: 'Bottom', Bottom: 'Top'};
    const present = Object.keys(S).filter(k => S[k].w > 0 && visible(S[k].c));
    const minW = Math.min(S.Top.w, S.Bottom.w, S.Left.w, S.Right.w);
    for (const k of ['Left', 'Right', 'Top', 'Bottom']) {
      const a = S[k], b = S[opp[k]];
      if (!(a.w > 0 && visible(a.c))) continue;
      const thickAccent = a.w >= 2 && a.w - b.w >= 1 && a.w > minW + 0.5;
      const onlySide = present.length === 1 && (coloured(a.c) || a.w >= 2);
      const lrColour = (k === 'Left' || k === 'Right') && coloured(a.c) && (b.w === 0 || !visible(b.c) || b.c !== a.c);
      if (thickAccent || onlySide || lrColour) {
        errors.push({rule: 'one-sided-border', detail: `${path(el)} border ${k.toLowerCase()} ${a.w}px ${a.c} (L${S.Left.w} R${S.Right.w} T${S.Top.w} B${S.Bottom.w})`});
        break;
      }
    }
    if (cs.boxShadow && /inset/.test(cs.boxShadow)) {
      for (const m of cs.boxShadow.matchAll(/(-?\d+(?:\.\d+)?)px (-?\d+(?:\.\d+)?)px 0px(?: 0px)? inset|inset[^,]*?(-?\d+(?:\.\d+)?)px (-?\d+(?:\.\d+)?)px 0px/g)) {
        const x = parseFloat(m[1] ?? m[3]), y = parseFloat(m[2] ?? m[4]);
        if ((x !== 0) !== (y !== 0)) { errors.push({rule: 'inset-edge-shadow', detail: `${path(el)} box-shadow ${cs.boxShadow}`}); break; }
      }
    }
    if (/linear-gradient/.test(cs.backgroundImage) && /(\d+(?:\.\d+)?)px,\s*(?:transparent|rgba\([^)]*,\s*0\))\s+\1px/.test(cs.backgroundImage) && el.innerText && el.innerText.trim().length > 20) {
      errors.push({rule: 'gradient-stripe', detail: `${path(el)} background ${cs.backgroundImage.slice(0, 80)}`});
    }
    // Pseudo-element bars flush on one edge of a box that holds text.
    const r = el.getBoundingClientRect();
    if (r.height > 24 && el.innerText && el.innerText.trim().length > 20) {
      for (const pseudo of ['::before', '::after']) {
        const ps = getComputedStyle(el, pseudo);
        if (!ps || ps.content === 'none' || ps.content === 'normal' || ps.position !== 'absolute') continue;
        const pw = parseFloat(ps.width) || 0, ph = parseFloat(ps.height) || 0;
        const bg = coloured(ps.backgroundColor);
        const bl = parseFloat(ps.borderLeftWidth) > 0 && coloured(ps.borderLeftColor) && !(parseFloat(ps.borderRightWidth) > 0);
        if (((bg && pw > 0 && pw <= 6) || bl) && ph >= r.height * 0.6) {
          errors.push({rule: 'one-sided-border', detail: `${path(el)}${pseudo} is a ${pw}px coloured bar along one edge`});
        }
      }
    }
  }
  if (spills > 15) errors.push({rule: 'content-spills', detail: `${spills - 15} more elements spill`});

  // Annotation labels.
  const labels = [...document.querySelectorAll('.ann-label, [data-no-overlap]')].filter(el => getComputedStyle(el).display !== 'none')
    .map(el => ({el, r: el.getBoundingClientRect()}));
  for (let i = 0; i < labels.length; i++) for (let j = i + 1; j < labels.length; j++) {
    if (hits(labels[i].r, labels[j].r)) errors.push({rule: 'labels-overlap', detail: `"${labels[i].el.textContent.trim().slice(0, 40)}" overlaps "${labels[j].el.textContent.trim().slice(0, 40)}"`});
  }
  for (const {el, r} of labels) {
    const panel = el.closest('.panel') || document.body;
    const pr = panel.getBoundingClientRect();
    if (r.width && (r.left < pr.left - 1 || r.right > pr.right + 1 || r.bottom > pr.bottom + 1)) errors.push({rule: 'label-outside-panel', detail: `"${el.textContent.trim().slice(0, 40)}" runs outside its panel`});
    const line = el.closest('.ann-line');
    if (!line) continue;
    const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT);
    let node, found = false;
    while (!found && (node = walker.nextNode())) {
      if (!node.textContent.trim() || node.parentElement.closest('.ann-label')) continue;
      const range = document.createRange(); range.selectNodeContents(node);
      for (const tr of range.getClientRects()) {
        if (hits(r, tr, 2)) { errors.push({rule: 'label-on-text', detail: `"${el.textContent.trim().slice(0, 40)}" sits on "${node.textContent.trim().slice(0, 30)}"`}); found = true; break; }
      }
    }
  }

  // SVG text.
  for (const svg of document.querySelectorAll('svg')) {
    const sr = svg.getBoundingClientRect();
    if (!sr.width) continue;
    // Compare the letters, not the font's line cell: on Linux a bold face can report a cell
    // 1.6 em tall, so stacked lines that do not touch would count as an overlap.
    const inkBox = el => {
      const r = el.getBoundingClientRect();
      try {
        const n = el.getNumberOfChars(), ctm = el.getScreenCTM();
        if (!n || !ctm || Math.abs(ctm.b) > 1e-6 || Math.abs(ctm.c) > 1e-6) return r;
        const fs = Math.max(...[el, ...el.querySelectorAll('tspan')].map(e => parseFloat(getComputedStyle(e).fontSize) || 0)) * Math.abs(ctm.d);
        const y = p => new DOMPoint(p.x, p.y).matrixTransform(ctm).y;
        const top = Math.max(r.top, y(el.getStartPositionOfChar(0)) - 0.8 * fs);
        const bottom = Math.min(r.bottom, y(el.getStartPositionOfChar(n - 1)) + 0.25 * fs);
        return bottom > top ? {left: r.left, right: r.right, top, bottom, width: r.width, height: bottom - top} : r;
      } catch (e) { return r; }
    };
    const texts = [...svg.querySelectorAll('text')].map(el => ({el, r: inkBox(el)})).filter(t => t.r.width > 0);
    let n = 0;
    for (let i = 0; i < texts.length && n < 10; i++) for (let j = i + 1; j < texts.length && n < 10; j++) {
      if (hits(texts[i].r, texts[j].r)) {
        errors.push({rule: 'svg-text-overlap', detail: `"${texts[i].el.textContent.trim().slice(0, 30)}" overlaps "${texts[j].el.textContent.trim().slice(0, 30)}"`});
        n++;
      }
    }
    if (vw === 1440 && sr.width > 300) {
      const ctm = svg.getScreenCTM ? svg.getScreenCTM() : null;
      const scale = ctm ? Math.hypot(ctm.a, ctm.b) : 1;
      const small = texts.filter(t => (t.el.textContent || '').trim().length > 1 && parseFloat(getComputedStyle(t.el).fontSize) * scale < 11.5);
      if (small.length) warnings.push({rule: 'svg-text-small', detail: `${small.length} SVG labels render under about 12 px at 1440 px, for example "${small[0].el.textContent.trim().slice(0, 30)}"`});
    }
    for (const t of texts) {
      if (t.r.left < sr.left - 2 || t.r.right > sr.right + 2 || t.r.top < sr.top - 2 || t.r.bottom > sr.bottom + 2)
        errors.push({rule: 'svg-text-clipped', detail: `"${t.el.textContent.trim().slice(0, 30)}" runs outside its SVG`});
    }
  }

  // Visible text, without quoted non-STE text and code.
  const parts = [];
  const tw2 = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
  let tn;
  while ((tn = tw2.nextNode())) {
    const p = tn.parentElement;
    if (!p || p.closest('[data-ste="ignore"], code, pre, kbd, samp, script, style')) continue;
    if (getComputedStyle(p).display === 'none') continue;
    parts.push(tn.textContent);
  }
  const text = parts.join(' ');
  const dashes = (text.match(/—| – /g) || []).length;
  if (dashes) errors.push({rule: 'dash', detail: `${dashes} em dash or spaced en dash in visible text`});
  const emoji = text.match(/[\p{Emoji_Presentation}�{1F000}-�{1FAFF}]/gu);
  if (emoji) errors.push({rule: 'emoji', detail: `emoji in visible text: ${[...new Set(emoji)].join(' ')}`});

  const paras = [...document.querySelectorAll('p')].filter(p => {
    const r = p.getBoundingClientRect();
    const lh = parseFloat(getComputedStyle(p).lineHeight) || 18;
    return r.height > lh * 2.5 && p.innerText.length > 120;
  });
  const justified = paras.filter(p => getComputedStyle(p).textAlign === 'justify').length;
  if (vw >= 1024 && paras.length && justified < paras.length) {
    warnings.push({rule: 'not-justified', detail: `${paras.length - justified} of ${paras.length} multi-line paragraphs are not justified`});
  }
  if (vw < 680 && justified) warnings.push({rule: 'justified-on-phone', detail: `${justified} paragraphs stay justified at ${vw}px`});
  const brs = [...document.querySelectorAll('p br, li br')].length;
  if (brs) warnings.push({rule: 'br-in-text', detail: `${brs} <br> inside p or li`});
  for (const panel of document.querySelectorAll('.panel')) {
    const pr = panel.getBoundingClientRect();
    // Content bottom: the lowest visible text, image or SVG in the panel, whatever its markup.
    let bottom = pr.top;
    const walker = document.createTreeWalker(panel, NodeFilter.SHOW_TEXT);
    let tnode;
    while ((tnode = walker.nextNode())) {
      if (!tnode.textContent.trim() || !tnode.parentElement || getComputedStyle(tnode.parentElement).display === 'none') continue;
      const range = document.createRange(); range.selectNodeContents(tnode);
      for (const rr of range.getClientRects()) bottom = Math.max(bottom, rr.bottom);
    }
    for (const media of panel.querySelectorAll('img, svg, canvas, video, .gauge-track, .timeline .node, table')) {
      const mr = media.getBoundingClientRect(); if (mr.height) bottom = Math.max(bottom, mr.bottom);
    }
    const gap = pr.bottom - bottom - 12;
    if (pr.height > 200 && gap > Math.max(70, pr.height * 0.15)) {
      const item = {rule: 'dead-space', detail: `${path(panel)}: ${Math.round(gap)}px empty at the bottom of a ${Math.round(pr.height)}px panel`};
      if (vw === 1440 && gap > Math.max(150, pr.height * 0.25)) errors.push(item); else warnings.push(item);
    }
  }
  const h1 = document.querySelector('h1');
  if (h1 && document.title.trim() !== h1.innerText.trim()) warnings.push({rule: 'title-mismatch', detail: `<title> "${document.title}" differs from <h1> "${h1.innerText.trim()}"`});

  return {errors, warnings, width: vw, height: document.documentElement.scrollHeight, isSheet: !!document.querySelector('.sheet'),
          words: (text.match(/[A-Za-z0-9'’]+/g) || []).length,
          fonts: [...document.fonts].filter(f => f.status === 'loaded').map(f => f.family).filter((v, i, a) => a.indexOf(v) === i)};
}
"""

PRINT_PROBE = r"""
() => {
  const sizes = [];
  const tw = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
  let n;
  while ((n = tw.nextNode())) {
    const t = n.textContent.trim();
    const el = n.parentElement;
    if (t.length < 2 || !el || el.closest('svg, script, style, [aria-hidden="true"]')) continue;
    const cs = getComputedStyle(el);
    if (cs.display === 'none' || cs.visibility === 'hidden') continue;
    const zoom = el.currentCSSZoom || 1;
    sizes.push({pt: parseFloat(cs.fontSize) * zoom * 0.75, text: t.slice(0, 30), tag: el.tagName.toLowerCase() + (el.className ? '.' + String(el.className).split(' ')[0] : '')});
  }
  sizes.sort((a, b) => a.pt - b.pt);
  const body = [...document.querySelectorAll('p, li, td')].map(el => parseFloat(getComputedStyle(el).fontSize) * (el.currentCSSZoom || 1) * 0.75).sort((a, b) => a - b);
  return {min: sizes.length ? sizes[0] : null, p10: sizes.length ? sizes[Math.floor(sizes.length * 0.1)].pt : null,
          bodyMedian: body.length ? body[Math.floor(body.length / 2)] : null};
}
"""

def _pdf_pages(data: bytes) -> int:
    return len(re.findall(rb"/Type\s*/Page(?!s)", data))

def check(page: Path, out: Path) -> dict:
    from playwright.sync_api import sync_playwright

    page = page.resolve()
    if not page.is_file():
        raise FileNotFoundError(f"no such page: {page}")
    out.mkdir(parents=True, exist_ok=True)
    report: dict = {"page": str(page), "out": str(out), "passed": True, "errors": [], "warnings": [], "viewports": {}, "tiles": []}
    blocked: list[str] = []
    js_errors: list[str] = []
    page_uri = page.as_uri()

    def route(r):
        url = r.request.url
        u = urlparse(url)
        if u.scheme in {"data", "blob", "about"}:
            return r.continue_()
        if u.scheme == "file":
            if url.split("#")[0] == page_uri or Path(unquote(u.path)).resolve() == page:
                return r.continue_()
            blocked.append(url)
            return r.abort()
        if u.hostname in ALLOWED_HOSTS:
            return r.continue_()
        blocked.append(url)
        return r.abort()

    seen: set[tuple[str, str]] = set()

    def add(kind: str, item: dict, vp: str) -> None:
        key = (item["rule"], item["detail"])
        if key in seen:
            return
        seen.add(key)
        report[kind].append({**item, "viewport": vp})

    with sync_playwright() as p:
        try:
            browser = p.chromium.launch()
        except Exception:
            browser = p.chromium.launch(channel="chrome")
        is_sheet = False
        for w in PROBE_WIDTHS:
            name = {1440: "desktop", 390: "mobile"}.get(w, f"{w}px")
            scale = 2 if name == "mobile" else 1
            ctx = browser.new_context(viewport={"width": w, "height": 900 if w > 600 else 844}, device_scale_factor=scale)
            tab = ctx.new_page()
            tab.on("pageerror", lambda e: js_errors.append(str(e)))
            tab.route("**/*", route)
            tab.goto(page_uri, wait_until="load")
            try:
                tab.evaluate("document.fonts.ready.then(() => true)")
            except Exception:
                pass
            tab.wait_for_timeout(400)
            result = tab.evaluate(PAGE_PROBE, name)
            is_sheet = is_sheet or result["isSheet"]
            for e in result["errors"]:
                add("errors", e, name)
            for wn in result["warnings"]:
                add("warnings", wn, name)
            info = {"width": result["width"], "height": result["height"], "fonts": result["fonts"], "words": result["words"]}
            if name in {"desktop", "mobile"}:
                shot = out / f"{name}.png"
                tab.screenshot(path=str(shot), full_page=True, scale="css")
                info["screenshot"] = str(shot)
                th = TILE_H[name]
                if name == "mobile" or result["height"] > 1500:
                    for i, y in enumerate(range(0, result["height"], th), start=1):
                        tile = out / f"{name}-{i:02d}.png"
                        tab.screenshot(path=str(tile), full_page=True,
                                       clip={"x": 0, "y": y, "width": w, "height": min(th, result["height"] - y)})
                        report["tiles"].append(str(tile))
            report["viewports"][name] = info
            if name == "desktop":
                tab.emulate_media(media="print")
                tab.evaluate("window.dispatchEvent(new Event('beforeprint'))")
                report["print"] = {}
                papers = [("default", "print.pdf")] + ([("a3", "print-a3.pdf")] if is_sheet else [])
                for paper, fname in papers:
                    if paper == "a3":
                        tab.evaluate("document.documentElement.dataset.paper = 'a3'; window.dispatchEvent(new Event('beforeprint'))")
                    sizes = tab.evaluate(PRINT_PROBE)
                    pdf = out / fname
                    data = tab.pdf(path=str(pdf), prefer_css_page_size=True, print_background=False)
                    pages = _pdf_pages(data)
                    box = re.search(rb"/MediaBox\s*\[\s*[\d.]+\s+[\d.]+\s+([\d.]+)\s+([\d.]+)", data)
                    w_pt = float(box.group(1)) if box else 0
                    label = "A3" if max(w_pt, float(box.group(2)) if box else 0) > 1100 else "A4"
                    entry = {"pdf": str(pdf), "pages": pages, "paper": label,
                             "min_pt": round(sizes["min"]["pt"], 1) if sizes["min"] else None,
                             "p10_pt": round(sizes["p10"], 1) if sizes["p10"] else None,
                             "body_pt": round(sizes["bodyMedian"], 1) if sizes["bodyMedian"] else None}
                    report["print"][paper] = entry
                    floor = 6.5 if label == "A3" else 4.5
                    if sizes["min"] and sizes["min"]["pt"] < floor:
                        add("errors", {"rule": "print-type", "detail": f"{label}: text at {sizes['min']['pt']:.1f} pt ({sizes['min']['tag']} \"{sizes['min']['text']}\"), the floor is {floor} pt"}, "print")
                    elif label == "A4" and is_sheet and sizes["p10"] and sizes["p10"] < 6.5:
                        add("warnings", {"rule": "print-type", "detail": f"A4: a tenth of the text is under {sizes['p10']:.1f} pt; for a sheet that will be pinned up, ship the A3 PDF"}, "print")
                    if is_sheet and pages > 1:
                        add("warnings", {"rule": "print-pages", "detail": f"{label}: the sheet prints on {pages} pages; a drawing sheet reads best on 1"}, "print")
            ctx.close()
        browser.close()

    for url in sorted(set(blocked)):
        add("errors", {"rule": "not-self-contained", "detail": f"blocked request: {url}"}, "all")
    for msg in sorted(set(js_errors)):
        add("errors", {"rule": "js-error", "detail": msg}, "all")
    report["passed"] = not report["errors"]
    (out / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
    return report

def print_report(report: dict) -> None:
    print(("PASS" if report["passed"] else "FAIL") + "  " + report["page"])
    for name, v in report["viewports"].items():
        shot = f"  screenshot {v['screenshot']}" if "screenshot" in v else ""
        print(f"  {name}: {v['width']}x{v['height']}{shot}  fonts {', '.join(v['fonts']) or 'none loaded'}")
    if "desktop" in report["viewports"]:
        print(f"  visible words: {report['viewports']['desktop']['words']} (a review of a document should stay under the document's own length)")
    for paper, p in report.get("print", {}).items():
        print(f"  print {p['paper']}: {p['pages']} page(s), body {p['body_pt']} pt, smallest {p['min_pt']} pt  {p['pdf']}")
    for e in report["errors"]:
        print(f"  [error] {e['rule']} ({e['viewport']}): {e['detail']}")
    for wn in report["warnings"]:
        print(f"  [warning] {wn['rule']} ({wn['viewport']}): {wn['detail']}")
    if report["tiles"]:
        print("  Read these tiles at full size, then the desktop screenshot:")
        for t in report["tiles"]:
            print(f"    {t}")
    else:
        print("  Look at both screenshots at full size before you hand over the page.")

GOOD = """<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Good page</title><style>body{margin:0;padding:16px;font:16px/1.5 system-ui} p{text-align:justify;hyphens:auto;max-width:100%}
@media (max-width:680px){p{text-align:left;hyphens:manual}} .box{border:1px solid #000;padding:8px}</style></head>
<body><div class="box"><h1>Good page</h1><p>The pump supplies fuel to the engine when the switch is on. The pump stops when the
switch is off. This paragraph is long enough to wrap onto more than two lines at the phone width and at the desktop width.</p>
<blockquote data-ste="ignore">Original: the plan — as written — is fine.</blockquote><p>Source: © IETF 2022, Plex™.</p>
<svg width="300" height="70" viewBox="0 0 300 70" style="font:13px monospace"><text x="8" y="20"><tspan font-weight="700">code_verifier</tspan> = random</text>
<text x="8" y="39"><tspan font-weight="700">code_challenge</tspan> =</text><text x="8" y="58">  BASE64URL(SHA256(v))</text></svg></div></body></html>"""

BAD = """<!doctype html><html><head><meta charset="utf-8"><script src="https://cdn.example.com/x.js"></script>
<style>p{max-width:60ch;text-wrap:balance} .bar{border-left:4px solid red;padding:4px} .wide{width:2000px}
.top{border-top:4px solid blue;padding:8px} .thin{border-left:1px solid #1f5fbf;padding:8px}
.ps{position:relative;padding:8px 8px 8px 14px} .ps::before{content:"";position:absolute;left:0;top:0;bottom:0;width:4px;background:#1f5fbf}
.clip{width:80px;height:20px;overflow:hidden;display:inline-block}</style></head>
<body><p class="bar">Fast — most of the time \U0001F680</p>
<div class="top">A card with a coloured top edge only, long enough to count.</div>
<div class="thin">A card with a thin coloured left edge, long enough to count.</div>
<div class="ps">A card with a pseudo-element bar on the left edge, long enough.</div>
<span class="clip">Important instruction that is clipped</span>
<svg width="300" height="60" viewBox="0 0 300 60"><text x="10" y="30">First label here</text><text x="20" y="32">Second label</text><text x="10" y="100">Lost label</text></svg>
<svg width="300" height="60" viewBox="0 0 300 60" style="font:14px monospace"><text x="8" y="24">Upper line</text><text x="8" y="32">Lower line</text></svg>
<div class="wide">wide</div><img src="local.png"></body></html>"""

def self_test() -> int:
    failures = 0
    with tempfile.TemporaryDirectory() as tmp:
        tmp_path = Path(tmp) / "dir with space"
        tmp_path.mkdir()
        good = tmp_path / "good.html"
        good.write_text(GOOD, encoding="utf-8")
        bad = tmp_path / "bad.html"
        bad.write_text(BAD, encoding="utf-8")
        r = check(good, tmp_path / "good-check")
        if not r["passed"]:
            failures += 1
            print("good page FAILED:", r["errors"])
        r = check(bad, tmp_path / "bad-check")
        rules = {e["rule"] for e in r["errors"]}
        details = " ".join(e["detail"] for e in r["errors"])
        want = {"not-self-contained", "text-wrap", "text-max-width", "one-sided-border", "dash", "emoji", "page-overflow",
                "svg-text-overlap", "svg-text-clipped", "content-clipped"}
        if r["passed"] or not want <= rules:
            failures += 1
            print("bad page FAILED: missing", sorted(want - rules), "got", sorted(rules))
        for needle in ["div.top", "div.thin", "div.ps::before", '"Upper line" overlaps "Lower line"']:
            if needle not in details:
                failures += 1
                print("bad page FAILED: no finding for", needle)
    print("self-test:", "OK" if not failures else f"{failures} failure(s)")
    return 1 if failures else 0

def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("page", nargs="?")
    ap.add_argument("--out", help="folder for screenshots, print.pdf and report.json")
    ap.add_argument("--json", action="store_true")
    ap.add_argument("--self-test", action="store_true")
    args = ap.parse_args(argv)
    if args.self_test:
        return self_test()
    if not args.page:
        ap.print_usage()
        return 2
    page = Path(args.page)
    out = Path(args.out) if args.out else Path(tempfile.gettempdir()) / "legible-check" / page.stem
    try:
        report = check(page, out)
    except Exception as e:  # the page could not be opened or rendered
        print(f"cannot check {page}: {e}", file=sys.stderr)
        return 2
    if args.json:
        print(json.dumps(report, indent=2))
    else:
        print_report(report)
    return 0 if report["passed"] else 1

if __name__ == "__main__":
    sys.exit(main())
```

## File: skills/legible-explainer/scripts/ste_lint.py
size: 36950
sha: 3ef5b2bea949e30e25851e8fab9847c82226d81b
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/scripts/ste_lint.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/scripts/ste_lint.py

## File: skills/legible-explainer/references/diagram.md
size: 7075
sha: ef4cdd5123d5d7bfe99d72c977a62897af4148ec
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/references/diagram.md

````text
# Tier 2: diagrams

Use a diagram when the reader must see a shape: an order of steps, who talks
to whom, what contains what, which state follows which. A diagram that only
restates a list in boxes adds nothing; use a list instead.

## Pick the diagram kind

| The content is | Draw | Layout |
|---|---|---|
| Messages between parties over time (OAuth, TCP handshake, an API call chain) | Sequence diagram | One vertical lifeline for each party, time runs down, numbered arrows |
| Steps with decisions (a deploy pipeline, a support triage) | Flowchart | Top to bottom or left to right, diamonds only for real decisions |
| States and the events that move between them (a TCP connection, an order) | State diagram | States as boxes, events as arrow labels, start and end marks |
| Parts inside parts (a system, a document, a team) | Tree or nested boxes | Root at the top, siblings aligned |
| Data moving through components (a request through a CDN, a cache, an origin) | Data-flow or architecture | Components in columns by tier, arrows labelled with what moves |

## Deliverable

One `.html` file that holds the diagram as inline SVG, in the drawing-sheet
visual language: copy `assets/spec-sheet-template.html`, keep its font links,
`<style>` block, frame and title block, and delete the demo panels. The
diagram comes first and gets the full width: one `span-12` panel at the top,
with the numbered steps, tables and notes in panels below it. For a working
diagram (kept open while the user debugs or builds), use `<div class="frame
plain">` to drop the zone margins, so every pixel goes to the diagram; keep
the zone frame for a reference sheet. A working diagram that the user keeps
open must show the whole flow on one 1080p screen: tighten the row spacing,
or add a compact toggle that keeps every step and its key values. A visible
marker for each step (which steps show in the browser's DevTools and which
only in server logs) helps the user debug. A working diagram is for the screen:
write "Screen" in the title block's Sheet field and ship no PDF unless the user
asks to print it; `check_page.py` warns about print pages that do not matter
here. Fill the title block as in
`references/spec-sheet.md` step 5 (title, source, "Facts as of", language,
sheet number) and set `<title>` to the same title. A standalone `.svg` is fine
when the user asks for one, but then the fonts fall back to the system stack.

Hand-draw the SVG. Do not load Mermaid, D3 or any script from a CDN: the page
must work from `file://` with Google Fonts as its only request. When the user
says they will edit the diagram later, offer an Excalidraw scene through the
`excalidraw-diagrams` skill as well.

## SVG rules

- Use a `viewBox` and `width="100%"`; set no fixed pixel height. Draw at the size it will show on a desktop panel (about 900 to 1300 units wide), so 1 unit is about 1 px and 13-unit text reads at 13 px.
- Text at 13 units or more for labels and 12 for parameter lines, as rendered at desktop width: `var(--sans)` for labels, `var(--mono)` for code, headers and field names. A diagram read from a second monitor needs 14 or more.
- Show the values the user tracks on the arrows in the default view (for an auth flow: state, code_challenge, code_verifier, the token). Do not hide them behind a toggle or a click.
- Colours from the sheet tokens through CSS classes inside the SVG, so dark mode still works: ink for structure, blue for the normal path and annotations, red only for an error path or a "do not" item.
- Arrowheads: one `<marker>` whose path uses `fill="context-stroke"`, so each arrowhead takes the colour of its own line. (A marker filled with `currentColor` takes the colour of the SVG, not of the line, and gives black heads on blue lines.)
- Straight or orthogonal lines; no curves unless the curve carries meaning.
- Number the steps of a sequence or flow (1, 2, 3 in small circles or as a prefix in the label) and use the same numbers in the steps list beside the diagram.
- Label every arrow with what moves or what happens, in STE: "Sends code_challenge" says what the step does. Names of fields, headers and parameters stay as they are, in mono.
- Keep 24 or more units between parallel arrows and between a label and the next line. No label crosses a line. No two labels touch.
- Give the SVG `role="img"` and a `<title>` that says what the diagram shows.

## Phone width

An SVG scales down with its panel. A wide sequence diagram at 390 px becomes
unreadable text. Choose one:

- wrap the SVG in `<div class="table-wrap">` and give the SVG a `min-width` (for example 760 px) so it scrolls sideways inside the panel and the page does not, and add a mono caption "Scroll sideways to see all parties", or
- draw a second, vertical version for small screens and switch between them with a media query.

The numbered steps list beside the diagram carries the meaning on any screen
and for a screen reader.

## Sequence diagram pattern

```html
<svg viewBox="0 0 1000 560" width="100%" role="img" aria-labelledby="seq-t" class="diagram">
  <title id="seq-t">Authorization code flow with PKCE</title>
  <defs>
    <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
      <path d="M0 0 L10 5 L0 10 z" fill="context-stroke"/>
    </marker>
  </defs>
  <!-- parties: header box + dashed lifeline -->
  <g class="party">
    <rect x="40" y="20" width="180" height="40"/>
    <text x="130" y="45" text-anchor="middle">Browser</text>
    <line x1="130" y1="60" x2="130" y2="540" class="lifeline"/>
  </g>
  <!-- one message: numbered, labelled arrow -->
  <g class="msg">
    <line x1="130" y1="110" x2="480" y2="110" marker-end="url(#arrow)"/>
    <text x="140" y="102"><tspan class="n">1</tspan> Sends code_challenge</text>
  </g>
  <g class="msg bad">
    <line x1="480" y1="160" x2="130" y2="160" marker-end="url(#arrow)"/>
    <text x="140" y="152"><tspan class="n">2</tspan> Returns an error when the state does not agree</text>
  </g>
</svg>
```

```css
.diagram { font: 13px var(--sans); }
.diagram rect { fill: var(--paper); stroke: var(--ink); stroke-width: 1.5; }
.diagram text { fill: var(--ink); }
.diagram .lifeline { stroke: var(--muted); stroke-dasharray: 4 4; }
.diagram .msg line { stroke: var(--blue); stroke-width: 1.5; }
.diagram .msg.bad line { stroke: var(--red); }
.diagram .n { font-weight: 600; fill: var(--blue); }
.diagram .bad .n { fill: var(--red); }
```

For a flowchart or a state diagram, use the same pieces: boxes as `rect`
with the panel stroke, a decision as a `polygon` diamond, start and end as a
filled and a ringed `circle`, and labelled arrows with the same marker.

## Check

Run both checkers (`references/spec-sheet.md`, "Final check"). `check_page.py`
fails on SVG labels that overlap each other or leave the SVG, and
`ste_lint.py` reads the SVG `<text>` elements. Then read the desktop
screenshot at full size: every arrow points the right way, the numbers run in
order, every arrowhead has the colour of its line, and no label touches a
line.
````

## File: skills/legible-explainer/references/spec-sheet.md
size: 13057
sha: d3a4e93c1e866b0f0ba92a266a9cd6b022a5f332
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/references/spec-sheet.md

````text
# Tier 3: the spec-sheet page

A spec sheet is one dense page that shows a subject from several sides at
once, laid out like an engineering drawing: a frame with zone references
(1 to 8 across, A to D down), lettered panels, and a title block at the bottom
right. The reader scans it, finds the panel they need, and reads only that.
`assets/spec-sheet-template.html` is a working example with every component.

## Contents

- Workflow
- Plan the panels
- Panel catalogue
- Layout
- Visual language
- House design rules
- Sheets that explain a document
- Final check

## Workflow

1. **Collect the facts.** Verify them first, from the source the user gave, the repository, or a current primary source. Write down what each panel will claim and where the claim comes from.
2. **Plan the panels** (next section). Write the plan as a short list: letter, title, the question it answers, component, span.
3. **Copy the template** to the output path. Keep the font links, the whole `<style>` block, the icon sprite, the frame and the `<script>` at the end (it makes annotated lines safe at every width). Delete every demo panel and all demo text (HTTP caching).
4. **Build the panels** from the catalogue. Write all prose in STE (`references/ste-writing.md`).
5. **Fill the title block**: Title (also the page `<title>`), the main source or standard, owner, scope, "Facts as of" with the date you checked the facts, revision, source location, "Sheet 1 of 1". Add a "Language: 80% ASD-STE100" cell only when the user asked for STE. Use fields that are true for the subject; rename keys if you must, but keep "Facts as of".
6. **Check** with both scripts and read the screenshots (end of this file).

## Plan the panels

Use one panel for each real question the reader has about the subject,
usually 3 to 8. A narrow subject can be 1 or 2 panels plus the title block.
If you find fewer than 3 questions, ask yourself if a diagram (tier 2) is the
better answer. Never invent a panel to fill the grid: padding is where
unchecked facts get in. Good questions, by kind:

- What are its parts, and how do they fit together? (structure tree)
- What does one real example look like, piece by piece? (annotated line)
- Which options are allowed, and which are not? (status table)
- What does each term or option mean, and what do people get wrong? (dictionary table)
- What are the limits, sizes or thresholds? (gauges)
- How did it change over time, or what are the phases? (timeline)
- What must I do, step by step? (procedure)
- What must I always or never do? (rule list)
- What could go wrong? (risk table with severity chips, WARNING and CAUTION callouts)

Order the panels in reading order: A at the top left, then across the row,
then the next row. Panel A answers the user's question when the question has
a short answer (a verdict, a recommendation, "the main difference is ..."):
it is the first thing read on a desktop and the first panel on a phone. The
most important explanatory panel comes next and gets the largest span. Each panel has a meta label at the top right that names its
source or its kind ("RFC 9111 section 5.2", "annotated examples", "plan.md
section 4", "assessment, not in the source").

## Panel catalogue

All class names are in the template's `<style>` block.

| Component | Markup | Use it for |
|---|---|---|
| Panel | `section.panel.span-N` > `.panel-head` (`.panel-id`, `h2.panel-title`, `.panel-meta`) + `.panel-body` + optional `hr.hair.flush` and `.panel-note` | Every panel. The note holds a definition or a short remark. |
| Structure tree | `.tree` > `.tree-root`, `.tree-stem`, `.tree-branches[style="--n:K"]` > `.tree-branch` > `.tree-node` + `ul.tree-list` (`.k` key, `small` remark) | Parts of a system, sections of a document, a hierarchy of 2 to 4 branches. |
| Callout | `.callout`, optional `small`; `.callout.warning` (red outline and tint), `.callout.caution` (ink outline) | One fact the reader must not miss. A WARNING or CAUTION callout starts with a `.sev` chip, then the command, then the risk. |
| Severity chip | `span.sev.warning`, `.sev.caution`, `.sev.note` | Risk tables and callouts. |
| Annotated line | `.ann-block` > `.sub` + optional `.ann-wrap` > `.measure` + `.ann-line`. Each annotated piece is `span.seg` > `.t` (the annotated text: a `code` or a `span`) + `span.ann-label` (options `.lane-2`, `.start`, `.end`); `.seg.bad` for a wrong part; separators between segments get `.sep` | A header, a command, a config line or a sentence, explained piece by piece. `.measure` above it gives a length ("13 words, limit 20"). |
| Status table | `table.sheet-table` inside `.table-wrap`; status cells `.status.ok` / `.status.no` with the `#i-ok` / `#i-no` icons; `.d` for a second line in a cell | Allowed and not allowed, supported and not supported, pass and fail. |
| Dictionary table | Same table with `.stack-sm` and `data-label="<column>"` on every `td`, so rows become cards on a phone; columns such as Term, Status, Meaning, Example, Do not write (red cells with `.red`) | Terms, options or words with meaning and misuse. Use `.stack-sm` for any table of 3 or more columns. |
| Gauges | `.gauges` > `.gauge[style="--value:V; --max:M"]` (`.gauge-head` with `.v`, `.gauge-track` > `.gauge-fill`, `.gauge-ticks`), `.gauge.bad` for a value over its limit | Limits, sizes, thresholds, a worked calculation. Give gauges that share a scale the same ticks. |
| Procedure | `ol.procedure` > `li`, introduced by a `.sub` line ending in a colon | Steps in order, one instruction in each step. |
| Rule list | `ul.rules` | Short imperative rules, one in each item. |
| Timeline | `ol.timeline[style="--n:K"]` > `li` (`.year`, `.node`, `.what`) | History, phases, a rollout plan. Keep each caption under about 8 words. |
| Title block | `.titleblock` > `.tb.tb-title` (with the page `h1`) and `.tb` cells (`.k`, `.v`); `.tb-wide` for a long value, `.tb-3` + `.tb-1` for a long value next to a short one | Always, at the bottom right (last item of the last row). |

**Annotated lines at every width.** The script at the end of the template
looks at each `.ann-line` after the fonts load, on resize and before print.
When the segments wrap onto a second line, a label leaves its panel, or labels
collide, it switches that line to legend mode: numbered brackets on the line
and the labels as a numbered list under it. So you do not need to measure; you
do need to keep the script, the `.seg > .t` markup, and short labels (about 6
words). A full sentence anatomy reads best in a `span-7` or wider panel, where
it stays inline at desktop width.

You can add a component that the subject needs (a small inline SVG diagram in
a panel, a matrix, a before-and-after pair). Build it from the same tokens,
1 px and 1.5 px ink lines, and the same type scale.

## Layout

- The panel grid has 12 columns. Use `span-3` to `span-12`. Each row should add up to 12.
- To put two items in one column (the template stacks History on the title block), wrap them in `div.stack.span-N`. Keep the title block in the last item of the grid.
- At 1180 px and below, `span-3` to `span-5` become half width and wider spans become full width; the grid fills gaps (`row dense`) and the last stack stays at the right. At 760 px and below every panel is full width. Check the 1024 and 800 px results in the report, not only the desktop screenshot.
- Balance each row: panels in a row stretch to the same height, so a panel with little content leaves dead space (`check_page.py` fails a panel at 1440 px with more than about a quarter empty). Change spans, move a component, or merge two small panels. Add content only when it answers a real question. Widen a table column rather than let short cells wrap onto two lines.
- Print: the template prints the whole sheet on one landscape page with its line work. Before printing, its script tries several layout widths and keeps the zoom that fills the page, so keep the script. `check_page.py` writes two PDFs and reports the type size of each: `print.pdf` on A4 (fits any printer; body type about 5.5 pt) and `print-a3.pdf` on A3 (body type about 8 pt, readable on a wall). When the user will pin or print the sheet, ship both and say which is which. Do not cut content to fit a page: if the A3 sheet needs more than one page, split the subject into "Sheet 1 of 2" and "Sheet 2 of 2". Lay the sheet out in the paper's shape: landscape, about 1.4 times as wide as it is tall (the A-series ratio), so the print fills the page. A near-square sheet prints with a quarter of the page blank and smaller type. Keep every panel the user's reference or request asks for (for example a History panel); never drop one to gain print size, ship the A3 PDF instead.

## Visual language

Keep the template's tokens and type. Do not invent new colours.

- Paper `--paper`, ink `--ink`, secondary ink `--ink-2`, `--muted` for labels, `--hair` for light rules, `--tint` and `--zebra` for fills.
- `--blue` for approved, normal, explanatory annotation. `--red` only for "not approved", errors, risks and wrong examples.
- IBM Plex Sans Condensed for text and titles, IBM Plex Mono for codes, field names, axis numbers and meta labels.
- Lines are 1 px (rules, connectors) or 1.5 px (panel and box borders). No shadows, no rounded corners except timeline nodes, no gradients.

## House design rules

These are the skill's house design rules (opinionated defaults; edit them to taste). `check_page.py` enforces the ones a script can see.

- No one-sided accent marks: no coloured `border-left` or `border-right` strips, no single coloured edge on a card, no pseudo-element bars, no inset edge shadows. Highlight with a tint fill, a full four-sided outline, or a chip.
- Text uses the full width it has. No `max-width` on text, no `text-wrap: balance` or `pretty`, no `<br>` to lay out running text.
- Body paragraphs are justified with `hyphens: auto` and `lang="en"` on `<html>`; below 680 px they are left-aligned.
- No em dashes and no emoji. Icons are inline Material SVG paths.
- Self-contained: inline CSS and JS, images as data URIs, Google Fonts as the only network request.

## Sheets that explain a document

When the user gives you a document to understand (an agent's plan, a design
doc, a diff, a long answer), the sheet maps that document, and a separate
panel gives your assessment. The sheet is shorter than the document: a
reader with no time for the source has no time for a longer review.
`check_page.py` prints the visible word count; keep it under the source's
word count. Typical
panels:

- Bottom line (panel A): your verdict on the user's decision in one sentence, the conditions, and a sentence the user can say at their meeting
- What it proposes (tree of the parts or phases)
- Decisions it makes (status table: decision, what it says, section)
- Numbers it depends on (gauges or a table, each with its section)
- Order of work (timeline of phases, with each exit criterion)
- Risks (table with severity; mark which risks the document names and which you add)
- What to check before you approve (procedure in STE)
- Title block with the document name and its date or version

Every fact names its section of the source in a column or in the meta label.
When the source does not say something that matters, write "Not stated in the
source" in that cell. Quote the source's own words only inside
`data-ste="ignore"`.

**Check the document against itself before you build.** A faithful map of a
flawed plan reads like an approval. Ask:

- Does each mechanism meet the goal it claims? (A guarantee that one step quietly breaks.)
- Do the numbers agree across sections? (A retention time against a deduplication window; a limit against a peak rate.)
- Does each failure path keep the promise the document makes? (What happens on a crash, a retry, a replay, a full disk.)
- What happens on the first start, a restart and a rebuild? (An initial snapshot or backfill, a consumer that restarts from the beginning, a cache that starts empty.)
- Is every step that one section depends on in the order of work?
- Is every open question tied to a gate or an owner?

Put each mismatch in the assessment panel, with both section references, in
STE, and with a WARNING or CAUTION chip when it can lose data or cause an
outage.

## Final check

```bash
python3 <skill-dir>/scripts/check_page.py <page.html> --out <scratch-dir>/<page>-check
python3 <skill-dir>/scripts/ste_lint.py <page.html> --mode 80    # or strict
```

Fix every error. Then read the tiles that `check_page.py` lists (2x phone
tiles, and desktop tiles for a tall page) and the desktop screenshot at full
size, and check:

- every panel has its letter, title and meta label, and letters run in reading order;
- annotation brackets sit under the part they explain, inline or in legend mode;
- no heading or paragraph wraps while space remains on its line;
- no large empty area inside a panel (the report warns about dead space);
- the title block is complete, with "Facts as of", and at the bottom right;
- the print report says 1 A4 page.
````

## File: skills/legible-explainer/references/ste-writing.md
size: 12630
sha: a53f0527dfca06f88d17f8d0bf0a5c5c53a8540a
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/references/ste-writing.md

```text
# Writing in ASD-STE100 (Simplified Technical English)

ASD-STE100 is a controlled language standard. The aerospace industry made it
for maintenance documentation, so that a reader whose first language is not
English, under time pressure, reads one meaning only. The same rules make any
explanation faster to read. This file paraphrases the rules for use in
explanations; it is not the standard. The standard (Issue 9, 15 January 2025:
53 writing rules in 9 sections and a dictionary of about 900 approved words)
is free to download from asd-ste100.org and is the authority. Do not copy text
from it into outputs. Facts here checked against the STEMG FAQ, ASD and
tcworld notes on Issue 9, and an Issue 9 dictionary copy, as of 2026-10-03.

## Contents

- The rules, by section
- The dial: 80% and strict
- Substitution table
- STE for explanations (beyond maintenance text)
- Keep the meaning
- Before and after
- History, for sheets about STE itself
- What the linter checks

## The rules, by section

**1 Words.** Use approved words only in their approved meaning and part of
speech. "Close" is a verb ("close the valve"), never an adjective meaning
"near". "Check" and "test" are approved only as nouns: write "do a check of
the oil level", not the verb. "About" means only "concerned with"; for a
rough number write "approximately". Issue 9 calls the words of a trade
**technical nouns** (names of parts, tools, software objects, protocols) and
**technical verbs** (verbs of the trade, such as "compile" or "deploy"). They are
not in the dictionary: the dictionary lists approved words and common
unapproved words, and the writer adds the technical nouns and verbs of the
subject under the Part 1 rules. Use
them when no approved word can replace them, and use each only in its own part
of speech: a technical noun is never a verb ("cache the response" uses the
noun "cache" as a verb; write "keep a copy of the response"), and a technical
verb is never a noun ("a deploy"). Use the same word for the same thing every
time: do not switch between "server", "host" and "machine" for one thing. Use
American spelling.

**2 Multi-word nouns.** Issue 9 calls them multi-word nouns (Issue 8: noun
clusters). Do not write one of more than 3 words. Break a long one with a
preposition or a relative clause: "the cache invalidation event handler"
becomes "the handler for cache invalidation events". An established technical
noun of more than 3 words can stay, but explain it the first time.

**3 Verbs.** Use only these forms: the imperative ("Close the valve."), the
simple present ("The valve closes."), the simple past ("The valve closed."),
the simple future ("The valve will close."), the infinitive ("Turn the knob to
close the valve.") and the past participle as an adjective ("the closed
valve", "make sure that the valve is closed"). Do not use the progressive
("is closing") or the perfect ("has closed"). Use the -ing form of a verb only
as a technical noun or as a modifier in a technical noun ("landing gear",
"logging"); "before starting the pump" and "by using the tool" are not STE.
Words that only end in -ing, and approved -ing words such as "during",
"missing" and "remaining", are fine. Use the active voice. In an instruction,
never the passive ("The valve must be closed." is not an instruction in STE;
write "Close the valve."). In a description, the passive only when the agent
is not known.

**4 Sentences.** Write short sentences. Write only one topic in each sentence.
Do not leave out words to make a sentence shorter: keep "the", "a" and "that".
Use a vertical list for complex text. Use connecting words ("then", "but",
"because") to join sentences into a logical sequence.

**5 Procedures.** No more than 20 words in a sentence of an instruction. Write
one instruction in each sentence, unless two actions occur at the same time.
Write instructions in the imperative. When there is a condition, put it first
("If the light comes on, stop the pump."). Put a note (useful information that
is not an instruction) separately from the instruction.

**6 Descriptive writing.** No more than 25 words in a descriptive sentence. No
more than 6 sentences in a paragraph, and one topic in each paragraph. Start a
paragraph with its topic sentence. Give the information in a logical order,
and use words like "first", "then" and "but" to show the order.

**7 Safety instructions.** WARNING is for a risk of injury or death, CAUTION
for a risk of damage to equipment. A project can choose how to map its own
risks; this skill maps data loss and security exposure to WARNING and outages
or damage to CAUTION. Start with a clear and simple command or condition, then
give the risk in a second sentence: "WARNING: Do not touch the brake unit until
it is cool. Hot parts can cause injury."

**8 Punctuation and word counts.** Do not use the semicolon at all. Use a colon
before a vertical list. A number with its unit counts as one word ("10 mm"),
and a hyphenated word counts as one word. The house style adds one rule: no
dashes as punctuation in running text.

**9 Writing practices.** When a word-for-word swap to approved words does not
work, change the construction of the sentence. Use each approved word
correctly. Do not use phrasal verbs ("set up", "carry out", "shut down",
"find out"): use one approved verb ("install", "do", "stop", "find"). Keep a
consistent style.

## The dial: 80% and strict

Karpathy found strict STE stiff and asked for "80% of the way" instead. That
is the default here. The dial relaxes vocabulary, never grammar.

| Rule | 80% (default) | Strict (on request) |
|---|---|---|
| Sentence length 20 / 25 | Keep. A rare sentence (at most 1 in 10) may run up to 3 words over when a split would separate a condition from its action. | Keep, no exceptions. |
| Paragraph of 6 sentences, one topic | Keep. | Keep. |
| Verb forms (no progressive, no perfect) | Keep. | Keep. |
| Other -ing verb forms (gerund, participle) | Avoid them; a few may stay when the rewrite is clumsy. | Remove them all. |
| Active voice, no passive in instructions | Keep. | Keep, and in descriptions too unless the agent is unknown. |
| One instruction for each sentence | Keep. | Keep. |
| Unapproved words, phrasal verbs, "check" and "test" as verbs | Replace the common ones (table below). Keep a non-STE word when the STE word is clumsy or loses meaning ("trade-off", "latency"). | Replace every one you know of. Keep only technical nouns and technical verbs. |
| Approved words in their approved part of speech | Try. | Keep. |
| UPPERCASE for approved words in examples | No. | Only in a dictionary-style table, if useful. |

In 80% mode the goal is the reader's understanding: if an approved word would
make a sentence unclear, use the clearer word. In strict mode, rewrite the
sentence until it is both strict and clear; if you cannot, tell the user which
sentence breaks which rule.

## Substitution table

Common words that STE does not approve, with the approved replacement. The
linter (`scripts/ste_lint.py`) knows this list. It is a small working subset
for this skill, not the STE dictionary. Approximately, frequently,
subsequently and transmit (for energy or a signal) are approved words: do not
replace them.

| Do not write | Write |
|---|---|
| about (meaning "approximately") | approximately |
| accomplish | do, complete |
| additional | more |
| advise | tell |
| allow | let |
| ascertain | find, make sure |
| assist | help |
| attempt | try |
| avoid | prevent, or "do not ..." |
| begin, commence, initiate | start |
| check (verb), verify | do a check of, make sure |
| choose | select |
| demonstrate, illustrate, indicate | show |
| determine | find, calculate |
| due to | because of |
| eliminate | remove |
| ensure | make sure |
| facilitate | help, make easier |
| in order to | to |
| in the event that | if |
| inspect | examine |
| it is imperative that | must |
| leverage, utilize | use |
| locate | find |
| maintain, retain | keep |
| modify | change |
| numerous | many |
| obtain | get |
| often | frequently |
| perform | do |
| permit | let |
| prior to | before |
| replenish | fill |
| terminate | stop |
| test (verb) | do a test of |
| via | through |
| whether | if |
| set up, carry out, shut down, find out, roll out | install or prepare, do, stop, find, release in steps |

Software words that are usually technical nouns or technical verbs (keep them
in their own part of speech): API, request, response, cache, commit, deploy,
compile, query, thread, token, endpoint, schema, latency, timeout, retry.

## STE for explanations (beyond maintenance text)

STE was made for procedures and descriptions of equipment. For explanations,
these habits add the most:

- Define a term in the sentence where it first appears, then never change it.
- Give the purpose before the mechanism: "The cache keeps copies of responses. Pages then load more quickly."
- One idea in each sentence. If a sentence has "and" between two ideas, make two sentences.
- Show cause with "because", "if" and "so". Show order with "first", "then", "after".
- Put numbers in digits with their units: "600 s", "3 replicas", "20 words".
- For a trade-off, write the gain and the cost as two separate sentences.
- Introduce a list by its subject ("What to check before phase 0:"), with no count.
- Write a WARNING or CAUTION only for a real risk, and give the reason after the command.

## Keep the meaning

Simplification must not change what the source says. Before you accept a
rewrite, compare it with the original for:

- certainty: "should reduce" is an expectation, so "the team expects that this will decrease";
- conditions: an "if" or "only when" in the source stays in the rewrite;
- negation and limits: "not", "at most", "only";
- attribution: who claims it ("the plan says", "the vendor states");
- numbers and units, exactly as in the source.

## Before and after

Original (not STE):
<!-- ste-ignore-start -->
> It is imperative that the operator ensures the hydraulic reservoir is
> replenished prior to commencing operation.

> The migration is being rolled out gradually, and once all traffic has been
> shifted to the new cluster, the old one will be decommissioned, which should
> reduce costs by approximately 30%.
<!-- ste-ignore-end -->

STE:

> Make sure that the hydraulic reservoir is full before you start the operation.

> The team moves traffic to the new cluster in steps. When all traffic is on
> the new cluster, the team will stop the old cluster. The team expects that
> this will decrease the cost by approximately 30%.

The second rewrite removes a progressive with a phrasal verb ("is being
rolled out"), a perfect passive ("has been shifted") and the unapproved
"decommission", and splits one 33-word sentence into three. It keeps
"approximately" (an approved word) and keeps the source's "should" as an
expectation.

## History, for sheets about STE itself

- 1979: European airlines asked AECMA (the European association of aerospace manufacturers) to study a controlled form of English.
- 1983: the AECMA Simplified English working group started (it later became the STEMG, the STE Maintenance Group).
- 1986: the first AECMA Simplified English Guide (document PSC-85-16598).
- 2004: AECMA merged into ASD, and the guide became ASD-STE100, Simplified Technical English.
- 2005: ASD-STE100 became an international specification.
- 2013 (Issue 6): free of charge.
- 15 January 2025 (Issue 9): 53 rules unchanged in number, 31 refined, 555 dictionary entries updated, technical nouns and technical verbs reclassified in line with ISO 1087-1:2019.

Sources: STEMG FAQ and history pages (asd-ste100.org), tcworld news on Issue 9, Wikipedia. Re-check before you quote them.

## What the linter checks

`ste_lint.py` reads text, Markdown, HTML and SVG (stdin is read as Markdown).
It counts words the STE way (a number with its unit is one word) and flags:

- errors in both modes: sentences over their limit (in 80 mode only more than 3 words over, or more than 1 in 10 sentences over), paragraphs over 6 sentences, progressive and perfect verbs, the passive in an instruction or with a named agent, semicolons, dashes, and the house rules ("caveat", headcount openers, "X, not Y");
- warnings in 80 mode, errors in strict: the words and phrasal verbs in the table, "check" and "test" as verbs, other -ing verb forms, two instructions joined by "and" or "then".

It does not check meaning, parts of speech in general, or multi-word nouns.
Read every finding: some are false alarms (for example a technical noun that
ends in -ing; pass it with `--allow`).
```

## File: skills/legible-explainer/references/video.md
size: 10893
sha: a8666d823f058ba4985ff53b502d0a743dd05d9f
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/references/video.md

````text
# Tier 4: explainer video

A narrated video is the richest tier and the slowest to make. Use it when the
user asks for a video, or when the subject unfolds in time (a protocol
exchange, an algorithm step by step, an idea that builds up) and the user
wants something to watch.

## Pick the engine

| The user asks for | Engine | Why |
|---|---|---|
| "3b1b style", "3Blue1Brown", math or mechanism shown as geometry | **Manim Community Edition** with LaTeX | It is the tool that look comes from: LaTeX type, vectors as arrows on a plane, objects that transform into the next state |
| Any other explainer look (typographic, diagram-led, data-viz, a brand style) | The **`hyperframes`** skill, `faceless-explainer` workflow | HTML compositions, captions, music and a full review loop |

## Workflow

1. **Get the content right first.** Collect and verify the facts as for a sheet. For a subject with several parts, plan the sheet panels (`references/spec-sheet.md`) even if you do not build the sheet: each scene comes from a panel. Recompute every number you show.
2. **Write the message**: one sentence that the viewer must remember.
3. **Plan the film in three parts** (see Structure below): a title card with a one-line intro, the body, then a recap card.
4. **Choose the voice** (below). When the user has not heard the options, render a 10-second sample of 4 to 6 candidate voices into one small HTML page with a player for each, open it, and let them pick by number.
5. **Write the narration** and **the scene plan** (below) in a brief folder: `<delivery folder>/<slug>-video/explainer-narration.md` and `explainer-scenes.md`. Keep these names: hyperframes owns `STORYBOARD.md`, and on a case-insensitive disk `storyboard.md` is the same file.
6. **Build** with the engine (below).
7. **Verify the render** (below).
8. **Deliver** only what the user needs: the `.mp4`, an `.srt`, the narration, the scene plan, and the source in `<slug>-video/source/` (scene code and a build script). Keep framework working files (presets, packets, captures, caches) out of the delivery folder.

## Voice

- `ELEVENLABS_API_KEY` is set: ElevenLabs.
- The user asks for free and local, or there is no key: Kokoro on-device. With Manim, use `kokoro-onnx` in a Python venv and its model files (`kokoro-v1.0.onnx`, `voices-v1.0.bin` from the kokoro-onnx release). With hyperframes, use `media-use` with `--local-only`. espeak-ng stores its data path in a short buffer: if Kokoro fails with a "phontab" error, copy the espeak-ng data folder to a short path and point to it.
- Pick the voice that suits the named style and name the other option in one line. With Kokoro, start from `af_heart` (the voice users preferred in testing; `am_michael` sounded flat to them), at `speed` 0.8.
- Leave room to think: about 1.1 s of silence after each sentence and about 1.9 s between scenes. Users found the default pace (speed 1.0, 0.3 s gaps) far too fast for a math explainer.
- Nothing works: macOS `say -v Samantha -o narration.aiff`, and tell the user it is a placeholder.

Generate the voice one sentence at a time and record each clip's length; time the animation from those lengths, so each visual lands on the sentence that names it.

## Narration

Spoken English is the one place where STE yields. Keep its discipline (short
sentences, one idea in each, one word for one thing, active voice, no
progressive or perfect forms) but write the way a good teacher talks:
"Here is the trick.", "Now watch what happens to bank." Do not label the
narration as STE unless the user asked for STE.

- At the pace above, narration runs at about 100 words a minute including pauses. Target words = seconds x 1.6: 60 s is about 95 words, 90 s about 145.
- At most 15 to 18 words in a sentence.
- Say what is on the screen: "This arrow is the query. It points at each key in turn."
- Define each term the first time you say it, then never change the word.
- Lint it with `ste_lint.py explainer-narration.md --mode 80` and fix the grammar findings.

## Structure

Every video has three parts, so a viewer knows what they will learn, follows it, and leaves with the point.

1. **Title card, 6 to 9 s.** It is also the thumbnail, so it is the first frame: the topic in large type, a one-line subtitle ("in about a minute"), one visual hint of the subject, and a footer with the source or maker when the user wants one. The narration says what the viewer is about to see in one sentence: "In the next minute, you will see how a model finds the meaning of a word from the words around it."
2. **The body**, built from the scene plan.
3. **Recap card, 12 to 20 s.** The steps as a short chain of boxes with arrows, and the key formula or result. The narration starts "So, to recap." and repeats the steps in one or two sentences, then names the idea. Hold 2 to 3 s after the last word, with the music fading out.

Crossfade between the parts (about 0.6 s). Never open on a black or half-drawn frame.

## Music

A quiet bed helps a long explainer; a harsh one ruins it.

- Prefer a real track: `media-use resolve --type bgm --intent "calm minimal piano, no drums"` (needs the HeyGen CLI and its OAuth sign-in; ask the user once).
- Without a catalog, synthesize a sparse soft piano locally: single notes about once a second on a slow four-chord progression, short decays, a low-pass around 2 kHz and a little reverb. Never use sustained synth pads or detuned sine stacks; users found them painful.
- Mix it about 20 dB under the voice (measure the music-only stretches with `volumedetect`), duck it gently under speech (ratio about 2.5, attack 250 ms, release 1.2 s), fade in over 2 s and out over 3 s.
- When the user says the music hurts or distracts, remove it at once and offer a catalog track.

## Scene plan

A table with one row for each scene. Each scene shows one idea.

| # | Seconds | Narration (exact words) | On screen | Motion |
|---|---|---|---|---|
| 1 | 0 to 6 | "Attention lets each word look at the other words." | A sentence of 5 tokens in a row | Tokens fade in from left to right |

## Look (3Blue1Brown style)

- Dark background, light ink, one accent colour for the thing being explained, a second accent only for contrast.
- Show mechanisms as geometry: vectors as arrows on a plane, a dot product as alignment between two arrows, weights as bar lengths.
- Build up, do not cut: objects move, split, combine and transform into the next state. Fade out a text label before you transform its object, so no garbled glyphs show mid-morph.
- One new object or change at a time, timed to the word that names it. Start each visual on the first word of its sentence, so no second of the video is empty.
- Show where each new quantity comes from when it first appears (for attention: q = W_Q x, k = W_K x, v = W_V x).
- Use one symbol for one thing in narration and on screen (for example √d_k everywhere, with "d_k is the key size" on screen once).
- Math in LaTeX (`MathTex`), set in pieces as the narration reaches them.
- Labels at 28 px or more at 1080p; keep everything inside a 5% title-safe margin.
- Burn the captions in: X, LinkedIn and most feeds autoplay muted and drop soft subtitle tracks. Use a small sans font at the bottom margin, clear of every on-screen label (check the frames where labels sit low). On the title and recap cards, leave an empty band above the footer and place those captions in it with a larger bottom margin. Also ship the `.srt`.
- Hold the final state for 2 to 3 seconds with the message on screen.

## Build with Manim

- Create a venv (`uv venv` or `python3 -m venv`) in scratch and install `manim`; it needs ffmpeg, cairo and pango, and a LaTeX install for `MathTex`.
- One `Scene` class with a section for each row of the scene plan; read the clip lengths from the timings file and use them as `run_time` and `wait` values.
- Render at 1080p (`manim -qh`). Render the title and recap cards as still frames (`manim -s`) in the same colours and fonts.
- Assemble with ffmpeg: title card, body and recap card with `xfade`; the intro, body and recap narration placed at their offsets; the music bed ducked under the narration; captions burned in with `subtitles` (a build of ffmpeg with libass; a container image such as `linuxserver/ffmpeg` has it when the local one does not). Take the length from the video so the closing hold is kept.
- Put `scene.py`, `narrate.py` and a `build.sh` that rebuilds everything in `source/`.

## Build with hyperframes

1. Create the film project in a new, empty folder, for example `<slug>-video/film/`: `npx hyperframes init <that folder> --skill=faceless-explainer`. `init` refuses a folder that has files in it.
2. Write `BRIEF.md` at the root of the film project, in the hyperframes brief format:

```markdown
---
workflow: faceless-explainer
flow: automation
storyboard: no            # yes when the user wants to review the plan before the build
message: "<the one sentence>"
destination: youtube
aspect: 1920x1080
language: en
length: 45s
angle: concept
audience: "<who watches>"
voice: <the voice you chose>
---

## Intent

<One short paragraph: what the video teaches, for whom, the tone.>

## Assets

- ../explainer-narration.md: final narration. VO_MODE: verbatim.
- ../explainer-scenes.md: scene plan with timings; build one frame for each row.

## Notes

- The narration is final. Do not rewrite it.
- Captions: burned in, small, at the bottom margin, clear of labels; also export an .srt.
- <When the user is not present:> The user is not available for questions. Proceed with these answers.
```

3. Load the `hyperframes` skill and ask it to build and render the project. A `BRIEF.md` on disk lets it run without its interview.

## Verify the render

```bash
ffprobe -v error -show_entries format=duration:stream=codec_type -of json <video.mp4>
```

- The duration is within 15% of the requested length; there is an audio stream.
- The first frame is the title card, and its text reads at phone size.
- Captions never overlap a label or the card footer; check a frame from every scene and both cards.
- Pauses: the gaps between sentences are 0.7 s or longer (`silencedetect` on the narration track). Music: the music-only stretches sit 18 to 22 dB under the speech.
- Extract frames (`ffmpeg -vf fps=0.5`) and look at them at full size: text is readable, nothing is cut off at the edges, no glyph is garbled mid-transform, each scene matches its row.
- Transcribe the audio locally (whisper.cpp when installed) and compare with the narration.

## Hand over

Lead the chat reply with the file path, the length and the voice, then two or
three lines on what the video shows. When the user asked for a free or local
tool, name it, its licence, and the one command that installs it on their
machine, even when it was already installed on yours. Put install and rebuild notes in a
`README.md` next to `source/`, not in the chat.
````

## File: skills/legible-explainer/assets/spec-sheet-template.html
size: 36519
sha: 494f4c5efda3e5aff5c850241c3f2da6ad1fd6c5
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/assets/spec-sheet-template.html

Content is not inlined in the catalog. Read the upstream file: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/assets/spec-sheet-template.html

## File: skills/legible-explainer/evals/evals.json
size: 10572
sha: e7e9c7abb1019ad11f0aa4c41bafe9f750ef6fad
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/evals/evals.json

```text
{
  "skill_name": "legible-explainer",
  "evals": [
    {
      "id": 1,
      "name": "ste-text-tcp-congestion",
      "prompt": "can you explain how TCP congestion control works? write it in ASD-STE100, maybe 80% of the way there, the full spec reads too stiff for me. I mostly care about slow start, what happens when a packet gets lost, and why CUBIC is the default on linux now",
      "expected_output": "Tier 1: the answer in chat (saved as answer.md), no HTML page, opening with a short answer to each named topic. Written in about 80% STE: short sentences, approved verb forms, active voice. Covers slow start, congestion avoidance, loss signals (timeout vs triple duplicate ACK), fast retransmit / fast recovery, and why CUBIC replaced Reno-style AIMD on Linux (window growth as a cubic function of time since the last loss, better on high bandwidth-delay paths, default since kernel 2.6.19). Offers the next tier in one line.",
      "files": [],
      "assertions": [
        "Technically accurate: slow start grows cwnd by about one MSS per ACK (doubling each RTT) up to ssthresh; a timeout sets ssthresh to about half and restarts cwnd from a small window; three duplicate ACKs trigger fast retransmit and fast recovery with cwnd about halved; no wrong claims",
        "Explains why CUBIC is the Linux default: window growth is a cubic function of the time since the last loss, mostly independent of RTT, so it uses high bandwidth-delay paths well and treats flows with different RTTs more fairly; default since about kernel 2.6.19 (2006)",
        "Reads as about 80% STE: short sentences, active voice, approved verb forms, mostly approved words, and it does not read stiff",
        "Does not over-build: a prose answer (chat or Markdown), no page, diagram or video that the user did not ask for",
        "Opens with a short answer to each topic the user named before the detail"
      ]
    },
    {
      "id": 2,
      "name": "diagram-oauth-pkce",
      "prompt": "I keep losing track of the OAuth 2.0 authorization code flow with PKCE while debugging our login (Next.js app, Auth0 is the IdP, then we call our own API with the access token). Draw me a diagram I can keep open on my second monitor.",
      "expected_output": "Tier 2: one self-contained HTML page with a hand-drawn inline SVG sequence diagram in the drawing-sheet style. Parties: user/browser, Next.js app (client), Auth0 authorization server, own API (resource server). Numbered steps covering code_verifier generation, code_challenge (S256) on /authorize, login and consent, redirect with code (and state), token request with code + code_verifier, Auth0 checks the challenge, tokens returned, API call with the bearer access token and token validation. STE labels and a numbered STE steps list. Passes check_page.",
      "files": [],
      "assertions": [
        "Sequence is correct: the client makes code_verifier, sends code_challenge = BASE64URL(SHA-256(verifier)) with method S256 and state on /authorize; user logs in at Auth0; Auth0 redirects with code and state; the app checks state; the app exchanges code + code_verifier at /oauth/token; Auth0 checks the challenge and returns tokens (access token for the API audience); the API validates the JWT (signature with JWKS, iss, aud, exp)",
        "Usable as a second-monitor reference: numbered steps, legible text at desktop size, no labels on lines or on each other (judge from the screenshot)",
        "Specific to the user's stack and debugging: shows where each value lives or the common failure points (state mismatch, redirect URI mismatch, wrong audience, verifier lost between requests)",
        "Uses the engineering-drawing sheet language (frame, title block, sheet tokens) or an equally clear, consistent visual system",
        "Diagram text reads at 12 px or more on the desktop screenshot and the tracked values (state, code_challenge, code_verifier, token) are visible without clicking"
      ]
    },
    {
      "id": 3,
      "name": "sheet-ste-overview",
      "prompt": "Make me a one-page overview of ASD-STE100 itself, drawn like an engineering drawing sheet. Something like the attached image (evals/files/example-ste-sheet.png). I want to pin it next to my desk when I write docs.",
      "expected_output": "Tier 3: one self-contained HTML spec sheet that matches the reference image's visual language (zone frame 1-8 by A-D, lettered panels, title block) with correct STE facts: Issue 9 (2025), 9 sections, 53 rules, about 900 approved words, limits 20 / 25 words, 6 sentences per paragraph, noun clusters of max 3 words, approved verb forms, WARNING vs CAUTION, history 1979 / 1986 / 2004-2005. Prose in STE. Passes check_page and ste_lint. It must not copy the reference image's own errors: APPROXIMATELY is an approved word (ABOUT means only 'concerned with'), TEST and CHECK are approved only as nouns, and Issue 9 uses 'technical nouns' and 'multi-word nouns'.",
      "files": [
        "evals/files/example-ste-sheet.png"
      ],
      "assertions": [
        "Visual fidelity to the reference image: zone frame 1-8 by A-D, lettered panels, title block at bottom right, blue approved and red not approved, bracket annotations under an example sentence, limit gauges, a timeline (judge from the desktop screenshot)",
        "Does not copy the reference image's STE errors: does not call APPROXIMATELY unapproved or replace it with ABOUT, does not show TEST or CHECK as approved verbs, uses Issue 9 terms (technical nouns, multi-word nouns) when it names Issue 9",
        "Facts are correct on a spot-check of at least 8 facts (limits 20/25/6/3, verb forms, WARNING vs CAUTION, Issue 9 date and counts, history dates)",
        "Annotations stay readable at desktop and phone width (no labels over text, no clipped panels)",
        "No large empty area in any panel at 1440 px and short table cells do not wrap onto two lines"
      ]
    },
    {
      "id": 4,
      "name": "understand-llm-plan",
      "prompt": "Claude wrote this migration plan overnight (evals/files/plan.md). I don't have time to read all of it carefully before standup. Help me actually understand what it proposes and what could go wrong before I approve phase 0.",
      "expected_output": "The skill picks a sheet (tier 3) or another tier with a stated reason. Every fact traces to plan.md: CDC with Debezium into Kafka topic orders.status.v1 (12 partitions, keyed by order_id, 7-day retention), notifier service, rejected outbox and LISTEN/NOTIFY with reasons, at-least-once plus Redis idempotency key (72 h TTL), rollout phases 0-5 with the 10/50/100% flag steps and the 99.9% shadow match, p95 from 4 min 40 s to under 10 s, rollback by flag, cost figures, named risks and both open questions. Its own assessment is separated from the plan's claims and catches at least one real gap the plan does not name (for example: the Redis key is set before the provider call, so a failed send is skipped on retry; the 72 h TTL is shorter than the 7-day Kafka retention, so a replay resends; max_slot_wal_keep_size invalidates the slot and loses events). No invented numbers.",
      "files": [
        "evals/files/plan.md"
      ],
      "assertions": [
        "Every claim traces to plan.md; no invented numbers, names or decisions (spot-check numbers against the plan)",
        "Keeps the plan's own claims visibly separate from the reviewer's assessment",
        "Finds at least one real gap the plan does not name: the Redis key is set before the provider call so a failed send is skipped on retry; the 72 h TTL is shorter than the 7-day retention so a replay resends; max_slot_wal_keep_size invalidates the slot and loses events; the cron key backport is not in the phase 0 row; open questions are not tied to a gate",
        "Gives a clear answer on approving phase 0 (with conditions) that the user can use at standup",
        "Scannable in a few minutes: the reader finds what the plan proposes and the top risks without reading everything",
        "Opens with a one-sentence verdict on phase 0 and a line the user can say at standup (in chat and on the sheet)"
      ]
    },
    {
      "id": 5,
      "name": "video-attention",
      "prompt": "Create a 3b1b style video explainer on how self-attention works in transformers, about 45 seconds, with narration. I don't have an ElevenLabs key, so find something free that runs locally.",
      "expected_output": "Tier 4: an MP4 of about 45 s (within 15%) with an audio stream, made with Manim (the skill's engine for a 3Blue1Brown look), voiced by a free local TTS (Kokoro or similar). Narration script in STE (about 100 words) and a scene plan saved next to it, outside the hyperframes project. Content covers queries, keys and values, dot-product scores, softmax weights and the weighted sum. The final message names the voice used.",
      "files": [],
      "assertions": [
        "The voice is free and runs locally (for example Kokoro), with no cloud TTS or paid provider, and the final message names it",
        "Looks 3Blue1Brown-like on extracted frames: dark background, objects that build up and change, readable text, nothing cut off",
        "Content is correct: queries, keys and values from learned projections, dot-product scores (scaled by the square root of d_k), softmax weights, and the weighted sum of values",
        "Narration is complete and matches the scenes (judge from the script, timings and any transcript)",
        "Looks like 3Blue1Brown on the frames: LaTeX-set math, vectors drawn as arrows, objects that transform, no burned-in captions"
      ]
    },
    {
      "id": 6,
      "name": "tier-restraint-mutex",
      "prompt": "quick q, whats the difference between a mutex and a semaphore? keep it short and STE-ish, I'm reading this on my phone",
      "expected_output": "Tier 1 only: a short STE answer in chat (saved as answer.md for grading), under about 300 words, no HTML page, no video offer. Correct: a mutex has one owner and only the owner can release it; a semaphore holds a count and any thread can signal it; a binary semaphore is not the same as a mutex (ownership, priority inheritance).",
      "files": [],
      "assertions": [
        "Correct: a mutex has an owner and only the owner unlocks it; a semaphore holds a count and any thread can signal it; a binary semaphore is not the same as a mutex",
        "Phone-friendly: short, scannable, no page or file the user has to open",
        "Opens with the bottom line: the first sentence states the difference"
      ]
    }
  ]
}
```

## File: skills/legible-explainer/evals/files/example-ste-sheet.png
size: 344308
sha: 5d286611d0c5c7c10b7189d47a78aa33e3d1b9ca
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/evals/files/example-ste-sheet.png

Content is not inlined in the catalog. Read the upstream file: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/evals/files/example-ste-sheet.png

## File: skills/legible-explainer/evals/files/plan.md
size: 7956
sha: 35acfe234c967c89d731317b488c10bff20a7831
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/skills/legible-explainer/evals/files/plan.md

```text
# Migration Plan: Event-Driven Order Notifications (v2)

*Prepared by the coding agent overnight, based on the repository, the incident history in `docs/incidents/`, and the Grafana dashboards linked from the README.*

## 1. Executive Summary

Our current order-notification system relies on a cron job (`notify_orders`) that runs every five minutes and polls the `orders` table for rows whose `status` has changed since the last run. While this approach has served us well, it is increasingly showing its limitations: the p95 delay between a status change and the customer receiving a notification currently sits at 4 minutes 40 seconds, the polling query accounts for roughly 18% of CPU on the primary Postgres instance during business hours, and we have had three incidents in the last quarter where overlapping cron runs sent duplicate emails. We send approximately 1.2 million notifications per day across email, SMS and push.

This document proposes migrating to an event-driven pipeline built on change data capture (CDC). Debezium will stream row-level changes from Postgres into a Kafka topic, and a new `notifier` service will consume those events and dispatch notifications through our existing provider integrations. The target is a p95 end-to-end delay below 10 seconds, the removal of the polling load from the primary, and a structural fix for the duplicate-send problem.

## 2. Current State

- `notify_orders` is a Python cron job deployed on the `jobs` host, scheduled with `*/5 * * * *`.
- Each run selects rows where `updated_at > last_run_at` and `status IN ('confirmed','shipped','delivered','refunded')`, renders templates, and calls the email (SendGrid), SMS (Twilio) and push (FCM) providers synchronously.
- `last_run_at` is stored in a single-row table. When a run takes longer than five minutes (which happens during peaks), the next run starts with a stale `last_run_at` and picks up the same rows again. This is the root cause of the duplicate-send incidents INC-2291, INC-2304 and INC-2342.
- There are 14 distinct code paths in the monolith that write to `orders.status`, which is relevant to the choice of approach below.

## 3. Options Considered

### 3.1 Transactional outbox

Each of the 14 write paths would insert a row into an `outbox` table inside the same transaction, and a relay would publish outbox rows to Kafka. This is the textbook approach and gives strong guarantees, but it requires touching all 14 write paths, several of which live in legacy modules with poor test coverage. We estimate 3 to 4 weeks of additional work and a meaningful regression risk. **Rejected for now**, although it remains the long-term ideal.

### 3.2 Postgres LISTEN/NOTIFY

Lightweight and built in, but notifications are not durable (anything sent while the consumer is disconnected is lost), and payloads are limited to 8000 bytes. **Rejected** because missed notifications are not acceptable.

### 3.3 Change data capture with Debezium (chosen)

Debezium reads the Postgres write-ahead log (WAL) through a logical replication slot and publishes every change to `orders` as an event. No application code changes are required, all 14 write paths are covered automatically, and events are durable in Kafka. **Chosen.**

## 4. Target Architecture

1. **Debezium connector** (`orders-cdc`) running on our existing Kafka Connect cluster, using the `pgoutput` plugin and a dedicated replication slot `debezium_orders`. It captures only the `orders` table and only the columns `id`, `status`, `version`, `merchant_id`, `customer_id`, `updated_at`.
2. **Kafka topic** `orders.status.v1` with 12 partitions, keyed by `order_id`, replication factor 3, retention 7 days.
3. **`notifier` service**, a new Go service in its own deployment with 3 replicas in a single consumer group. For each event it:
   - filters to the four notifiable statuses,
   - builds the idempotency key `order_id:status:version`,
   - checks and sets that key in Redis with a TTL of 72 hours (`SET NX EX`), skipping the event if the key already exists,
   - renders the template and calls the provider,
   - commits the Kafka offset only after the provider call succeeds.
4. **Delivery semantics** are at-least-once from Kafka, made effectively-once for customers by the Redis idempotency check.
5. **Ordering** is guaranteed per order because events are keyed by `order_id`, so all events for one order land on the same partition. There is no ordering guarantee across orders, which we do not need.

## 5. Rollout Plan

| Phase | Week | What happens | Exit criterion |
|---|---|---|---|
| 0 | 1 | Create topic, deploy Debezium connector, deploy `notifier` with sending disabled | Connector lag under 5 s for 3 days |
| 1 | 2 to 3 | Shadow mode: `notifier` consumes and logs the notification it *would* send; a comparison job diffs this against what cron actually sent | At least 99.9% match over 7 consecutive days |
| 2 | 4 | Feature flag `notif_pipeline_v2` turned on for 10% of merchants; cron skips merchants where the flag is on | No increase in support tickets about notifications |
| 3 | 5 | Flag at 50% of merchants | p95 delay under 10 s |
| 4 | 6 | Flag at 100%; cron job disabled but left deployed | 7 days without a rollback |
| 5 | 8 | Delete `notify_orders` and the `last_run_at` table | n/a |

During phases 2 to 4 both systems are live for different merchants. Because cron and `notifier` share the same Redis idempotency keys (we will backport the key check into cron in phase 0), a merchant who is moved between systems mid-flight will not receive duplicates.

## 6. Rollback

At any point before phase 5, rollback is a single flag change: turning `notif_pipeline_v2` off returns all merchants to cron within one cron cycle. We expect rollback to take under 5 minutes end to end. After phase 5 the cron code is gone and rollback would require a redeploy from the last tagged release.

## 7. Cost

- Kafka (managed, 3 brokers) and Kafka Connect add approximately $1,400 per month.
- Redis usage is negligible on the existing cluster (about 3.6 million keys at steady state given the 72-hour TTL).
- Removing the polling query frees about 18% of primary CPU during business hours, which lets us defer the planned primary upgrade (currently budgeted at $2,100 per month) by at least two quarters.

## 8. Risks and Mitigations

- **Replication slot growth.** If Debezium stops consuming, Postgres retains WAL for the slot indefinitely and can fill the disk. Mitigation: alert when slot lag exceeds 20 GB, and set `max_slot_wal_keep_size = 50GB` so that the primary is protected.
- **Schema changes to `orders`.** Renaming or dropping a captured column breaks the connector. Mitigation: add a CI check that fails migrations touching captured columns unless the connector config is updated in the same PR.
- **Duplicate sends during cutover.** Covered by the shared Redis idempotency key described in section 5.
- **Provider outages.** `notifier` retries with exponential backoff (max 5 attempts) and then writes the event to a dead-letter topic `orders.status.dlq.v1` for manual replay.

## 9. Open Questions

- **Kafka on-call ownership.** The platform team has not yet agreed to own Kafka on-call. Until they do, the orders team would carry the pager.
- **SMS rate limits.** Our Twilio account is limited to 100 messages per second. Cron naturally smoothed bursts by batching every five minutes; the event-driven pipeline will send as fast as events arrive, so a large batch of status changes (for example a bulk "shipped" update from a warehouse import) could exceed the limit. We have not decided whether to add a rate limiter in `notifier` or request a higher limit.

## 10. Recommendation

Proceed with phase 0 next week. The plan delivers a large latency improvement, removes a recurring incident class, and reduces load on the primary, with a low-risk rollback path through phase 4. The two open questions should be resolved before phase 2.
```

## File: README.md
upstream: https://github.com/futureatoms/karpathy-ladder/blob/main/README.md

````text
# The Karpathy Ladder

[![checks](https://github.com/FutureAtoms/karpathy-ladder/actions/workflows/test.yml/badge.svg)](https://github.com/FutureAtoms/karpathy-ladder/actions/workflows/test.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Claude Code plugin](https://img.shields.io/badge/Claude%20Code-plugin-d97757.svg)](#install)

**An unofficial Claude Code skill that makes LLM output easy to understand.** Not affiliated with or endorsed by Andrej Karpathy or Anthropic. Ask for an explanation and get it in the format that fits: ASD-STE100 prose, a diagram, a one-page engineering-drawing spec sheet, or a narrated 3Blue1Brown-style video.

![The Karpathy Ladder: STE prose, diagram, spec sheet and explainer video, with test results](docs/karpathy-ladder.png)

On 2 October 2026 Andrej Karpathy [posted](https://x.com/karpathy/status/2105819303471976479) that we will spend a lot more time trying to understand the outputs of language models, and he ranked the output formats that help most. Each one is "even better" than the last: text in ASD-STE100 (the controlled English of aircraft maintenance manuals), then diagrams, then web pages, then custom explainer videos. This repo turns that ladder into one skill that picks the right rung for each question, builds the output, and checks it before you see it.

## Install

In Claude Code (v2.1.275 or later):

```
/plugin install karpathy-ladder --marketplace FutureAtoms/karpathy-ladder
```

On an older version, add the marketplace first:

```
/plugin marketplace add FutureAtoms/karpathy-ladder
/plugin install karpathy-ladder@karpathy-ladder
```

The plugin is one skill. It has no hooks and no MCP server; it runs two local Python checkers on the pages it makes.

Or copy the skill folder by hand:

```bash
git clone https://github.com/FutureAtoms/karpathy-ladder
cp -r karpathy-ladder/skills/legible-explainer ~/.claude/skills/
```

The page checker needs Python 3 and Playwright (`pip install playwright && playwright install chromium`). The video rung also uses [Manim Community Edition](https://www.manim.community/), ffmpeg, a LaTeX install, and [kokoro-onnx](https://github.com/thewh1teagle/kokoro-onnx) for a free local voice (or ElevenLabs when `ELEVENLABS_API_KEY` is set).

## Use it

Ask the way you normally would. The skill picks the lowest rung that fully answers the question, and an explicit format request always wins.

| You ask | You get |
|---|---|
| "Explain TCP congestion control in ASD-STE100, about 80% of the way" | The answer in chat, in STE: short sentences, approved verb forms, one meaning for each word |
| "Draw the OAuth PKCE flow so I can keep it open while I debug" | A self-contained HTML page with a hand-drawn SVG sequence diagram, every value on its arrow |
| "Make a one-page overview of X I can pin next to my desk" | An engineering-drawing spec sheet in HTML, plus A4 and A3 PDFs |
| "An agent wrote this plan overnight. What does it propose and what could go wrong?" | A sheet that maps the document, checks it against itself, and leads with a verdict you can say at standup |
| "Make a 3b1b-style video on self-attention with a free local voice" | A narrated MP4 built with Manim and Kokoro: a title card that says what is coming, the explanation at a calm pace, a recap card, burned-in captions and a quiet music bed |

## What is inside

```
skills/legible-explainer/
  SKILL.md                      how to pick a rung, write in STE, deliver
  references/ste-writing.md     ASD-STE100 rules in plain words, the 80% / strict dial, a substitution table
  references/diagram.md         rung 2: SVG diagrams
  references/spec-sheet.md      rung 3: the drawing-sheet layout and its components
  references/video.md           rung 4: Manim or HyperFrames, voice, narration, scene plan
  assets/spec-sheet-template.html   a working sheet with every component
  scripts/ste_lint.py           STE linter: sentence limits, verb forms, passive voice, unapproved words
  scripts/check_page.py         renders at 5 widths and in print; flags overflow, collisions, tiny print type
  evals/                        the test prompts used below
examples/                       real outputs from the evaluation runs
```

Every page the skill makes opens from `file://` with no build step, and Google Fonts is its only network request. The skill also follows a house style that you can edit in `SKILL.md`: no em dashes, justified body text, no one-sided accent bars, no text squeezed into a narrow column.

## Does it work?

The skill was built with Anthropic's skill-creator loop and reviewed by four AI reviewers from three model families. As of 2026-10-03:

- **Blind reader test:** each reviewer saw the skill's output and plain Claude's output for six tasks, labelled A and B at random, and said which one a reader would understand faster. The skill won 17 of 24 comparisons, with 2 ties.
- **Graded checks:** 93% passed with the skill, 75% without it, across the six evals (STE quality, accuracy, layout, print, delivery).
- **Cost:** about 390 s more per task than plain Claude, mostly spent on checking the page and verifying facts.

Both sides ran fresh on the same day with the same model. One run per side is a small sample, so read these as a direction. Details, the tasks where plain Claude won, and what changed after are in [docs/benchmark.md](docs/benchmark.md).

## Examples

| Rung | Example |
|---|---|
| STE prose | [TCP congestion control](examples/1-ste-prose/tcp-congestion-control.md), [mutex vs semaphore](examples/1-ste-prose/mutex-vs-semaphore.md) |
| Diagram | [OAuth 2.0 + PKCE with Next.js and Auth0](examples/2-diagram-oauth-pkce/) |
| Spec sheet | [ASD-STE100 overview](examples/3-spec-sheet-ste100/) (HTML, A4 and A3 PDF), [review of an agent-written migration plan](examples/3-plan-review/) |
| Video | [Self-attention in 92 s](examples/4-video-self-attention/) (MP4, script, scene plan, Manim source) |

Open an HTML example in a browser. The sheets reflow on a phone and print on one landscape page.

## Contributing

New examples, sharper checks, more STE substitutions and new video styles are all welcome. Start with [CONTRIBUTING.md](CONTRIBUTING.md), pick an issue labelled [good first issue](https://github.com/FutureAtoms/karpathy-ladder/labels/good%20first%20issue), or post what the skill made for you in [Show and tell](https://github.com/FutureAtoms/karpathy-ladder/discussions/categories/show-and-tell). Run `./tests/check.sh` before you open a pull request; CI runs the same checks.

## Credits

The idea and the ladder come from Andrej Karpathy's post. ASD-STE100 is maintained by the ASD Simplified Technical English Maintenance Group; the standard is free from [asd-ste100.org](https://www.asd-ste100.org). This skill paraphrases its rules and does not reproduce the standard.

MIT licensed. Made by [FutureAtoms](https://github.com/FutureAtoms).
````
