From b353fac2ba054277af0c036e6f72ea93a53d17e2 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sat, 17 Oct 2026 13:05:01 +0200 Subject: [PATCH 1/3] 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. --- .claude/tasks/TODO.md | 9 + CHANGELOG.md | 1 + README.md | 1 + USAGE.md | 2 + lib/profiles/dev.profile | 1 + lib/profiles/full.profile | 1 + lib/profiles/max.profile | 1 + lib/tests/explain-diff-check.test.sh | 101 ++++ mods/model-router/routing.json | 1 + skills/explain-diff/SKILL.md | 153 +++++ skills/explain-diff/assets/template.html | 549 ++++++++++++++++++ skills/explain-diff/references/components.md | 187 ++++++ .../explain-diff/scripts/check_explanation.py | 254 ++++++++ skills/explain-diff/test-prompts.json | 5 + 14 files changed, 1266 insertions(+) create mode 100755 lib/tests/explain-diff-check.test.sh create mode 100644 skills/explain-diff/SKILL.md create mode 100644 skills/explain-diff/assets/template.html create mode 100644 skills/explain-diff/references/components.md create mode 100755 skills/explain-diff/scripts/check_explanation.py create mode 100644 skills/explain-diff/test-prompts.json diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index 1761160..a50de5f 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 4e4a105..7288f3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 ` and `/route verbose on` adds `(: 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//YYYY-MM-DD-.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). diff --git a/README.md b/README.md index ef32df7..daf9aaa 100644 --- a/README.md +++ b/README.md @@ -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 | diff --git a/USAGE.md b/USAGE.md index 02c7755..3942bd0 100644 --- a/USAGE.md +++ b/USAGE.md @@ -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 / / model=… effort=… / switch on\|off / classify on\|off (classifieur de prompt) / verbose on\|off (transitions seules) | diff --git a/lib/profiles/dev.profile b/lib/profiles/dev.profile index 4c347c5..ca2ea17 100644 --- a/lib/profiles/dev.profile +++ b/lib/profiles/dev.profile @@ -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 diff --git a/lib/profiles/full.profile b/lib/profiles/full.profile index fb05c55..7e26963 100644 --- a/lib/profiles/full.profile +++ b/lib/profiles/full.profile @@ -59,6 +59,7 @@ qa-only doc personal document-release pdf-translate personal +explain-diff personal # === Session hygiene + memory ======================================== close personal diff --git a/lib/profiles/max.profile b/lib/profiles/max.profile index 426b572..055c28d 100644 --- a/lib/profiles/max.profile +++ b/lib/profiles/max.profile @@ -62,6 +62,7 @@ document-release diagram make-pdf pdf-translate personal +explain-diff personal # === Session hygiene + memory ======================================== close personal diff --git a/lib/tests/explain-diff-check.test.sh b/lib/tests/explain-diff-check.test.sh new file mode 100755 index 0000000..d64f8fb --- /dev/null +++ b/lib/tests/explain-diff-check.test.sh @@ -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 — 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": "

Text.

", + "INTUITION_BODY": "

Text with a — b.

", + "CODE_BODY": "
if (a < b) { go(); }
", + "QUIZ_INTRO": "

Five questions.

", "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 — 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" '' \ + '' +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 < b) { go(); }' \ + 'const m = new Map();' +check T10-unescaped-generic-fails "$(rc "$D-generic.html")" 1 +mutate "$OK" "$D-box.html" 'if (a < 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 ] diff --git a/mods/model-router/routing.json b/mods/model-router/routing.json index eb00b04..f14a87d 100644 --- a/mods/model-router/routing.json +++ b/mods/model-router/routing.json @@ -73,6 +73,7 @@ "hotfix": "reflect", "bugfix": "reflect", "refactor": "reflect", + "explain-diff": "reflect", "web-validate": "reflect", "harden": "reflect", "seo": "reflect", diff --git a/skills/explain-diff/SKILL.md b/skills/explain-diff/SKILL.md new file mode 100644 index 0000000..b712c4c --- /dev/null +++ b/skills/explain-diff/SKILL.md @@ -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 `), else the current one. +Map the argument to a diff: + +| Argument | Commits to read | Diff to explain | +|---|---|---| +| `` | `git log -1 ` | `git show `; a merge → `git diff ^1 `, the whole merged branch | +| `A..B` | `git log A..B` | `git diff A...B` | +| `` | `git log ..` | `git diff ...` | +| `#`, PR | `gh pr view ` | `gh pr diff ` (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` | + +`` is `develop` when it exists, else `main`, else `master`. + +No argument: on a branch ahead of its base, explain `...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 `
` blocks, HTML-escaped (`<` as `<`, `>` as `>`,
+   `&` as `&`). An unescaped `` 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//YYYY-MM-DD-.html`.
+   Today's date comes first so the folder sorts by time, `` is the
+   basename of the repo and `` 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" 
+   ```
+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 |
diff --git a/skills/explain-diff/assets/template.html b/skills/explain-diff/assets/template.html
new file mode 100644
index 0000000..574056d
--- /dev/null
+++ b/skills/explain-diff/assets/template.html
@@ -0,0 +1,549 @@
+
+
+
+
+
+
+{{TITLE}}
+
+
+
+
+ +
+

{{TITLE}}

+

{{PROJECT}} · {{RANGE}} · {{DATE}} · {{STATS}}

+

{{LEAD}}

+
+ + + +
+
+

{{BACKGROUND_TITLE}}

+ {{BACKGROUND_BODY}} +
+ +
+

{{INTUITION_TITLE}}

+ {{INTUITION_BODY}} +
+ +
+

{{CODE_TITLE}}

+ {{CODE_BODY}} +
+ +
+

{{QUIZ_TITLE}}

+ {{QUIZ_INTRO}} +
+

+
+
+ +
{{COLOPHON}}
+
+ + + + + diff --git a/skills/explain-diff/references/components.md b/skills/explain-diff/references/components.md new file mode 100644 index 0000000..03424c1 --- /dev/null +++ b/skills/explain-diff/references/components.md @@ -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 +
+ How the hint service works (skip if you + know it) +

…

+
+``` + +## 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 + + + +``` + +## 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 +
+
+
Browser + guest g-42, no session
+
ensureGuest()
+
fetchHint + new: session first
+
rpc hint(day=12)
+
Database + auth-gated RPC
+
+
After the fix: the session exists before the hint call. +
+
+``` + +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 +
+
running
+
crash ×3
+
stopped + new: final
+
+``` + +## Before and after + +```html +
+
+

Before

+

…

+
+
+

After

+

…

+
+
+``` + +## 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 +
+
Daily puzzle · day 12
+
+

Find the word in 6 tries.

+
B _ _ _ _
+
Hint
+
Hint unavailable
+
+
+``` + +`mock-alert ok` gives the success colour. + +## Toy data + +```html +
+ + + + + +
VisitorSessionHint
g-42nonerefused
+
+``` + +## Code excerpt and diff + +Show only the lines that matter, with the `path:line` above. Escape `<`, +`>` and `&` in every code block. + +```html +
+ apps/web/src/game/daily.ts:31 +
export async function fetchDailyHint(day: number) {
+  const ok = await ensureGuestSession();
+  if (!ok) return null;
+}
+
The session comes first; a failure ends in null.
+
+``` + +A diff block holds raw unified-diff lines; the template's script colours +the `+`, `-` and `@@` lines. Keep the leading `+` / `-` / space. + +```html +
+ apps/web/src/game/daily.ts +
@@ -28,6 +28,9 @@ export async function fetchDailyHint
+ export async function fetchDailyHint(day: number) {
++  const ok = await ensureGuestSession();
++  if (!ok) return null;
+   return rpc("hint", { day });
+
+``` + +## 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 ` +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-.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", " 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", "