feat(explain-diff): explain a diff as one self-contained HTML page

Adapted from Geoffrey Litt's explain-diff gist: background, intuition, grouped code walkthrough, 5-question quiz, saved outside the repo. Bundled template, components catalog and checker with its test suite. Row reflect; profiles full, max, dev.
This commit is contained in:
bchanot committed 2026-10-17 13:05:01 +02:00
1 parent 6f0deb489d
commit b353fac2ba
14 files changed
+1266

No files matched your search

+9
View File
@@ -1,5 +1,14 @@
# TODO
## 2026-10-17 — /explain-diff skill: HTML explanation of a diff (feature/explain-diff)
Source: geoffreylitt gist `explain-diff-html` (Notion variant dropped). Built through the skill-creator loop (draft, evals with/without skill, user review).
- [x] T1 `skills/explain-diff/SKILL.md` (target resolution, understand, 4 sections, style, save outside repo, check, hand-over) + `test-prompts.json`
- [x] T2 `assets/template.html` (self-contained skeleton: light/dark tokens, TOC, diagram primitives, diff + quiz JS) + `references/components.md`
- [x] T3 `scripts/check_explanation.py` (deterministic floor: name, location, sections, TOC, 5-question quiz, code escaping, no ASCII art, no em-dash, self-contained) + `lib/tests/explain-diff-check.test.sh` (17 checks: valid page, raw template, one mutant per check)
- [x] T4 registration: full/max/dev profiles, routing.json row `reflect`, README + USAGE x2 + CHANGELOG
- [ ] T5 skill-creator iteration 1: 3 evals x (with skill, baseline), grading, static viewer, user review
- [ ] T6 `make test` + `impeccable detect` on the template; commit on the branch; merge = user go
## 2026-10-16 — impeccable = Build path for all UI (chore/impeccable-build-path)
User validated: frontend-design overlaps impeccable 4.6; gate still blocked on frontend-design. Supersedes the 2026-07-05 "complementary, keep both" call.
- [x] CLAUDE.global.md Build line: impeccable leads, frontend-design = light path only, rule count 45 -> 61
+1
View File
@@ -13,6 +13,7 @@ Format follows [Keep a Changelog](https://keepachangelog.com/) and this project
- **model-router prompt classifier**: a plain prompt typed in the composer (12 characters or more, not a slash command, not mid-turn, never under `-p` or in a sub-agent) that no keyword rule, skill, run slot, `/route` or floor covers is labelled by one call to the engine's small model (`design`, `analysis`, `coding`, `bookkeeping`, `chat`), bounded to 3 s. The label maps to plan, reflect, implement or apply and the turn takes that phase's route: its effort, and its model under the switch and the downgrade cap, never above the session model (an `ultrathink` floor keeps its model); no dialog, no file write, gone at the end of the turn, replaced by any route call or typed skill, and dropped for that turn by a `/effort` typed between turns. Three failures in a row pause it for `cooldownMinutes` (one toast, `classifier: paused` in the status line). `"classify": false` in `~/.claude/model-router.json` and `/route classify on|off` turn it off; `/route show` prints `classify:`. The status line reads `route: classifier <phase>` and `/route verbose on` adds `(<phase>: classifier)`.
- **model-router cold-read caps**: both main-loop caps measure the cold read a switch costs, from a per-model record of main's last step, warm within the engine's prompt-cache TTL (`cache_ttl` 5m or 1h from main's model-switch events, 1 h before the first, kept across `/clear`; records cleared by `/clear` and `/route reload`), plus the submitted prompt the engine's usage may not count yet (code points / 3 of its text, context entries and a typed skill's body, added at the turn's first main step unless usage already grew by half of it; a `document` attachment blocks the switch for that step); `downgradeMaxTokens` (default 120000) joins `upgradeMaxTokens` (200000). A model-loaded helper skill inside a best-tier run moves effort only; main routed onto a model whose window the context outgrew returns to the session model. `/route show` prints `switch: on (downgrade, cap 120000 tokens cold, ttl 60 min)`, the status line shows ` · switch off` only when the switch is off, the skip line is logged once per cap crossing and the change toast names a cap hold. A built-in `general-purpose` agent that main spawns with no model while main sits below the session model starts on the session model instead of inheriting the lower one.
- **/explain-diff skill**: turns a change (commit, range, branch, merge, PR, staged or uncommitted work) into one self-contained HTML page saved outside the repo, under `~/Documents/explanations/<project>/YYYY-MM-DD-<slug>.html`. The page has a background, an intuition built on toy data with HTML diagrams, a code walkthrough grouped by concern and a 5-question interactive quiz. Adapted from Geoffrey Litt's explain-diff gist. A bundled template (light and dark, works offline) and a checker (`scripts/check_explanation.py`: file name, location, sections, quiz, code escaping, no ASCII art, no em-dash) hold every page to the same floor. Routing row `reflect`; profiles full, max and dev.
### Changed
- impeccable is the Build path for all UI: it replaces `frontend-design` on the design gate's `# GATE-BLOCK:` list and leads the Build line of the design doctrine. `frontend-design` stays installed as the light path for a one-off visual. Detector rule count corrected 45 to 61 (BDR-119).
+1
View File
@@ -227,6 +227,7 @@ a different package, ships its own conflicting `graphify` bin) — see
| `/prune-memory` | Curate and compress the .claude/memory/ registries |
| `/reconcile` | Confront declared status (TODO, registries) against real git/fs state — surface stale items |
| `/pdf-translate` | Translate a PDF to another language, output as HTML (via Vision) |
| `/explain-diff` | Explain a diff, commit, branch or PR as one self-contained HTML page (background, intuition, code walkthrough, 5-question quiz), saved outside the repo |
| `/close` | End-of-session ritual — alias for `/capitalize --ritual` (dedup + TODO reconcile + 3-question reflection) |
| `/harden` | Web hardening audit — HTTPS/TLS, HSTS, CSP, security headers |
| `/web-validate` | W3C HTML/CSS validity + WCAG 2.1 accessibility audit |
+2
View File
@@ -119,6 +119,7 @@ Tu veux...
| Visibilité IA (GEO seul) | `/geo` |
| Livraison client finale | `/client-handover` |
| Traduire un PDF | `/pdf-translate` |
| Comprendre un changement pas suivi | `/explain-diff` |
| Changer profil skills | `/profile` |
| Audit/polish design (anti-slop) | `/impeccable` |
| Sweep groupé tous axes (nettoyage + sécu + reconcile + doc) | `/tour` |
@@ -161,6 +162,7 @@ Tu veux...
| `/web-validate` | Audit W3C + WCAG a11y | Avant livraison projet web |
| `/client-handover` | Livraison client | Audits finaux + livrable brandé |
| `/pdf-translate` | Traduire un PDF vers une autre langue | Sortie HTML fidèle (images, layout, style préservés) |
| `/explain-diff` | Comprendre un commit, une branche ou une PR qu'on n'a pas suivis | Page HTML autonome hors du repo : contexte, intuition, code, quiz de 5 questions |
| `/impeccable` | Audit/polish design + détecteur anti-slop déterministe | 23 verbes ; `npx impeccable detect` (exit 0/2) |
| `/tour` | Sweep groupé sur un ou plusieurs projets | Sécu + nettoyage + reconcile + doc, boucle jusqu'à un pass propre |
| `/route` | Voir ou fixer la route du mod model-router | show / clear / off / on / reload / pending / ask on\|off / <phase> / model=… effort=… / switch on\|off / classify on\|off (classifieur de prompt) / verbose on\|off (transitions seules) |
+1
View File
@@ -17,6 +17,7 @@ review
refactor personal
code-clean personal
commit-change personal
explain-diff personal
# Dev-lifecycle skills (agent-skills trio)
observability-and-instrumentation external
+1
View File
@@ -59,6 +59,7 @@ qa-only
doc personal
document-release
pdf-translate personal
explain-diff personal
# === Session hygiene + memory ========================================
close personal
+1
View File
@@ -62,6 +62,7 @@ document-release
diagram
make-pdf
pdf-translate personal
explain-diff personal
# === Session hygiene + memory ========================================
close personal
+101
View File
@@ -0,0 +1,101 @@
#!/usr/bin/env bash
# lib/tests/explain-diff-check.test.sh — skills/explain-diff checker
# (scripts/check_explanation.py): the template filled with valid content
# passes, the raw template fails, and one single-change mutant per check
# fails (each mutant is a positive control that MUST be detected).
set -u
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
SKILL="$ROOT/skills/explain-diff"
CHECK="$SKILL/scripts/check_explanation.py"
pass=0; fail=0
check() { if [ "$2" = "$3" ]; then pass=$((pass+1)); else fail=$((fail+1));
printf 'FAIL %s: got[%s] want[%s]\n' "$1" "$2" "$3"; fi; }
WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
# fill <out> <quiz-mode> — the template with valid sample content; the quiz
# mode (valid | four | two-right | no-why) breaks the quiz on purpose.
fill() {
python3 -I - "$SKILL/assets/template.html" "$1" "$2" <<'PY'
import json, sys
src = open(sys.argv[1], encoding="utf-8").read()
mode = sys.argv[3]
def opts(i):
return [{"text": "a", "correct": True, "why": "right, since"},
{"text": "b", "correct": mode == "two-right", "why": "no"},
{"text": "c", "correct": False,
"why": "" if mode == "no-why" else "no"}]
count = 4 if mode == "four" else 5
quiz = [{"q": f"Question {i}?", "options": opts(i)} for i in range(count)]
values = {
"LANG": "en", "TITLE": "Sample", "PROJECT": "demo", "RANGE": "abc123",
"DATE": "2026-10-17", "STATS": "2 files", "LEAD": "A lead.",
"TOC_TITLE": "Contents", "BACKGROUND_TITLE": "Background",
"INTUITION_TITLE": "Intuition", "CODE_TITLE": "Code",
"QUIZ_TITLE": "Quiz", "BACKGROUND_BODY": "<p>Text.</p>",
"INTUITION_BODY": "<p>Text with <code>a — b</code>.</p>",
"CODE_BODY": "<pre><code>if (a &lt; b) { go(); }</code></pre>",
"QUIZ_INTRO": "<p>Five questions.</p>", "QUIZ_RIGHT": "Right.",
"QUIZ_WRONG": "Not quite.", "QUIZ_SCORE": "Score: {n} out of {total}",
"COLOPHON": "Made by explain-diff.", "QUIZ_JSON": json.dumps(quiz),
}
for key, value in values.items():
src = src.replace("{{" + key + "}}", value)
open(sys.argv[2], "w", encoding="utf-8").write(src)
PY
}
# mutate <in> <out> <old> <new> — exactly one literal replacement
mutate() {
python3 -I -c 'import sys
s = open(sys.argv[1], encoding="utf-8").read()
assert s.count(sys.argv[3]) == 1, sys.argv[3]
open(sys.argv[2], "w", encoding="utf-8").write(s.replace(sys.argv[3], sys.argv[4]))
' "$1" "$2" "$3" "$4"
}
rc() { python3 "$CHECK" "$1" >/dev/null 2>&1; echo $?; }
D="$WORK/2026-10-17"
OK="$D-valid.html"
fill "$OK" valid
check T1-valid-page-passes "$(rc "$OK")" 0
cp "$SKILL/assets/template.html" "$D-raw-template.html"
check T2-raw-template-fails "$(rc "$D-raw-template.html")" 1
cp "$OK" "$WORK/sample.html"
check T3-undated-name-fails "$(rc "$WORK/sample.html")" 1
git init -q "$WORK/repo" && cp "$OK" "$WORK/repo/2026-10-17-in-repo.html"
check T4-inside-git-tree-fails "$(rc "$WORK/repo/2026-10-17-in-repo.html")" 1
mutate "$OK" "$D-cdn.html" '</title>' \
'</title><script src="https://cdn.example.com/x.js"></script>'
check T5-remote-script-fails "$(rc "$D-cdn.html")" 1
mutate "$OK" "$D-nosection.html" 'id="intuition"' 'id="intuit"'
check T6-missing-section-fails "$(rc "$D-nosection.html")" 1
mutate "$OK" "$D-toc.html" 'href="#quiz"' 'href="#top"'
check T7-toc-link-missing-fails "$(rc "$D-toc.html")" 1
mutate "$OK" "$D-viewport.html" 'name="viewport"' 'name="x-viewport"'
check T8-no-viewport-fails "$(rc "$D-viewport.html")" 1
for mode in four two-right no-why; do
fill "$D-quiz-$mode.html" "$mode"
check "T9-quiz-$mode-fails" "$(rc "$D-quiz-$mode.html")" 1
done
mutate "$OK" "$D-generic.html" 'if (a &lt; b) { go(); }' \
'const m = new Map<string, number>();'
check T10-unescaped-generic-fails "$(rc "$D-generic.html")" 1
mutate "$OK" "$D-box.html" 'if (a &lt; b) { go(); }' $'┌─┐'
check T11-box-drawing-fails "$(rc "$D-box.html")" 1
mutate "$OK" "$D-dash.html" 'A lead.' $'A lead — with a dash.'
check T12-em-dash-in-prose-fails "$(rc "$D-dash.html")" 1
check T13-em-dash-in-code-allowed "$(rc "$OK")" 0
mutate "$OK" "$D-left.html" 'A lead.' 'A lead. {{LEAD}}'
check T14-placeholder-left-fails "$(rc "$D-left.html")" 1
out=$(python3 "$CHECK" "$D-dash.html")
check T15-fail-line-names-check "$(printf '%s\n' "$out" \
| grep -c '^FAIL em-dash:')" 1
printf 'explain-diff checker: %d pass, %d fail\n' "$pass" "$fail"
[ "$fail" -eq 0 ]
+1
View File
@@ -73,6 +73,7 @@
"hotfix": "reflect",
"bugfix": "reflect",
"refactor": "reflect",
"explain-diff": "reflect",
"web-validate": "reflect",
"harden": "reflect",
"seo": "reflect",
+153
View File
@@ -0,0 +1,153 @@
---
name: explain-diff
effort: high
description: 'Use when the user wants to understand a code change they did not follow closely (a diff, commit, range, branch, merge or PR, often written by an agent) and asks for an explanation, a walkthrough or an HTML page of it. Writes one self-contained HTML file outside the repo: background, intuition with toy data and diagrams, grouped code walkthrough, 5-question interactive quiz. Fights cognitive debt. Triggers: "explain-diff", "explique ce diff", "explique ce qui a été fait", "explain this commit/PR/branch", "walk me through the changes", "pas suivi ce commit", "dette cognitive". Bug hunt on a diff → /code-review; code without a change → /analyze.'
argument-hint: '[sha | A..B | branch | PR# | staged | uncommitted] [project path]'
---
# Explain Diff
Code now lands faster than anyone reads it. An agent writes forty files, the
tests pass, the branch merges, and a month later nobody on the project can
say why a function runs twice. That gap is cognitive debt. This skill pays
it down: it turns one change into a page a reader can study in twenty
minutes and come out of able to own the code.
The page is one self-contained HTML file with four sections (background,
intuition, code, quiz), saved outside the repository so it never pollutes
version control.
## STEP 1 — Resolve the target
Work in the project the user names (`git -C <path>`), else the current one.
Map the argument to a diff:
| Argument | Commits to read | Diff to explain |
|---|---|---|
| `<sha>` | `git log -1 <sha>` | `git show <sha>`; a merge → `git diff <sha>^1 <sha>`, the whole merged branch |
| `A..B` | `git log A..B` | `git diff A...B` |
| `<branch>` | `git log <base>..<branch>` | `git diff <base>...<branch>` |
| `#<n>`, PR | `gh pr view <n>` | `gh pr diff <n>` (GitHub remote with `gh` only, else ask for the branch) |
| `staged` | none | `git diff --cached` |
| `uncommitted` | none | `git diff HEAD`, plus untracked files from `git status --porcelain` |
`<base>` is `develop` when it exists, else `main`, else `master`.
No argument: on a branch ahead of its base, explain `<base>...HEAD`, plus
the uncommitted changes when the tree is dirty. On the base branch itself,
explain the last commit (a merge → the whole merged branch).
Before writing, say in one line what resolved: range, commit count, files,
lines. An empty diff stops the skill: name the target that came out empty.
## STEP 2 — Understand before writing
The diff shows what moved. The explanation needs what it moved inside.
1. Read the whole diff, then the commit messages (`git log --format=%B`).
They usually hold the why. Follow what they cite when it exists in the
repo: a design record, a plan, a contract, an issue.
2. Read around the change: the functions it touches, their callers and
callees, the tests, the module's entry point. Background is about this
existing system, and the diff alone never shows it.
3. Name the problem the change solves as an observable behaviour: what a
user, a caller or a test saw before, and what it sees now. New tests are
the best witness of that.
4. Triage big diffs (roughly over 1500 changed lines or 25 files).
Generated files, lockfiles, snapshots and vendored code get one line in
the Code section, not a walkthrough. Group the rest by concern.
5. Keep facts and inferences apart. When nothing in the repo says why,
write the most plausible reading and mark it as an inference in the page.
6. Never copy a credential-like value (token, key, password, URL with auth)
into the page. Redact it and warn the user in the reply.
## STEP 3 — Write the explanation
Write in the user's language, the one of their request. Identifiers,
commands and code stay as they are. Aim for classic style with the clarity
and flow of Martin Kleppmann: the writer has seen something and shows it to
a smart reader, concrete before abstract, each section leading into the
next. The user-facing writing rules in context apply as well
(`rules/writing-style.md`: no em-dash, no "not X, it's Y" frame, no filler).
Open with a header and a lead: two or three sentences saying what changed
and why, the version a reader could repeat in one breath. Then four
sections, in this order, on one long page with a table of contents at the
top and no tabs:
1. **Background.** The existing system this change lives in. The reader's
level is unknown, so start with a deep background for newcomers inside a
collapsible block marked as skippable, then the narrow background this
change touches directly.
2. **Intuition.** The essence of the change, not its details. Build it on a
concrete example with toy data (a guest with id `g-42`, a cache holding
three entries) and show before and after. Use diagrams generously.
3. **Code.** A high-level walkthrough. Order the changes the way a reader
understands them, cause before effect and core before plumbing, never by
file order. For each group: what it does, why, a short excerpt of the
lines that matter, and the `path:line` to open. End with what the tests
now prove.
4. **Quiz.** Five multiple-choice questions of medium difficulty. Answering
needs the substance of the change, not trivia or traps: predict the
behaviour on a toy input, say why a step is needed, pick where a
follow-up fix belongs, spot the edge case. Every option, right or wrong,
carries a one or two sentence explanation.
Callouts mark key concepts, definitions, important edge cases and risks.
### Diagrams
Pick one to three diagram families and reuse them across the page, so the
reader learns the visual language once:
- a simplified mock of the screen the user sees, for UI changes;
- a flow of components with example data on each arrow, for data or calls;
- a row of states, for lifecycle or state-machine changes;
- a before and after pair, for any behaviour change.
Draw them with the HTML primitives of `references/components.md`, or with
inline SVG. Never ASCII art: box-drawing characters break on a phone and say
less than three styled boxes.
## STEP 4 — Build the page
The skill folder is `$HOME/.claude/skills/explain-diff/`.
1. Read `references/components.md` (the snippet catalog), then start from
a copy of `assets/template.html`.
2. Replace every `{{…}}` placeholder. Section ids stay `background`,
`intuition`, `code` and `quiz`: the table of contents and the checker
rely on them.
3. Code goes in `<pre>` blocks, HTML-escaped (`<` as `&lt;`, `>` as `&gt;`,
`&` as `&amp;`). An unescaped `<T>` generic or JSX tag silently swallows
the code that follows it.
4. The quiz lives in the `quiz-data` JSON block and the template's script
renders it. Keep the page self-contained: no CDN, no web font, no remote
image. It has to open offline from disk a year from now.
## STEP 5 — Save, check, hand over
1. Save to `~/Documents/explanations/<project>/YYYY-MM-DD-<slug>.html`.
Today's date comes first so the folder sorts by time, `<project>` is the
basename of the repo and `<slug>` a few kebab-case words naming the
change. Never inside the project tree. A taken name gets `-2`.
2. Run the checker and fix every FAIL until it exits 0:
```bash
python3 "$HOME/.claude/skills/explain-diff/scripts/check_explanation.py" <file>
```
3. Reread the prose against the writing rules and fix what slipped.
4. Reply with the absolute path and its `file://` URL, the one-line summary
of the change, the inferences the page marks as such, and the secret
warning if one was redacted. Do not paste the explanation into the chat:
the page is the deliverable.
## When things go wrong
| Situation | Action |
|---|---|
| Not a git repository | Ask for the project path |
| Target resolves to an empty diff | Stop and name the target |
| PR number without `gh`, or a non-GitHub remote | Ask for the branch name |
| Binary files in the diff | List them in Code, do not walk them |
| Over about 5000 changed lines | Explain the top level, offer one page per commit or folder |
| Checker FAIL | Fix and rerun; never hand over a failing page |
+549
View File
@@ -0,0 +1,549 @@
<!doctype html>
<html lang="{{LANG}}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light dark">
<title>{{TITLE}}</title>
<style>
:root {
--bg: #faf9f6;
--surface: #f1eee7;
--ink: #1f1d1a;
--muted: #5a554c;
--line: #d8d3c8;
--accent: #245a8f;
--accent-wash: #e4ecf4;
--add-bg: #e3f0e1;
--add-ink: #1f5427;
--del-bg: #f6e2de;
--del-ink: #8a2a1f;
--edge-ink: #7a5408;
--select: #cddff0;
--serif: Charter, "Bitstream Charter", "Iowan Old Style", "Sitka Text",
Cambria, "Noto Serif", Georgia, serif;
--sans: system-ui, -apple-system, "Segoe UI", Roboto, "Noto Sans",
sans-serif;
--mono: ui-monospace, "SF Mono", "Cascadia Mono", "DejaVu Sans Mono",
Menlo, Consolas, monospace;
--measure: 68ch;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #171614;
--surface: #22201c;
--ink: #ebe7df;
--muted: #aaa498;
--line: #3b3832;
--accent: #8fb8e2;
--accent-wash: #1d2935;
--add-bg: #1c2e1e;
--add-ink: #a3d6a6;
--del-bg: #361f1b;
--del-ink: #f2a89d;
--edge-ink: #e3b65f;
--select: #2d4560;
}
}
*, *::before, *::after { box-sizing: border-box; }
[hidden] { display: none !important; }
html {
-webkit-text-size-adjust: 100%;
scroll-behavior: smooth;
scrollbar-color: var(--line) var(--bg);
}
@media (prefers-reduced-motion: reduce) {
html { scroll-behavior: auto; }
}
body {
margin: 0;
background: var(--bg);
color: var(--ink);
font: 1.0625rem/1.65 var(--serif);
caret-color: var(--accent);
}
::selection { background: var(--select); color: var(--ink); }
a {
color: var(--accent);
text-decoration-thickness: 1px;
text-underline-offset: 0.18em;
}
a:hover { text-decoration-thickness: 2px; }
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 3px;
}
.page { max-width: 62rem; margin: 0 auto; padding: 3rem 1rem 6rem; }
.masthead, .toc, .q, .colophon,
main > section > :is(p, ul, ol, h2, h3, h4, blockquote, details, .callout) {
max-width: var(--measure);
}
h1, h2, h3, h4 {
font-family: var(--sans);
line-height: 1.2;
letter-spacing: -0.01em;
text-wrap: balance;
}
h1 {
margin: 0 0 0.75rem;
font-size: clamp(1.9rem, 1.4rem + 2.2vw, 2.7rem);
font-weight: 700;
letter-spacing: -0.02em;
}
h2 {
margin: 4.5rem 0 1rem;
padding-top: 1.5rem;
border-top: 1px solid var(--line);
font-size: 1.6rem;
font-weight: 650;
}
h3 { margin: 2.5rem 0 0.6rem; font-size: 1.15rem; font-weight: 650; }
h4 { margin: 1.75rem 0 0.4rem; font-size: 1rem; font-weight: 650; }
p, ul, ol { margin: 0 0 1.1rem; }
li + li { margin-top: 0.3rem; }
.meta {
margin: 0 0 1.5rem;
font: 0.9rem/1.5 var(--sans);
color: var(--muted);
font-variant-numeric: tabular-nums;
}
.lead { font-size: 1.2rem; line-height: 1.55; }
/* Table of contents */
.toc {
margin: 2.5rem 0 1rem;
padding: 1rem 1.25rem;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--surface);
font-family: var(--sans);
}
.toc-title { margin: 0 0 0.4rem; font-size: 0.95rem; font-weight: 650; }
.toc ol { margin: 0; padding-left: 1.25rem; }
.toc a { text-decoration: none; }
.toc a:hover { text-decoration: underline; }
/* Code */
code {
padding: 0.05em 0.3em;
border: 1px solid var(--line);
border-radius: 4px;
background: var(--surface);
font-family: var(--mono);
font-size: 0.88em;
}
pre {
margin: 0 0 1.5rem;
padding: 0.9rem 1rem;
overflow-x: auto;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--surface);
font: 0.85rem/1.6 var(--mono);
white-space: pre;
tab-size: 2;
}
pre code { padding: 0; border: 0; background: none; font-size: inherit; }
pre.diff { padding: 0.9rem 0; }
pre.diff .lines { display: inline-block; min-width: 100%; }
pre.diff .ln { display: block; padding: 0 1rem; }
pre.diff .add { background: var(--add-bg); color: var(--add-ink); }
pre.diff .del { background: var(--del-bg); color: var(--del-ink); }
pre.diff .hunk { color: var(--muted); }
figure { margin: 2rem 0; }
figure pre { margin: 0; }
figcaption {
max-width: var(--measure);
margin-top: 0.6rem;
font: 0.85rem/1.5 var(--sans);
color: var(--muted);
}
.path {
display: block;
margin: 0 0 0.35rem;
font: 0.8rem/1.4 var(--mono);
color: var(--muted);
}
/* Callouts and the skippable deep background */
.callout {
margin: 1.75rem 0;
padding: 0.9rem 1.1rem;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--surface);
}
.callout.concept { border-color: var(--accent-wash); background: var(--accent-wash); }
.callout > :last-child { margin-bottom: 0; }
.callout-title {
margin: 0 0 0.35rem;
font: 650 0.95rem/1.35 var(--sans);
color: var(--accent);
}
.callout.edge .callout-title { color: var(--edge-ink); }
.callout.risk .callout-title { color: var(--del-ink); }
details.deep {
margin: 1.5rem 0 2rem;
padding: 0 1.1rem;
border: 1px solid var(--line);
border-radius: 8px;
}
details.deep > summary {
padding: 0.8rem 0;
cursor: pointer;
font: 600 0.95rem/1.4 var(--sans);
}
details.deep > summary .hint { font-weight: 400; color: var(--muted); }
details.deep[open] > summary {
margin-bottom: 1rem;
border-bottom: 1px solid var(--line);
}
/* Diagrams: flow and states */
.flow { display: flex; align-items: stretch; }
.node {
flex: 1 1 0;
min-width: 0;
padding: 0.7rem 0.8rem;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--surface);
font: 0.9rem/1.4 var(--sans);
}
.node.hl { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); }
.node.state { border-radius: 999px; text-align: center; }
.node-title { display: block; font-weight: 650; }
.node-sub { display: block; font-size: 0.82rem; color: var(--muted); }
.edge {
position: relative;
flex: 0 0 7rem;
align-self: center;
padding: 0 0.6rem 0.7rem;
font: 0.75rem/1.3 var(--mono);
color: var(--muted);
text-align: center;
overflow-wrap: anywhere;
}
.edge::before {
content: "";
position: absolute;
left: 0.3rem;
right: 0.5rem;
bottom: 0.3rem;
border-top: 1.5px solid var(--muted);
}
.edge::after {
content: "";
position: absolute;
right: 0.3rem;
bottom: calc(0.3rem - 4.25px);
border: 5px solid transparent;
border-right: 0;
border-left: 7px solid var(--muted);
}
/* Diagrams: before and after, UI mock */
.compare {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
margin: 1.75rem 0;
}
.pane {
padding: 0.9rem 1rem;
border: 1px solid var(--line);
border-radius: 8px;
}
.pane > :last-child { margin-bottom: 0; }
.pane-label { margin: 0 0 0.5rem; font: 650 0.9rem/1.3 var(--sans); }
.pane.before .pane-label { color: var(--del-ink); }
.pane.after .pane-label { color: var(--add-ink); }
.mock {
max-width: 26rem;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--bg);
font: 0.9rem/1.4 var(--sans);
}
.mock-bar {
padding: 0.45rem 0.75rem;
border-bottom: 1px solid var(--line);
background: var(--surface);
font-size: 0.78rem;
color: var(--muted);
}
.mock-body { display: grid; gap: 0.6rem; padding: 0.9rem; }
.mock-body > * { margin: 0; }
.mock-button {
justify-self: start;
padding: 0.3rem 0.75rem;
border: 1px solid var(--accent);
border-radius: 6px;
color: var(--accent);
font-weight: 600;
}
.mock-field {
padding: 0.35rem 0.6rem;
border: 1px solid var(--line);
border-radius: 6px;
color: var(--muted);
}
.mock-alert {
padding: 0.45rem 0.7rem;
border-radius: 6px;
background: var(--del-bg);
color: var(--del-ink);
}
.mock-alert.ok { background: var(--add-bg); color: var(--add-ink); }
.mark { outline: 2px dashed var(--edge-ink); outline-offset: 3px; }
/* Toy data */
.table-wrap { margin: 1.5rem 0; overflow-x: auto; }
table.data {
width: 100%;
border-collapse: collapse;
font: 0.9rem/1.45 var(--sans);
font-variant-numeric: tabular-nums;
}
table.data th, table.data td {
padding: 0.45rem 0.65rem;
border-bottom: 1px solid var(--line);
text-align: left;
vertical-align: top;
}
table.data th { font-weight: 650; color: var(--muted); }
/* Quiz */
.q {
margin: 1.5rem 0;
padding: 1.1rem 1.2rem 1rem;
border: 1px solid var(--line);
border-radius: 10px;
}
.q-text { margin: 0 0 0.8rem; font-weight: 600; }
.opt {
display: block;
width: 100%;
margin: 0.45rem 0;
padding: 0.65rem 0.85rem;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--bg);
color: var(--ink);
font: 0.95rem/1.45 var(--sans);
text-align: left;
cursor: pointer;
transition: border-color 0.15s ease-out, background-color 0.15s ease-out;
}
.opt:hover:not(:disabled) { border-color: var(--accent); }
.opt:disabled { cursor: default; }
.opt.right { border-color: var(--add-ink); background: var(--add-bg); }
.opt.wrong { border-color: var(--del-ink); background: var(--del-bg); }
.opt .why { display: block; margin-top: 0.35rem; font-size: 0.88rem; color: var(--muted); }
.opt.right .why { color: var(--add-ink); }
.opt.wrong .why { color: var(--del-ink); }
.verdict { min-height: 1.4em; margin: 0.6rem 0 0; font: 600 0.95rem/1.4 var(--sans); }
.score { font: 650 1rem/1.4 var(--sans); }
.colophon {
margin-top: 5rem;
padding-top: 1rem;
border-top: 1px solid var(--line);
font: 0.8rem/1.5 var(--sans);
color: var(--muted);
}
@media (max-width: 40rem) {
body { font-size: 1rem; }
.page { padding-top: 2rem; }
h2 { margin-top: 3.5rem; }
.compare { grid-template-columns: 1fr; }
.flow { flex-direction: column; }
.edge {
flex-basis: auto;
align-self: flex-start;
padding: 0.55rem 0 0.75rem 1.5rem;
text-align: left;
}
.edge::before {
top: 0;
bottom: 0.2rem;
left: 0.65rem;
right: auto;
border-top: 0;
border-left: 1.5px solid var(--muted);
}
.edge::after {
right: auto;
bottom: 0;
left: calc(0.65rem - 4.25px);
border: 5px solid transparent;
border-bottom: 0;
border-top: 7px solid var(--muted);
}
}
</style>
</head>
<body>
<div class="page">
<header class="masthead">
<h1>{{TITLE}}</h1>
<p class="meta">{{PROJECT}} · {{RANGE}} · {{DATE}} · {{STATS}}</p>
<p class="lead">{{LEAD}}</p>
</header>
<nav class="toc" aria-labelledby="toc-title">
<p class="toc-title" id="toc-title">{{TOC_TITLE}}</p>
<ol>
<li><a href="#background">{{BACKGROUND_TITLE}}</a></li>
<li><a href="#intuition">{{INTUITION_TITLE}}</a></li>
<li><a href="#code">{{CODE_TITLE}}</a></li>
<li><a href="#quiz">{{QUIZ_TITLE}}</a></li>
</ol>
</nav>
<main>
<section id="background" aria-labelledby="h-background">
<h2 id="h-background">{{BACKGROUND_TITLE}}</h2>
{{BACKGROUND_BODY}}
</section>
<section id="intuition" aria-labelledby="h-intuition">
<h2 id="h-intuition">{{INTUITION_TITLE}}</h2>
{{INTUITION_BODY}}
</section>
<section id="code" aria-labelledby="h-code">
<h2 id="h-code">{{CODE_TITLE}}</h2>
{{CODE_BODY}}
</section>
<section id="quiz" aria-labelledby="h-quiz">
<h2 id="h-quiz">{{QUIZ_TITLE}}</h2>
{{QUIZ_INTRO}}
<div id="quiz-root" data-right="{{QUIZ_RIGHT}}"
data-wrong="{{QUIZ_WRONG}}" data-score="{{QUIZ_SCORE}}"></div>
<p class="score" id="quiz-score" aria-live="polite"></p>
</section>
</main>
<footer class="colophon">{{COLOPHON}}</footer>
</div>
<script type="application/json" id="quiz-data">
{{QUIZ_JSON}}
</script>
<script>
(function () {
"use strict";
// Backtick spans become <code>; all text goes through textContent.
function withInlineCode(text, el) {
String(text).split("`").forEach(function (part, i) {
if (i % 2 === 1) {
var code = document.createElement("code");
code.textContent = part;
el.appendChild(code);
} else if (part) {
el.appendChild(document.createTextNode(part));
}
});
return el;
}
function lineKind(line) {
if (line.indexOf("@@") === 0) return " hunk";
if (line.charAt(0) === "+") return " add";
if (line.charAt(0) === "-") return " del";
return "";
}
function renderDiff(pre) {
var lines = pre.textContent.replace(/^\n+|\s+$/g, "").split("\n");
var wrap = document.createElement("span");
wrap.className = "lines";
lines.forEach(function (line) {
var span = document.createElement("span");
span.className = "ln" + lineKind(line);
span.textContent = line || " ";
wrap.appendChild(span);
});
pre.textContent = "";
pre.appendChild(wrap);
}
function reveal(chosen, options, verdict, ctx) {
options.forEach(function (o) {
o.button.disabled = true;
o.why.hidden = false;
if (o.data.correct) o.button.classList.add("right");
});
if (!chosen.data.correct) chosen.button.classList.add("wrong");
chosen.button.setAttribute("aria-pressed", "true");
verdict.textContent =
chosen.data.correct ? ctx.labels.right : ctx.labels.wrong;
ctx.answered += 1;
if (chosen.data.correct) ctx.right += 1;
if (ctx.answered === ctx.total) {
ctx.score.textContent = ctx.labels.score
.replace("{n}", ctx.right).replace("{total}", ctx.total);
}
}
function renderOption(data, box) {
var button = document.createElement("button");
button.type = "button";
button.className = "opt";
withInlineCode(data.text, button);
var why = withInlineCode(data.why, document.createElement("span"));
why.className = "why";
why.hidden = true;
button.appendChild(why);
box.appendChild(button);
return { data: data, button: button, why: why };
}
function renderQuestion(item, index, ctx) {
var box = document.createElement("div");
box.className = "q";
var text = document.createElement("p");
text.className = "q-text";
text.appendChild(document.createTextNode(index + 1 + ". "));
box.appendChild(withInlineCode(item.q, text));
var options = item.options.map(function (d) {
return renderOption(d, box);
});
var verdict = document.createElement("p");
verdict.className = "verdict";
verdict.setAttribute("aria-live", "polite");
box.appendChild(verdict);
options.forEach(function (o) {
o.button.addEventListener("click", function () {
reveal(o, options, verdict, ctx);
});
});
return box;
}
function renderQuiz() {
var root = document.getElementById("quiz-root");
var data = document.getElementById("quiz-data");
if (!root || !data) return;
var quiz = JSON.parse(data.textContent);
var ctx = {
labels: root.dataset, answered: 0, right: 0, total: quiz.length,
score: document.getElementById("quiz-score")
};
quiz.forEach(function (item, i) {
root.appendChild(renderQuestion(item, i, ctx));
});
}
document.querySelectorAll("pre.diff").forEach(renderDiff);
renderQuiz();
})();
</script>
</body>
</html>
@@ -0,0 +1,187 @@
# Components for an explain-diff page
Every snippet below is styled by `assets/template.html`. Copy, then replace
the sample content. Keep the class names: the stylesheet and the checker
know them. Sample text is in English; write yours in the page language.
## Skippable deep background
The newcomer's tour of the system goes in a collapsible block, so a reader
who knows it can jump straight to the narrow background.
```html
<details class="deep">
<summary>How the hint service works <span class="hint">(skip if you
know it)</span></summary>
<p>…</p>
</details>
```
## Callouts
Three kinds: `concept` (a definition or key idea), `edge` (an edge case
worth remembering), `risk` (what can still go wrong, or a follow-up).
```html
<aside class="callout concept">
<p class="callout-title">Lazy guest</p>
<p>A visitor who has not played yet has no session row …</p>
</aside>
<aside class="callout edge">
<p class="callout-title">Edge case: session creation fails</p>
<p>…</p>
</aside>
<aside class="callout risk">
<p class="callout-title">Not covered by this change</p>
<p>…</p>
</aside>
```
## Flow of components
Nodes left to right, an edge between each pair. The edge label carries the
example data that travels (a call, a payload, a return value). `hl` marks
the component the change touches. On a phone the flow turns vertical.
```html
<figure class="diagram">
<div class="flow">
<div class="node"><span class="node-title">Browser</span>
<span class="node-sub">guest g-42, no session</span></div>
<div class="edge">ensureGuest()</div>
<div class="node hl"><span class="node-title">fetchHint</span>
<span class="node-sub">new: session first</span></div>
<div class="edge">rpc hint(day=12)</div>
<div class="node"><span class="node-title">Database</span>
<span class="node-sub">auth-gated RPC</span></div>
</div>
<figcaption>After the fix: the session exists before the hint call.
</figcaption>
</figure>
```
A return value travels back through the label of the same edge
(`hint(day=12) → "starts with B"`) or through a second flow below.
## Row of states
Same markup with `state` nodes; `hl` marks the state the change adds.
```html
<div class="flow">
<div class="node state"><span class="node-title">running</span></div>
<div class="edge">crash ×3</div>
<div class="node state hl"><span class="node-title">stopped</span>
<span class="node-sub">new: final</span></div>
</div>
```
## Before and after
```html
<div class="compare">
<div class="pane before">
<p class="pane-label">Before</p>
<p>…</p>
</div>
<div class="pane after">
<p class="pane-label">After</p>
<p>…</p>
</div>
</div>
```
## Simplified UI mock
For UI changes: draw only what the user sees that matters, as boxes.
`mark` outlines the element the change affects. Put two mocks inside the
panes of a `compare` block for a before and after view.
```html
<div class="mock">
<div class="mock-bar">Daily puzzle · day 12</div>
<div class="mock-body">
<p>Find the word in 6 tries.</p>
<div class="mock-field">B _ _ _ _</div>
<div class="mock-button">Hint</div>
<div class="mock-alert mark">Hint unavailable</div>
</div>
</div>
```
`mock-alert ok` gives the success colour.
## Toy data
```html
<div class="table-wrap">
<table class="data">
<thead><tr><th>Visitor</th><th>Session</th><th>Hint</th></tr></thead>
<tbody>
<tr><td>g-42</td><td>none</td><td>refused</td></tr>
</tbody>
</table>
</div>
```
## Code excerpt and diff
Show only the lines that matter, with the `path:line` above. Escape `<`,
`>` and `&` in every code block.
```html
<figure>
<span class="path">apps/web/src/game/daily.ts:31</span>
<pre><code>export async function fetchDailyHint(day: number) {
const ok = await ensureGuestSession();
if (!ok) return null;
}</code></pre>
<figcaption>The session comes first; a failure ends in null.</figcaption>
</figure>
```
A diff block holds raw unified-diff lines; the template's script colours
the `+`, `-` and `@@` lines. Keep the leading `+` / `-` / space.
```html
<figure>
<span class="path">apps/web/src/game/daily.ts</span>
<pre class="diff">@@ -28,6 +28,9 @@ export async function fetchDailyHint
export async function fetchDailyHint(day: number) {
+ const ok = await ensureGuestSession();
+ if (!ok) return null;
return rpc(&quot;hint&quot;, { day });</pre>
</figure>
```
## Quiz data
The template renders the quiz from the JSON block `quiz-data`. Five
questions, three or four options each, exactly one `"correct": true`, and a
`why` on every option. Backticks in any string render as inline code. Plain
text only, no HTML; write `<\/` for any `</` inside a string.
```json
[
{
"q": "A guest with no session asks for a hint. What runs first?",
"options": [
{"text": "The hint RPC", "correct": false,
"why": "That was the bug: the RPC refused a caller with no session."},
{"text": "`ensureGuestSession()`", "correct": true,
"why": "The fetcher now creates the session, then calls the RPC."},
{"text": "A page reload", "correct": false,
"why": "Nothing reloads; the fix stays inside the fetcher."}
]
}
]
```
Labels on `#quiz-root` follow the page language. `{n}` and `{total}` in the
score label are filled by the script.
| Placeholder | English | French |
|---|---|---|
| `{{QUIZ_RIGHT}}` | Right. | Exact. |
| `{{QUIZ_WRONG}}` | Not quite. | Pas tout à fait. |
| `{{QUIZ_SCORE}}` | Score: {n} out of {total} | Score : {n} sur {total} |
+254
View File
@@ -0,0 +1,254 @@
#!/usr/bin/env python3
"""Deterministic floor for an explain-diff page.
Usage: check_explanation.py <file.html>
Prints one PASS / WARN / FAIL line per check. Exit 1 when any check fails,
2 on a usage or read error.
"""
import json
import re
import subprocess
import sys
from html.parser import HTMLParser
from pathlib import Path
SECTIONS = ("background", "intuition", "code", "quiz")
PRE_INLINE_TAGS = {"code", "span", "b", "strong", "em", "i", "mark", "a", "br"}
BOX_DRAWING = re.compile("[─-╿]")
ASCII_BOX = re.compile(r"\+-{3,}\+|\|\s{2,}\S.*\s{2,}\|")
NAME = re.compile(r"^\d{4}-\d{2}-\d{2}-[a-z0-9]+(-[a-z0-9]+)*\.html$")
REMOTE_TAG = re.compile(
r"<(script|link|img|iframe|source|video|audio)\b[^>]*"
r"\b(src|href)\s*=\s*[\"']?(https?:)?//", re.I)
REMOTE_CSS = re.compile(r"@import|url\(\s*[\"']?(https?:)?//", re.I)
EM_DASH = "—"
class Page(HTMLParser):
"""Collects, in one pass, what the checks below need."""
def __init__(self):
super().__init__(convert_charrefs=True)
self.ids, self.toc_links, self.pre_bad_tags = set(), set(), set()
self.lang, self.viewport, self.quiz_text = "", False, None
self.pre_text, self.prose = [], []
self._pre = self._code = self._skip = 0
self._nav = self._quiz = False
def handle_starttag(self, tag, attrs):
attr = {k: v or "" for k, v in attrs}
if attr.get("id"):
self.ids.add(attr["id"])
if self._pre and tag not in PRE_INLINE_TAGS:
self.pre_bad_tags.add(tag)
handler = getattr(self, "_open_" + tag, None)
if handler:
handler(attr)
def handle_endtag(self, tag):
if tag == "pre":
self._pre = max(0, self._pre - 1)
elif tag == "code":
self._code = max(0, self._code - 1)
elif tag in ("script", "style"):
self._skip, self._quiz = max(0, self._skip - 1), False
elif tag == "nav":
self._nav = False
def handle_data(self, data):
if self._quiz:
self.quiz_text = (self.quiz_text or "") + data
elif self._skip:
return
elif self._pre:
self.pre_text.append(data)
elif not self._code:
self.prose.append(data)
def _open_html(self, attr):
self.lang = attr.get("lang", "").strip()
def _open_meta(self, attr):
if attr.get("name", "").lower() == "viewport":
self.viewport = True
def _open_nav(self, _attr):
self._nav = True
def _open_a(self, attr):
href = attr.get("href", "")
if self._nav and href.startswith("#"):
self.toc_links.add(href[1:])
def _open_pre(self, _attr):
self._pre += 1
def _open_code(self, _attr):
self._code += 1
def _open_style(self, _attr):
self._skip += 1
def _open_script(self, attr):
self._skip += 1
self._quiz = attr.get("id") == "quiz-data"
def check_name(path):
if NAME.match(path.name):
return [("PASS", "name", path.name)]
return [("FAIL", "name", f"{path.name} must be YYYY-MM-DD-<slug>.html")]
def check_location(path):
try:
out = subprocess.run(
["git", "-C", str(path.parent), "rev-parse",
"--is-inside-work-tree"],
capture_output=True, text=True, check=False).stdout.strip()
except OSError:
return [("WARN", "location", "git not found, location unchecked")]
if out == "true":
return [("FAIL", "location", "file sits inside a git work tree")]
return [("PASS", "location", "outside any git work tree")]
def check_self_contained(src):
hits = REMOTE_TAG.findall(src) + REMOTE_CSS.findall(src)
if hits:
return [("FAIL", "self-contained", f"{len(hits)} remote resource(s)")]
return [("PASS", "self-contained", "no remote script, style or media")]
def check_head(page):
out = []
if not page.lang:
out.append(("FAIL", "lang", "<html> has no lang attribute"))
if not page.viewport:
out.append(("FAIL", "viewport", "no viewport meta"))
return out or [("PASS", "head", f"lang={page.lang}, viewport set")]
def check_sections(page):
missing = [s for s in SECTIONS if s not in page.ids]
if missing:
return [("FAIL", "sections", "missing id(s): " + ", ".join(missing))]
unlinked = [s for s in SECTIONS if s not in page.toc_links]
if unlinked:
return [("FAIL", "toc", "<nav> lacks link(s) to: "
+ ", ".join(unlinked))]
return [("PASS", "sections", "4 sections, all linked from the TOC")]
def question_problems(index, question):
text = question.get("q", "") if isinstance(question, dict) else ""
if not str(text).strip():
return [f"Q{index} has no text"]
options = question.get("options")
if not isinstance(options, list) or len(options) < 3:
return [f"Q{index} needs 3 options or more"]
out = []
right = [o for o in options
if isinstance(o, dict) and o.get("correct") is True]
if len(right) != 1:
out.append(f"Q{index} needs exactly one correct option")
for number, option in enumerate(options, 1):
filled = isinstance(option, dict) and all(
str(option.get(k, "")).strip() for k in ("text", "why"))
if not filled:
out.append(f"Q{index} option {number} lacks text or why")
return out
def load_quiz(page):
try:
quiz = json.loads(page.quiz_text or "")
except ValueError as err:
return None, f"quiz-data is missing or not JSON ({err})"
if not isinstance(quiz, list) or len(quiz) != 5:
count = len(quiz) if isinstance(quiz, list) else "not a list"
return None, f"want 5 questions, got {count}"
return quiz, None
def check_quiz(page):
quiz, error = load_quiz(page)
if error:
return [("FAIL", "quiz", error)]
problems = [p for i, q in enumerate(quiz, 1)
for p in question_problems(i, q)]
if problems:
return [("FAIL", "quiz", "; ".join(problems))]
return [("PASS", "quiz", "5 questions, one right answer each, explained")]
def quiz_strings(page):
quiz, error = load_quiz(page)
if error:
return []
out = []
for question in quiz:
if isinstance(question, dict):
out.append(str(question.get("q", "")))
for option in question.get("options") or []:
if isinstance(option, dict):
out += [str(option.get("text", "")),
str(option.get("why", ""))]
return out
def check_code_blocks(page):
out = []
if page.pre_bad_tags:
tags = ", ".join(sorted(page.pre_bad_tags))
out.append(("FAIL", "escaping",
f"markup <{tags}> inside <pre>: code left unescaped?"))
text = "".join(page.pre_text)
if BOX_DRAWING.search(text):
out.append(("FAIL", "ascii-art", "box-drawing characters in <pre>"))
elif ASCII_BOX.search(text):
out.append(("WARN", "ascii-art", "a <pre> looks like an ASCII box"))
return out or [("PASS", "code", "code blocks escaped, no ASCII diagram")]
def check_prose(page, src):
out = []
text = "".join(page.prose) + " ".join(quiz_strings(page))
dashes = text.count(EM_DASH)
if dashes:
out.append(("FAIL", "em-dash", f"{dashes} em-dash(es) in the prose"))
if "{{" in src:
out.append(("FAIL", "placeholders", "template placeholder left"))
return out or [("PASS", "prose", "no em-dash, no placeholder left")]
def run_checks(path, src, page):
return (check_name(path) + check_location(path)
+ check_self_contained(src) + check_head(page)
+ check_sections(page) + check_quiz(page)
+ check_code_blocks(page) + check_prose(page, src))
def main(argv):
if len(argv) != 2:
print(__doc__.strip())
return 2
path = Path(argv[1]).expanduser().resolve()
try:
src = path.read_text(encoding="utf-8")
except (OSError, UnicodeDecodeError) as err:
print(f"ERROR cannot read {path}: {err}")
return 2
page = Page()
page.feed(src)
page.close()
results = run_checks(path, src, page)
for level, name, detail in results:
print(f"{level} {name}: {detail}")
failed = sum(1 for level, _, _ in results if level == "FAIL")
print(f"{'FAIL' if failed else 'OK'}: {failed} failing check(s)")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+5
View File
@@ -0,0 +1,5 @@
[
{"id": 1, "prompt": "Explique-moi le commit c11cd3b du mod model-router, j'ai pas suivi pourquoi il fallait sonder le modèle de session. Fais-moi une page HTML que je puisse relire.", "expected": "Resolves the sha, reads register.ts around the probe and its test, French page dated in ~/Documents/explanations/claude/, 4 sections with TOC, 5-question quiz, checker exit 0, reply gives path + one-line summary, no chat dump"},
{"id": 2, "prompt": "fais-moi une page html qui explique la branche bugfix/guest-hints mergée dans ~/Documents/game", "expected": "Merge resolved as first-parent diff of the branch; UI mock of the hint before (indice indisponible) and after; flow guest -> session -> hint RPC with toy data; tests explained; checker exit 0"},
{"id": 3, "prompt": "Explain commit 6371523 in ~/Documents/faunosteo, I want something I can read on my phone tonight", "expected": "English page; 24-file diff triaged and grouped by concern, not file order; config and doc files summarized; responsive layout; 5-question quiz; checker exit 0"}
]