Skip to content

An AI skill that turns books into animated, narrated, interactive web experiences

feat(skill): dialog-first intake anchored by style.json

yzr4e4b3ce04236
diff --git a/.claude/skills/papermorph/SKILL.md b/.claude/skills/papermorph/SKILL.md
index 2c3efd7..6d956a9 100644
--- a/.claude/skills/papermorph/SKILL.md
+++ b/.claude/skills/papermorph/SKILL.md
@@ -5,9 +5,11 @@ description: Make or edit animated, narrated, interactive web books from referen
# Papermorph
-Make the picture explain the idea through change: rearrange, split, balance, count, compare. Each chapter is one 1600×900 SVG stage plus controls; **beats** pair narration clips with timed actions. Quick checks and final practice happen inside the picture. Templates supply mechanics; choose the visual argument for the content.
+Each chapter is a short animated lesson film: the picture carries the explanation, the narration says it, and quick checks and practice happen inside the picture. Good means **alive** (things act and change with weight and timing), **composed** (each moment reads as one picture, text beside what it names), **true** (motion, labels and numbers agree at every moment) and **smooth** (it plays without stutter, Firefox included). Technically a chapter is one 1600×900 SVG stage plus a player; **beats** pair narration clips with timed actions.
-Follow the pipeline forward, entering at the requested stage for existing work. User requests override defaults. Default to code/SVG artwork; record any other asset choices in the book's conventions. Re-create explanations, examples and drawings; keep source PDFs, page images and extracted text outside the static output folder and out of version control (`.gitignore`: `*.pdf`, `books/*/pages/`). Deliver a self-contained book folder with a cover, contents, chapters and local preview instructions.
+What the picture should be depends on the book and on the user, so the work starts with a conversation ([intake.md](references/intake.md)) that ends in `style.json`, the book's agreed style. Every chapter is made against it. Then read the reference for the technique in use: [diagrams.md](references/diagrams.md) (symbols and diagrams that change), [scenes.md](references/scenes.md) (illustrated scenes, actors, camera), [assets.md](references/assets.md) (shared components, images, sprites), [authoring.md](references/authoring.md) (chapter shape, narration, questions), [engine.md](references/engine.md), [review.md](references/review.md), [site.md](references/site.md).
+
+Follow the pipeline forward, entering at the requested stage for existing work. User requests override defaults. Re-create explanations, examples and drawings; keep source PDFs, page images and extracted text outside the static output folder and out of version control (`.gitignore`: `*.pdf`, `books/*/pages/`). Deliver a self-contained book folder with a cover, contents, chapters and local preview instructions.
## Project layout
@@ -15,46 +17,45 @@ Follow the pipeline forward, entering at the requested stage for existing work.
books/<book>/
book.pdf, sections.json source and page map (private)
pages/chNN/text.md, *.png extracted reference material (private)
- BOOK.md current scope, conventions, helper index
+ style.json the agreed style every chapter anchors to (assets/templates/style.json)
chapters.md chapter map and status
- chapters/chNN.md brief storyboard, relevant errata and feedback
+ chapters/chNN.md storyboard, errata, feedback
+ images/ inbox, SOURCES.md, image-requests.md, processing scripts
+ review/chNN/ storyboard sheets, strips, check output
content/<book>/chNN/ narration.<lang>.json and TTS cache
-tools/<book>/ targeted tests when needed
-site/ static output; private sources stay outside
- <book>/index.html cover + contents (assets/templates/book.html)
- <book>/unit-art.js unit sketches (assets/templates/unit-art.js)
- <book>/lib/engine.*, volume.* the shared engine, copied from assets/engine/ by scripts/sync_engine.py
- <book>/lib/book.css this book's engine settings and style overrides
- <book>/chNN/index.html a lesson (assets/templates/chapter.html)
- <book>/chNN/audio/<lang>/ beat MP3s + timings.js
+tools/<book>/ tests and evidence scripts
+site/<book>/ the static book (only this is delivered)
+ index.html, unit-art.js cover + contents, unit sketches
+ lib/engine.*, volume.* the engine, copied into the book by scripts/engine.py
+ lib/book.css this book's engine settings and style overrides
+ lib/*.js, img/ the book's element library and images
+ chNN/index.html, audio/<lang>/ a lesson, its beat MP3s + timings.js
```
-`SKILL` means this skill's absolute folder; `<book>` is the book slug, `<lang>` its primary language code. Existing books keep their paths. Needs: `uv`, `ffmpeg`/`ffprobe`, Edge TTS network access and Playwright Chromium (`uv run --with playwright playwright install chromium`). Preview: `python3 -m http.server 8765 -d site`.
+`SKILL` means this skill's absolute folder; `<book>` is the book slug, `<lang>` its primary language code. Existing books keep their paths. Needs: `uv`, `ffmpeg`/`ffprobe`, Edge TTS network access and Playwright browsers (`uv run --with playwright playwright install chromium firefox`). Preview: `python3 SKILL/scripts/serve.py 8765 site` (no browser caching).
## Pipeline
-Resolve intake, book map and pilot decisions with the user; reuse answers and approvals already given.
+Start with intake whenever `books/<book>/style.json` does not exist yet; reuse answers and approvals already given.
-1. **Intake.** Choose a slug; create `books/<book>/BOOK.md` from the template. Record readers, tone, primary language, scope and assets/guide. Ask for missing decisions together, with defaults.
-2. **Split.** Run `uv run --with pymupdf SKILL/scripts/outline.py books/<book>/book.pdf`; use `--level N -o books/<book>/sections.json` at chapter depth. For a PDF without usable chapter bookmarks, inspect `split_pages.py … --pages 1-12 --out books/<book>/pages`, then write the map from its contents (schema: `outline.py --help`). Match the map to the contents; extract chapter text with `split_pages.py … --sections books/<book>/sections.json --out books/<book>/pages --text-only`.
-3. **Book map.** Read contents and chapter openings; inspect more text where the scope is unclear. Create `chapters.md` with columns `# | Title | Unit | Minutes | Status` (planned, ready, user-approved); put colours and candidate recurring visual models in BOOK.md. Confirm the list and visual approach with the user.
-4. **Initialize.** Follow [site.md](references/site.md#start-a-book-folder) to copy the book engine, cover/contents and chapter skeleton before making the pilot.
-5. **Pilot.** Make chapter 1 through the chapter loop. Deliver it for the user's review and record approved conventions in BOOK.md. Implement helpers as needed; share one when another chapter uses it.
-6. **Remaining chapters and finish.** Produce chapters sequentially (see *Context*). Complete cover text, contents and unit sketches using [site.md](references/site.md). Deliver the static book folder, its entry URL for local preview and any unresolved issues for human review; reuse each chapter's delivery results.
+1. **Split.** Run `uv run --with pymupdf SKILL/scripts/outline.py books/<book>/book.pdf`; use `--level N -o books/<book>/sections.json` at chapter depth. For a PDF without usable chapter bookmarks, inspect `split_pages.py … --pages 1-12 --out books/<book>/pages`, then write the map from its contents (schema: `outline.py --help`). Extract chapter text with `split_pages.py … --sections books/<book>/sections.json --out books/<book>/pages --text-only`.
+2. **Intake.** Follow [intake.md](references/intake.md): find the PDF with the user, say what the book is, agree on one chapter to try and a tier, settle the look the way that tier needs, and write `style.json`.
+3. **Initialize.** Follow [site.md](references/site.md#start-a-book-folder); build agreed shared components once into the book's library ([assets.md](references/assets.md)) and list them in `style.json`.
+4. **Pilot.** Make the chosen chapter through the chapter loop and deliver it for the user's judgement. Fold their feedback into `style.json` and record the chapter under `approved`.
+5. **Remaining chapters and finish**, when the user wants the whole book: write `chapters.md`, produce chapters sequentially (see *Context*), complete cover text, contents and unit sketches using [site.md](references/site.md). Deliver the static book folder, its entry URL for local preview and any unresolved issues.
## Chapter loop
-1. **Read** this chapter's `pages/chNN/text.md`; render its pages with `split_pages.py … --only chNN` when diagrams or missing text need images. Select the ideas and examples to teach.
-2. **Storyboard** in `chapters/chNN.md`: beat list, visual changes, narration triggers and questions. Use [authoring.md](references/authoring.md) for content conventions; verify the examples and answers used in the finished chapter.
-3. **Narration**: write `content/<book>/chNN/narration.<lang>.json`, then `uv run --with edge-tts SKILL/scripts/tts.py content/<book>/chNN/narration.<lang>.json site/<book>/chNN/audio/<lang>`.
-4. **Beats**: implement the storyboard in `site/<book>/chNN/index.html`; API and replay invariants are in [engine.md](references/engine.md). Use the book's approved look and interactions.
-5. **Delivery pass**: follow [review.md](references/review.md) once for loading, opening blanks, overlap/cropping, text density and colour consistency. Correct clear defects locally, recheck the affected part, then deliver; report unresolved problems. The user reviews overall aesthetics, pacing and teaching effectiveness.
-6. **Register**: add the ready chapter to `UNITS`, set the previous chapter's `CHAPTER.next`, update its row in `chapters.md` and notes in `chapters/chNN.md`. Promote new shared decisions to BOOK.md. The coordinator owns this step when using subagents.
+1. **Read** this chapter's `pages/chNN/text.md`; render pages with `split_pages.py … --only chNN` when diagrams or missing text need images. Choose the ideas, examples and sections to teach.
+2. **Beats and narration**: list beats in `chapters/chNN.md` with what each says and which word triggers which action ([authoring.md](references/authoring.md)). Write `content/<book>/chNN/narration.<lang>.json`, then `uv run --with edge-tts SKILL/scripts/tts.py content/<book>/chNN/narration.<lang>.json site/<book>/chNN/audio/<lang>`.
+3. **Storyboard, layout first**: in the real page, place everything for one to three key moments per beat, real elements at their real sizes, no motion yet. Capture them into one sheet with `strip.py` and give each frame one line: what it says and where the eye goes. That sheet is the storyboard. Note what the chapter needs beyond the library: draw it, or add it to the image requests.
+4. **Motion**: add the motion, the camera and the questions; API and replay invariants are in [engine.md](references/engine.md).
+5. **Delivery pass**: watch your output in motion and judge it as a viewer would, against the storyboard; then run the checks in [review.md](references/review.md). Correct what you find, recheck, deliver; report unresolved problems.
+6. **Register**: add the chapter to `UNITS`, set the previous chapter's `CHAPTER.next`, update `chapters.md` and `chapters/chNN.md`. Promote new shared decisions and recurring elements to `style.json` and the library. The coordinator owns this step when using subagents.
## Context
-- Keep the pilot in the main conversation. Afterwards, use one fresh subagent per chapter sequentially when available; otherwise use the same chapter loop in the current agent with file-based state.
-- Brief with chapter number, relevant map row, book/source/output paths, Skill path and current user requests. Pass these instead of full conversation history where the host supports fresh context. Worker reads BOOK.md and its chapter notes, completes steps 1–5, and returns files, delivery result, errata and new helpers/decisions in a few lines. Coordinator registers it.
+- Keep intake and the pilot in the main conversation. Afterwards, use one fresh subagent per chapter sequentially when available; otherwise run the same loop in the current agent with file-based state.
+- A worker needs little besides this Skill and `style.json`: the user's words, the look, the approved chapters to watch and read, the element library. A brief adds the chapter number, its pages and any current user request. The worker returns files, delivery result, errata and new elements or decisions in a few lines; the coordinator registers it.
- Read only the reference needed for the current step. Use the engine API and inspect individual functions when needed; copy assets rather than reading their full source as instructions.
-- Keep BOOK.md to current conventions and the helper index. Chapter status, errata and historical feedback stay in their own files; read only relevant entries.
-- Write from the storyboard in one pass. Use contact sheets and short command summaries; retain failure details. Run targeted interaction tests when the engine or grading changes, as described in review.md.
+- Keep `style.json` current and short. Chapter status, errata and historical feedback stay in `chapters.md` and `chapters/chNN.md`.
diff --git a/.claude/skills/papermorph/assets/templates/BOOK.md b/.claude/skills/papermorph/assets/templates/BOOK.md
deleted file mode 100644
index 0e9c551..0000000
--- a/.claude/skills/papermorph/assets/templates/BOOK.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# <Book title> — book plan
-
-Read this compact current state for chapter work. The chapter map/status lives in `chapters.md`; storyboards, errata and feedback live in `chapters/chNN.md`.
-
-## Intake
-- Readers: … · Tone: … · Narration language: … · Guide character: …
-- Slug: … · Primary language code: … · Asset approach: code/SVG by default, or agreed assets.
-- Source: `book.pdf` · Page map: `sections.json` · N pages, N chapters in N units.
-
-## Conventions (approved in the pilot; later chapters follow them)
-- Look: palette, fonts, how a new idea enters, how steps are laid out …
-- Narration: voice, rate, how numbers and symbols are read …
-- Questions: placement, typical types, feedback style …
-- Subject conventions (definitions, notation, rounding) …
-
-## Visual models / available helpers
-- … (candidate model, chapters using it, helper name and file once implemented)
-
-## Current decisions
-- … (fold approved changes into conventions above; chapter feedback stays with its chapter)
diff --git a/.claude/skills/papermorph/assets/templates/book.html b/.claude/skills/papermorph/assets/templates/book.html
index 427ef4f..ca824b2 100644
--- a/.claude/skills/papermorph/assets/templates/book.html
+++ b/.claude/skills/papermorph/assets/templates/book.html
@@ -215,8 +215,10 @@ main#contents { padding-bottom: 80px; }
<script>
'use strict';
-// Chapters are numbered in order through the units. Add a chapter here when its lesson is ready.
-const UNITS = [ // [unit title, [[chapter title, minutes], ...]]; chapters are numbered in order. Add a chapter when its lesson is ready.
+// Units and chapters are numbered in order from START (a book whose scope starts mid-way keeps the original numbers).
+// Add a chapter here when its lesson is ready.
+const START = { unit: 1, chapter: 1 };
+const UNITS = [ // [unit title, [[chapter title, minutes], ...]]
['First unit', [['First chapter', 8]]],
];
const HUES = ['#f4a48c', '#86c9e8', '#f3c95c', '#e8a0c8', '#8fd6b0', '#bba8ee', '#f0b45a'];
@@ -230,22 +232,22 @@ try {
const done = new Set(Array.isArray(P.done) ? P.done.filter(n => Number.isInteger(n) && n > 0) : []);
// Contents.
-let n = 0, total = 0, i = 0; // i staggers the entrance, in reading order
+let n = START.chapter - 1, total = 0, i = 0; // i staggers the entrance, in reading order
const esc = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;');
document.getElementById('units').innerHTML = UNITS.map(([name, chs], u) => {
- return `<section class="unit" style="--c:${HUES[u % HUES.length]};--i:${i++}"><svg class="unit-art" viewBox="0 0 600 180" aria-hidden="true">${UNIT_ART[u] || ''}</svg><h2><span>Unit ${u + 1}</span>${esc(name)}</h2><div class="grid">` +
- chs.map(([t, min]) => { n++;
+ return `<section class="unit" style="--c:${HUES[u % HUES.length]};--i:${i++}"><svg class="unit-art" viewBox="0 0 600 180" aria-hidden="true">${UNIT_ART[u] || ''}</svg><h2><span>Unit ${u + START.unit}</span>${esc(name)}</h2><div class="grid">` +
+ chs.map(([t, min]) => { n++; total++;
const cls = 'ch' + (done.has(n) ? ' done' : '') + (P.last === n ? ' last' : '');
return `<a class="${cls}" id="${id(n)}" href="${id(n)}/" style="--i:${i++}"><b>${n}</b><span>${esc(t)}</span><small>${min} min</small></a>`;
}).join('') + '</div></section>';
}).join('');
-total = n;
// A unit's sketch draws itself the first time the unit scrolls into view.
const seen = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) { e.target.classList.add('seen'); seen.unobserve(e.target); } }), { threshold: .25 });
document.querySelectorAll('.unit').forEach(u => seen.observe(u));
-const finished = [...done].filter(k => k <= total).length;
+const finished = [...done].filter(k => k >= START.chapter && k <= n).length;
document.getElementById('prog').innerHTML = finished ? `<b>${finished}</b> of ${total} finished` : `${total} chapter${total === 1 ? '' : 's'}`;
-document.getElementById('meta').textContent = `${total} chapters · ${UNITS.length} units · with sound`;
+const pl = (k, w) => `${k} ${w}${k === 1 ? '' : 's'}`;
+document.getElementById('meta').textContent = `${pl(total, 'chapter')} · ${pl(UNITS.length, 'unit')} · with sound`;
const last = Number.isInteger(P.last) && document.getElementById(id(P.last));
if (last) {
const r = document.getElementById('resume');
diff --git a/.claude/skills/papermorph/assets/templates/e2e.py b/.claude/skills/papermorph/assets/templates/e2e.py
index ba6f824..ff29b23 100644
--- a/.claude/skills/papermorph/assets/templates/e2e.py
+++ b/.claude/skills/papermorph/assets/templates/e2e.py
@@ -1,61 +1,87 @@
-"""Optional interaction-test example; adapt the cases to the behavior being changed.
+"""Chapter checks, derived from BEATS: playback, replay of every lesson beat, quiz card layout at two viewport sizes,
+the answers, practice and finish card. Copy to tools/<book>/e2e_chNN.py and fill ANSWERS; add checks of your own
+(readouts that must agree with the motion at a moment, wrong-answer feedback) where the chapter needs them.
- python3 -m http.server 8765 -d site &
- URL=http://localhost:8765/BOOK/chNN/ uv run --with playwright tools/BOOK/e2e_chNN.py
-
-Beat numbers follow BEATS in the chapter page. Run relevant existing cases after engine changes.
+ python3 SKILL/scripts/serve.py 8765 site &
+ URL=http://localhost:8765/BOOK/chNN/ uv run --with playwright tools/BOOK/e2e_chNN.py # BROWSER=firefox too
"""
import asyncio, os
from playwright.async_api import async_playwright
-CH = "ch01"
-URL = os.environ.get("URL", f"http://localhost:8765/{CH}/index.html")
+URL = os.environ.get("URL", "http://localhost:8765/BOOK/ch01/")
+# Question beat id -> keys for each question in turn: '1'..'9' picks a choice; '=a,b' fills the boxes and checks.
+ANSWERS = {"q1": ["=7"], "final1": ["1"]}
+# The frame reached by seeking straight to t equals the one reached by stepping through the beat (replays are exact).
+SAME_FRAME = r"""
+([i, t]) => {
+ const snap = () => scene.innerHTML.replace(/(cam)\d+/g, '$1#').replace(/(\d+\.\d{2})\d+/g, '$1');
+ seek(i, false); P.t = t; evalTo(t); const a = snap();
+ seek(i, false); for (let u = 0; u < t; u += 1 / 60) evalTo(u); evalTo(t);
+ return a === snap();
+}
+"""
+# The open quiz card: prompt width and lines, every control inside the card, card bottom on the 900-high stage.
+CARD = r"""
+() => {
+ const st = document.getElementById('stage').getBoundingClientRect(), k = st.width / 1600;
+ const c = document.querySelector('.card.quiz'), cr = c.getBoundingClientRect(), pr = c.querySelector('.prompt').getBoundingClientRect();
+ const lines = pr.height / (parseFloat(getComputedStyle(c.querySelector('.prompt')).lineHeight) * k);
+ const ctl = [...c.querySelectorAll('.opt, input.box, .btn:not([hidden])')].map(b => b.getBoundingClientRect());
+ const inside = b => b.width > 0 && b.left >= cr.left - 1 && b.right <= cr.right + 1 && b.top >= cr.top - 1 && b.bottom <= cr.bottom + 1;
+ return { promptW: pr.width / k, lines, ok: ctl.length > 0 && ctl.every(inside), bottom: (cr.bottom - st.top) / k };
+}
+"""
async def main():
async with async_playwright() as p:
- b = await p.chromium.launch(args=["--autoplay-policy=no-user-gesture-required"])
+ ff = os.environ.get("BROWSER") == "firefox"
+ b = await (p.firefox.launch(firefox_user_prefs={"media.autoplay.default": 0}) if ff else p.chromium.launch(args=["--autoplay-policy=no-user-gesture-required"]))
pg = await b.new_page(viewport={"width": 1440, "height": 900})
errs = []
pg.on("pageerror", lambda e: errs.append(str(e)))
pg.on("console", lambda m: m.type == "error" and errs.append(m.text))
- await pg.goto(URL); await pg.wait_for_timeout(400)
- ev = pg.evaluate
-
- async def keys(*ks):
- for k in ks:
- await pg.keyboard.press(k); await pg.wait_for_timeout(60)
-
- async def typed(*vals): # fills answer boxes in order (Tab between them)
- for i, v in enumerate(vals):
- if i: await keys("Tab")
- await pg.keyboard.type(v); await pg.wait_for_timeout(40)
-
- async def at(i): # jump to beat i, playing
- await ev(f"seek({i}, true)"); await pg.wait_for_timeout(250)
-
- async def ok():
- assert "Correct" in await pg.inner_text(".card .fb"), await pg.inner_text(".card .fb")
-
- score = lambda k: ev(f"SCORE['{k}'] && SCORE['{k}'].right") # first-try score of question id k
- await keys("Space"); await pg.wait_for_timeout(1500)
- assert await ev("P.playing && P.t > .5"), "lesson plays"
-
- await at(2) # q1: wrong first, then right
- await typed("6"); await keys("Enter"); assert await score("c-first") == 0
- await pg.locator(".box").nth(0).fill("7"); await keys("Enter"); await ok()
- await keys("Enter"); assert await ev("P.i") == 3
-
- await at(4) # practice: one wrong, then Show answer (Esc first if a box has focus)
- await keys("2"); assert await score("p-one") == 0
- await keys("s"); assert "Answer" in await pg.inner_text(".card .fb")
- await keys("Enter"); await pg.wait_for_timeout(200)
- assert f"chapter {int(CH[2:])} complete" in (await pg.inner_text(".card")).lower()
- await keys("r"); await pg.wait_for_timeout(200); assert await ev("P.i") == 0 # Enter on the finish card opens the next chapter
-
- for i in range(await ev("BEATS.length")): # every beat must rebuild without errors
- await ev(f"seek({i}, false)")
+ await pg.goto(URL); await pg.wait_for_timeout(600)
+ ev, key = pg.evaluate, (lambda k: pg.keyboard.press(k))
+ ids = await ev("BEATS.map(b => b.id)")
+ asks = await ev("BEATS.map(b => !!b.ask)")
+
+ await key("Space"); await pg.wait_for_timeout(2500)
+ assert await ev("P.playing && P.t > 1"), "lesson plays"
+ await key("Space"); t1 = await ev("P.t"); await pg.wait_for_timeout(600)
+ assert await ev(f"!P.playing && P.t === {t1}"), "pause freezes"
+
+ for i, bid in enumerate(ids):
+ if asks[i]: continue
+ d = await ev(f"TIMINGS['{bid}'].dur")
+ for t in (round(d * .55, 2), round(d - .3, 2)):
+ assert await ev(SAME_FRAME, [i, t]), f"beat {bid} at {t} s replays the same frame"
+
+ for vw, vh in [(1280, 800), (1920, 1080)]:
+ await pg.set_viewport_size({"width": vw, "height": vh})
+ for i, bid in enumerate(ids):
+ if not asks[i] or bid == "finish": continue
+ await ev(f"seek({i}, true)"); await pg.wait_for_timeout(700)
+ m = await ev(CARD)
+ assert m["promptW"] > 400 and m["lines"] <= 4 and m["ok"] and m["bottom"] <= 901, (vw, bid, m)
+ await pg.set_viewport_size({"width": 1440, "height": 900})
+
+ for bid, steps in ANSWERS.items():
+ await ev(f"seek({ids.index(bid)}, true)"); await pg.wait_for_timeout(500)
+ for s in steps:
+ if s.startswith("="):
+ for j, v in enumerate(s[1:].split(",")): await pg.locator(".card input.box").nth(j).fill(v)
+ await key("Enter")
+ else: await key(s)
+ assert "Correct" in await pg.inner_text(".card .fb"), (bid, s)
+ await key("Enter"); await pg.wait_for_timeout(250)
+ assert await ev("BEATS[P.i].id") == "finish" and await pg.is_visible(".card.fin"), "practice leads to the finish card"
+ n = await ev("CHAPTER.number")
+ assert f"chapter {n} complete" in (await pg.inner_text(".card.fin")).lower()
+ assert n in (await ev("JSON.parse(localStorage.getItem(BOOK_PROGRESS_KEY))"))["done"], "chapter marked done"
+
+ for i in range(len(ids)): await ev(f"seek({i}, false)") # every beat rebuilds without errors
assert not errs, errs
- print(f"{CH} keyboard walk-through passed")
+ print(f"{URL} ({len(ids)} beats, {'firefox' if ff else 'chromium'}): playback, replay, quiz layout, answers, finish - passed")
await b.close()
asyncio.run(main())
diff --git a/.claude/skills/papermorph/assets/templates/style.json b/.claude/skills/papermorph/assets/templates/style.json
new file mode 100644
index 0000000..951a2ca
--- /dev/null
+++ b/.claude/skills/papermorph/assets/templates/style.json
@@ -0,0 +1,26 @@
+{
+ "schema": 1,
+ "tier": 2,
+ "book": { "title": "Book title", "slug": "physics", "language": "en", "readers": "middle school, first physics course", "pilot": "ch10" },
+ "words": [
+ "The user's own words about the look, verbatim.",
+ "ch10 feedback: later words that changed the bar, with the chapter they came from."
+ ],
+ "look": {
+ "palette": { "board": "#1f2b27", "ink": "#f2efe6", "accent": ["#e5533d", "#3d8be5"] },
+ "meaning": { "force": "#e5533d", "velocity": "#3d8be5" },
+ "fonts": { "text": "system UI", "math": "serif (engine default)" },
+ "notation": "SI units with a space (6 N); round to one decimal; say 'newtons' in narration"
+ },
+ "voice": { "engine": "edge", "voice": "en-US-AndrewMultilingualNeural", "rate": "-4%" },
+ "pacing": { "minutes": [6, 10], "checks": "one or two quick checks inside the lesson, practice at the end" },
+ "engine": { "source": "DozenTwelve/Papermorph", "ref": "main" },
+ "scenes": {
+ "art": "pixel scenes on a dark board, characters about a third of the stage tall",
+ "cast": [{ "name": "Mia", "look": "short hair, red jacket", "file": "site/physics/img/mia.png" }],
+ "storyboard": "the user reviews the layout sheet before motion in the pilot; later chapters self-check"
+ },
+ "components": [{ "name": "forceArrow", "file": "site/physics/lib/physics.js", "what": "arrow from a contact point, label on the arrow, length = magnitude" }],
+ "images": { "sources": ["drawn in code", "web images under CC0/CC-BY, credited in img/CREDITS.md"] },
+ "approved": [{ "chapter": "ch10", "why": "whole-frame composition; actors perform the push" }]
+}
diff --git a/.claude/skills/papermorph/references/assets.md b/.claude/skills/papermorph/references/assets.md
new file mode 100644
index 0000000..6a112f3
--- /dev/null
+++ b/.claude/skills/papermorph/references/assets.md
@@ -0,0 +1,20 @@
+# Assets: shared components and chapter needs
+
+What a book's pictures are made of comes from its content and the look the user chose, never from a default set. Two levels keep that consistent without making every book look alike.
+
+## Book level: the element library
+
+During intake ([intake.md](intake.md)) the shared components are proposed to the user with how each is made, and their look is agreed. Build each once into the book's library, `site/<book>/lib/<name>.js` (loaded after `engine.js`), drawn around its own origin and placed with `put`, with a short API (`f.set(x, y, len, angle, label)`, `actor.stride('walk', dist)`, `actor.hand()`). List it under `components` in `style.json`: name, file, one line on what it does. A fix to a shared element lifts every chapter at once, so after changing one, compare frames of approved chapters before and after. Keep chapter-specific drawing in the chapter; promote it when a second chapter needs it.
+
+## Chapter level: needs noticed while storyboarding
+
+Laying out a chapter's moments shows what the library lacks: a new prop, a place, a real photograph or map. Draw it in the chapter when code can; otherwise add it to `books/<book>/images/image-requests.md` (what, where it appears, size and view, style, licence needed) for the user or a sourcing pass. Anything that turns out to recur moves into the library.
+
+## Mechanics, whatever the style
+
+- Incoming files go to `books/<book>/images/inbox/` with `SOURCES.md` (origin URL, author, licence). Prefer public-domain or CC0/CC-BY; record attribution for anything that requires it.
+- A processing script in `books/<book>/images/` turns them into `site/<book>/img/` (crop, recolour, scale, compress), so every output can be rebuilt; `SKILL/scripts/sprites.py` has the common steps: integer nearest-neighbour scaling, colour mapping, pixel art from text rows, and assembling frames into one sheet with a JSON layout. Credits for the published images go in `site/<book>/img/CREDITS.md`.
+- Sprite animation: put a character's frames in one sheet and switch frames by changing a nested `<svg>`'s viewBox; changing an `<image href>` per frame can refetch. Pixel art is drawn at an integer scale with `image-rendering: pixelated` and pre-scaled files.
+- One large detailed object (a planet, a map) is cheaper as a single image than as many shapes; see the Firefox notes in [engine.md](engine.md#performance-firefox).
+
+Image-model generation is not part of the pipeline yet; it will come with picture-book and documentary looks.
diff --git a/.claude/skills/papermorph/references/authoring.md b/.claude/skills/papermorph/references/authoring.md
index cca6239..397bb44 100644
--- a/.claude/skills/papermorph/references/authoring.md
+++ b/.claude/skills/papermorph/references/authoring.md
@@ -2,7 +2,7 @@
## Shape
-The algebra book used roughly 5–11 minute chapters and 5–40 second beats. Let the content determine length and the number of checks/practice sets.
+Chapters have run 5–18 minutes with 5–40 second beats; a long chapter can hold several parts (each a short title beat, lessons, a quick check and a wrap). Let the content determine length and the number of checks/practice sets.
| Beat | Purpose |
| --- | --- |
@@ -10,30 +10,18 @@ The algebra book used roughly 5–11 minute chapters and 5–40 second beats. Le
| lesson beats | One idea each, built up in the picture while the narration explains it. |
| `q1`, `q2`, … | A check of already taught content, separated from the next check by a lesson beat. |
| `wrap` | Three or four numbered takeaways. |
-| `final1` … | Consecutive full-screen practice sets labelled "Chapter practice N of M", covering the whole chapter. |
+| `final1` … | Full-screen practice covering the whole chapter. With several sets, label them like `'Chapter practice, set 1 of 2 · question'` (the engine appends "k of n"). |
| `finish` | Score card (`finishCard`): first-try results for quick checks and practice. |
Beat ids are shared by the page (`BEATS`) and the narration file; a beat with `ask` waits for the answers before moving on.
-## Storyboard
+## Beats
-Before writing code, list the beats. For each lesson beat decide:
+Before writing code, list the beats. For each lesson beat decide what the eye should watch and what changes; why that change is true (the animation is the argument); which words trigger which actions (these become `[[marks]]`); what text appears, beside the thing it names; and what carries over from the previous beat. Then lay out the key moments as pictures (storyboard): [diagrams.md](diagrams.md) and [scenes.md](scenes.md).
-- what the eye should watch, and what changes;
-- why that change is true (the animation is the argument, not decoration);
-- which words trigger which actions (these become `[[marks]]`);
-- what text appears on screen: the key formula, rule or label, placed beside the thing it names;
-- what is still on screen from the previous beat, and what fades.
-
-Principles that held up over a whole book:
-
-- **Open on the subject.** When a beat clears the picture, the new topic (expression, diagram, question) appears right away; labels and steps then follow the words. The engine moves an opening group forward if nothing appears in the first 0.8 s, but design for it. Normal transitions and short pauses for thought are fine; the picture need not move all the time.
-- **One new thing at a time.** Don't introduce several objects, colours and texts at once.
-- **Balance explanation and decoration.** Favour objects and camera moves that carry the idea (the thing that moves, the reference it moves against, the cut that changes the point of view). Some atmosphere is welcome; keep it light so it never crowds the concept, distracts, or costs smooth playback. Judge each scene as a whole: trim extras (a bystander, dense scenery, stacked parallax layers, a flourish move) rather than strip it bare.
-- **Same colour, same meaning** within a chapter (and, where it fits, across the book).
-- **Be exact where it matters.** Number lines, grids and areas are to scale. Illustrative scenes (planets, people on Earth) need only be clear to the reader; add a scale note only when the size could mislead. Approximations are written as approximations (≈ 4.47…, never = 4.47).
-- **Teach the chapter's scope.** If the book jumps ahead or uses something not yet taught, leave it out or say so.
-- **Show the common mistake** where one exists (e.g. squaring the coefficient too), visually crossed out, then the right way.
+- **Open on the subject.** When a beat clears the picture, the new topic appears right away; labels and steps follow the words. Short pauses for thought are fine.
+- **One new thing at a time**, and **the same colour means the same thing** across the chapter and, where it fits, the book.
+- **Teach the chapter's scope**, choosing sections by idea; note any reordering in `chapters/chNN.md`.
## Narration
@@ -45,11 +33,10 @@ Principles that held up over a whole book:
```
- `[[name]]` goes right before the word an action waits for; `m('name', offset)` in the page returns when that word starts. Names are unique within a beat; a misspelt mark makes the page throw, and a mark that matches no spoken word makes `tts.py` stop.
-- Write for the ear: short sentences, one idea each. Say math in words ("negative seven halves", "x squared"); the picture shows the symbols.
+- Write for the ear: short sentences, one idea each. Say symbols and units in words ("negative seven halves", "meters per second squared"); the picture shows the symbols.
- Match the audience: plain, warm, never childish. Explain why, not only how.
- Question beats get one short line ("Quick check. Find the mean."); the card holds the question.
-- `tts.py` caches word timings beside the narration JSON; the output folder receives `<beat>.mp3` and `timings.js` (duration, marks, sentence captions). Moving or adding `[[marks]]` reuses the spoken-text cache and recalculates timings. Existing caches made with raw-text keys are reused for an unchanged beat and then upgraded; changing its marks before that upgrade may require one new synthesis.
-- Audio is replaced only after synthesis and timing validation succeed, and each completed beat is cached immediately. After a later failure, rerun the same command to reuse completed beats rather than regenerating the chapter.
+- `tts.py` writes `<beat>.mp3` and `timings.js` (duration, marks, captions) and caches each finished beat beside the narration JSON: moving `[[marks]]` reuses the cache, and after a failure the same command resumes rather than starting over.
## Questions
@@ -71,9 +58,11 @@ New types are welcome when the content calls for one; each needs keyboard play (
- Feedback: right → `why` (and an animation via `fx`/`onRight`); wrong → a hint aimed at that mistake; after a wrong try, Show answer.
- Grade meaning: equal values match (6/8 = 3/4) unless the lowest form is asked for; sets and pairs in any order; no denominators of zero; never judge irrationality from finitely many digits.
- The built-in numeric parser uses safe integer numerators and denominators and exact integer products for equality. For answers outside that range, use a subject-specific input and grader rather than allowing rounded values to pass.
-- Place cards so they don't cover the object being asked about (`BAND` under a number line, `TOPR` top right, a custom `{x, y, w, cls: 'side'}` beside a figure, `SCREEN` for practice).
+- Compose the question beat for its card: the picture the question is about stays visible (for example in the top 60 % with a `BAND` card below, or beside a `{x, y, w, cls: 'side'}` card); `SCREEN` for practice.
+- Units in typed answers: write the unit as a word after the box (`{ box: '60' }, ' kilograms'`) so it is not set as a math variable.
## Content rules
- Follow the agreed chapter scope and order. Verify facts, calculations and answers actually used in the finished lesson; correct or replace source errors and note them in `books/<book>/chapters/chNN.md` for the user.
-- Use BOOK.md's definitions, notation and rounding conventions. Record new shared decisions there.
+- Check worked examples as the subject, not only as arithmetic (a push on someone standing on the ground is not the net force).
+- Use the notation and rounding in `style.json` (`look.notation`). Record new shared decisions there.
diff --git a/.claude/skills/papermorph/references/diagrams.md b/.claude/skills/papermorph/references/diagrams.md
new file mode 100644
index 0000000..9514678
--- /dev/null
+++ b/.claude/skills/papermorph/references/diagrams.md
@@ -0,0 +1,11 @@
+# Symbols and diagrams that change
+
+For abstract and procedural ideas (the maths books on the showcase site). The picture explains through change: things are rearranged, split, balanced, counted and compared while the narration says why. The change is the argument, so each move must be one the idea allows.
+
+- **One reading line.** A derivation or a procedure reads in one direction, each step under or beside the last, aligned on what stays the same (the `=` sign, the place values). The eye never searches for the next step.
+- **Change the thing, don't replace it.** Tokens that combine move together and collapse into the result (`tokens`, `collapse`); a tile pair cancels where it stands; a dot hops along the number line. A fresh line of text is a weaker picture than the old one transforming.
+- **Exact where it matters.** Number lines, grids, areas and graphs are to scale; illustrative pictures only need to be clear. Approximations are written as approximations (≈ 4.47…, never = 4.47).
+- **Show the common mistake** where one exists (squaring the coefficient too), visibly crossed out, then the right way.
+- **Vary the composition with the content.** A chapter that is one centred formula after another feels monotonous; a number line, a table, a picture of the quantity and a worked line each have their own layout.
+
+Storyboard these beats like any other: place the key moments in the real page and capture them with `strip.py` before timing the moves ([scenes.md](scenes.md#storyboard-layout-first-then-motion)). The engine's maths helpers (number lines, tiles, fraction rows, planes, data plots) are listed in [engine.md](engine.md#drawing).
diff --git a/.claude/skills/papermorph/references/engine.md b/.claude/skills/papermorph/references/engine.md
index 83e8e34..8ecc0b9 100644
--- a/.claude/skills/papermorph/references/engine.md
+++ b/.claude/skills/papermorph/references/engine.md
@@ -2,9 +2,9 @@
A chapter page loads the engine and its `audio/<lang>/timings.js`, defines `CHAPTER` (including `language` when different from `en`), drawing helpers, `BEATS` and questions, then calls `boot()`. The engine provides the stage, drawing, timeline, question types, guide and player. Use the code's signatures if they differ from this reference.
-Every book keeps a copy of the shared engine in `lib/` (`engine.*`, `volume.*`), so the book runs on its own. Change the engine in `assets/engine/`, then copy it to the books with `python3 SKILL/scripts/sync_engine.py site` (`--check` lists copies that differ); a book's copy is not edited by hand. The book's own settings and style overrides live in `lib/book.css`, imported by `engine.css` and never overwritten: `--math-font` for numbers and formulas, `--progress-key` when the cover uses a key other than the default.
+Every book keeps a copy of the shared engine in `lib/` (`engine.*`, `volume.*`), so the book runs on its own. The engine is not part of this skill: it lives in the `engine/` folder of the Papermorph repository (or a fork), versioned by tags. `python3 SKILL/scripts/engine.py site` copies it into every book (`--check` lists copies that differ, `--from DIR|OWNER/REPO@REF` picks the source); a book's copy is not edited by hand. An engine bug is fixed at the source, then synced. The book's own settings and style overrides live in `lib/book.css`, imported by `engine.css` and never overwritten: `--math-font` for numbers and formulas, `--progress-key` when the cover uses a key other than the default.
-Many helpers are mathematical because the first book was algebra. Use those that fit, implement new ones in the chapter as needed, and move what several chapters use into the book's own library file (`lib/<name>.js`), not into the engine copy.
+Many drawing helpers are mathematical because the first book was algebra. Use those that fit; draw the rest in the chapter, and move what several chapters use into the book's element library (`lib/<name>.js`, [assets.md](assets.md)) rather than into the engine copy.
## Stage and state
@@ -12,7 +12,7 @@ Many helpers are mathematical because the first book was algebra. Use those that
- Every animated element carries a state object written to the DOM by `render()`: `x y` (translate), `s` (scale), `r` (rotate, degrees), `o` (opacity), `d` (stroke drawn, 0–1), `a_<attr>` (numeric attribute, e.g. `'a_stroke-width'`), `c_<attr>` (hex colour). Give a key a starting value before tweening it; an `a_`/`c_` key without one starts from the element's attribute.
- Scale and rotation are about the element's own origin: draw around (0,0) and place with `x/y`.
- `S` holds objects shared across beats (`S.panel`, `S.line`, …). `reset()` clears it, so anything a later beat needs must be stored on `S`.
-- Palette `COL`: `chalk dim faint task good bad board` plus six hues `nat whole int rat irr real`. Fonts: `UI` (text), `MATH` (serif unless the book's `--math-font` says otherwise).
+- Palette `COL`: `chalk dim faint task good bad board` plus six hues named `nat whole int rat irr real` (from the algebra book; give them the book's own meanings in `style.json` `look.meaning`, e.g. `const FORCE = COL.…`). Fonts: `UI` (text), `MATH` (serif unless the book's `--math-font` says otherwise).
## Drawing
@@ -71,6 +71,8 @@ Firefox repaints SVG on the main thread and is the slowest common browser for th
- Large shapes under a big camera zoom or roll are expensive: a filled `<circle>` scaled 6× and rotating cost about 200 ms a frame in Firefox, while the same picture as one `<image>` cost about 3 ms. Prefer one image for a big detailed object (a planet, a map), and few elements over many small ones (merge cells into one path per colour, or use an image).
- Write per-frame attributes and text only when they change (`render()` already skips unchanged transform and opacity). Old panels are set to `display: none` after their fade.
- Pixel-art sprites: draw `<image>` with `style="image-rendering: pixelated"` at an integer scale, and pre-scale the file (nearest neighbour) so it stays crisp where the style is ignored.
+- Cross-fading two full-screen cameras costs a long frame: fade only the incoming one in over the outgoing one, then hide the old.
+- A question card's entrance after a busy scene can hitch; measure it with `perf.py`.
## Questions
@@ -78,7 +80,7 @@ Firefox repaints SVG on the main thread and is the slowest common browser for th
quiz(position, [{ id: 'c-mean', prompt: ['Find the mean of ', $m('7, 3, 9'), '.'], build: blanks([...]) }, …], done, 'Quick check')
```
-- Positions: `BAND` (below a number line, y 686–886), `TOPR` (top right, ≤ 470 high), `RIGHT`, `SCREEN` (full-screen practice; label `'Chapter practice N of M'`), `SORT_SCREEN`, or any `{x, y, w, cls: 'side'}`.
+- Positions: `BAND` (bottom band, y 686–886; long content can push it past the stage, so check it), `TOPR` (top right, ≤ 470 high), `RIGHT`, `SCREEN` (full-screen practice; label `'Chapter practice N of M'`), `SORT_SCREEN`, or any `{x, y, w, cls: 'side'}`.
- `choice(options, right, why, wrongWhys[], onRight?)` — number keys.
- `blanks(rows)` — rows `{parts: [..., {box: '21'}, ...], why, hint?, fx?, test?}`; accepts −5, 3/4, 2 1/4, 0.75 as exact values; `{box, lowest: true}` demands lowest terms; `test(values)` judges the whole row (e.g. two factors in either order). Tab moves between boxes, Enter checks, Esc leaves a box.
- `grid(rows, cols, {multi, text})` — rows `{parts, ans: [keys], why, fx?}`, cols `[[key, label, colour?, hotkey?]]`; with `text: true` parts are rich text (math via `$m`). ↑/↓ change rows.
diff --git a/.claude/skills/papermorph/references/intake.md b/.claude/skills/papermorph/references/intake.md
new file mode 100644
index 0000000..bb3b492
--- /dev/null
+++ b/.claude/skills/papermorph/references/intake.md
@@ -0,0 +1,66 @@
+# Intake: from a PDF to one agreed chapter
+
+A cold agent with only a PDF has no idea what the user wants, and its guesses diverge from run to run. Intake closes that gap through a short conversation and writes the outcome to `books/<book>/style.json`, the anchor every chapter is made against. The schema fixes *what* the book looks and sounds like; *how* each moment is animated stays free.
+
+The conversation should feel light: the user tries one chapter first and decides about the rest of the book after seeing it.
+
+## Asking
+
+- Many users want to click, not type. Every point where you need the user, from finding the PDF to approving the finished chapter, is a choice: two to four concrete options drawn from this book, the recommended one first and labelled so, so that accepting every recommendation still makes a good book. Use the structured question tool when there is one (at most four questions a round); otherwise number the options so a single digit answers. Their own words are always welcome, never required.
+- Questions come from this book and this chapter, not from a form. Skip what the material or earlier answers already settle.
+- After each round, say the answers back as decisions in one or two lines, then move on.
+- Keep what the user says about the look **verbatim** in `words`; later chapters need their taste, not a summary of it. When they only pick options, record the chosen options' wording.
+
+## 1. Welcome and the PDF
+
+Greet briefly as Papermorph. Look for PDFs in the working folder and its subfolders (then the user's Downloads and Desktop if none are found) and ask "Is it this one?", listing up to four candidates. If none are found, offer to search another folder or to take a path. Choose a short slug and place the file at `books/<book>/book.pdf`, a copy or a link.
+
+## 2. What this book is
+
+Run the split ([SKILL.md](../SKILL.md#pipeline), step 1) and read the contents, the preface and the `text.md` of two or three chapter openings across the book. Say in two or three sentences what the book is: subject, readers, how it teaches. Then offer a chapter to try: name two or three candidates with one line each on what they would show, recommending one that is representative rather than the gentlest opening (a light introduction can pass while hiding the hard problems). A section of a long chapter is fine.
+
+## 3. Tier
+
+Offer the animation tiers as reference points. The published books at https://papermorph.diamonddoge.org/ show the first two; link them.
+
+1. **Diagrams that change**: symbols, number lines, graphs and shapes built in code, rearranged as the narration explains (the maths books). Lightest: about 100k tokens a chapter, works on a smaller model.
+2. **Illustrated scenes**: characters act out the idea, the camera moves, external images and a storyboard before motion (the science book). About 400k tokens a chapter on a large model.
+3. **Picture book**: coming, not available yet.
+4. **Documentary**: coming, not available yet.
+5. **Custom**: the user describes what they want; you judge which abilities it needs and say so.
+
+Recommend one from the chapter's content: abstract and procedural ideas fit tier 1 ([diagrams.md](diagrams.md)); physical and narrative ones fit tier 2 ([scenes.md](scenes.md)). Mixing per beat is allowed under any tier.
+
+## 4. The look, by tier
+
+**Tier 1** needs few decisions. Propose palette, fonts and the language and voice from the book itself. Then make the chapter's narration and its first one or two beats, laid out at real size ([SKILL.md](../SKILL.md#chapter-loop), steps 2–3), and capture a few key frames with `strip.py`. Show the sheet and ask: go ahead as it is (recommended), or one of two or three concrete changes (calmer, more colour, larger type …). Once agreed, write `style.json` and make the chapter.
+
+**Tier 2** has more to settle; ask in rounds:
+1. Art and sources: drawn in code, pixel scenes, illustrated, real images; whether web images (with credits) are acceptable. The recurring characters: propose two or three casts that suit the book, each in one line.
+2. Shared components: list the things this chapter, and the chapters around it, will draw again and again (in the science book: force arrows, crates, the actors), each with what it must do and how it would be made. Offer them as one multiple-choice question, recommending the ones that recur most, for which to build once for the whole book ([assets.md](assets.md)).
+3. The storyboard: lay out the key moments without motion and show the sheet ([scenes.md](scenes.md#storyboard-layout-first-then-motion)). Ask: add motion now (recommended), or a few concrete changes to named frames. Motion comes after the user agrees.
+
+**Custom**: ask what the description leaves open, using the closest tier's rounds and options.
+
+## 5. style.json
+
+Start from [the template](../assets/templates/style.json). Blocks are grouped by ability, not by tier; a tier is just which blocks are present:
+
+| Block | What it holds | Present in |
+|---|---|---|
+| `schema`, `tier`, `book` | schema version; `1`, `2` or `"custom"`; title, slug, language, readers, pilot chapter | all |
+| `words` | the user's own words about the look, verbatim, with later feedback that changed the bar | all |
+| `look` | palette, what each colour means, text and maths fonts, notation and rounding | all |
+| `voice` | TTS engine (`edge`), voice, rate | all |
+| `pacing` | minutes per chapter, where checks and practice go | all |
+| `engine` | engine source and version used to build the book | all |
+| `scenes` | art style, cast, how storyboards are reviewed | tier 2 |
+| `components` | shared elements: name, file, what each does | tier 2, tier 1 when the book has some |
+| `images` | where images may come from, credit rules | tier 2 |
+| `approved` | chapters the user approved and what each shows well | filled as chapters are approved |
+
+Leave out blocks the tier does not use. Later tiers add their own blocks (for example `illustration` or `footage`) beside these; a reader that meets a block it does not know reads it as plain intent. Increase `schema` only when an existing field changes meaning.
+
+Deliver the pilot with a choice: approve and make the rest of the book (recommended when it is good), approve and stop here, or one of two or three concrete changes you would make yourself. Fold the answer and any feedback into `words` and the affected block, and add an approved chapter to `approved`. Approved chapters are the strongest anchor: later chapters watch and read them as worked examples.
+
+When continuing, write `chapters.md` (`# | Title | Pages | Minutes | Status`: planned, ready, user-approved) and go on with the remaining chapters.
diff --git a/.claude/skills/papermorph/references/review.md b/.claude/skills/papermorph/references/review.md
index 5c4f59d..36a47b1 100644
--- a/.claude/skills/papermorph/references/review.md
+++ b/.claude/skills/papermorph/references/review.md
@@ -1,35 +1,33 @@
# Delivery pass
-Serve `site/` over HTTP. Use this pass once per chapter; inspect relevant frames, fix clear defects locally and recheck those parts. Deliver for the user's assessment of overall aesthetics, pacing and teaching effectiveness.
+Serve `site/` with `python3 SKILL/scripts/serve.py 8765 site` (no browser caching, so an engine edit is never hidden by a stale file). Use this pass once per chapter: watch, fix what you find, recheck those parts, then deliver for the user's judgement of aesthetics, pacing and teaching. Keep the evidence in `books/<book>/review/chNN/`.
-## Frames and opening blanks
+## Watch it in motion
```sh
-uv run --with playwright --with pillow SKILL/scripts/shot.py chNN --url http://localhost:8765/<book>/ --out /tmp/animebook-<book>
-uv run --with playwright SKILL/scripts/check_blank.py site/<book> chNN --url http://localhost:8765/<book>/
+uv run --with playwright --with pillow SKILL/scripts/strip.py chNN OUT --url http://localhost:8765/<book>/ push/0.25 law3/0.5@w
```
-`shot.py` captures open/end frames as 4-up sheets and reports console errors. Read the sheets once; use `shot.py chNN 5:7.5` for a specific transition or correction. Add `--moments mid` when intermediate geometry needs a frame. Run one screenshot browser at a time.
+A strip shows one beat at small steps; `@w` adds a motion WebP. Look at each action as a viewer would: do actors perform what the narration says, do props stay on the hands, does the camera move with purpose, does each frame still match the storyboard, do arrows, labels and readouts agree with the motion? Then watch a few beats live in Firefox with sound, which is how the user watches.
+
+## Frames and openings
-Make a brief judgment of:
+```sh
+uv run --with playwright --with pillow SKILL/scripts/shot.py chNN --url http://localhost:8765/<book>/ --out OUT
+uv run --with playwright SKILL/scripts/check_blank.py site/<book> chNN --url http://localhost:8765/<book>/
+uv run --with playwright SKILL/scripts/overlap.py chNN --url http://localhost:8765/<book>/
+```
-- the picture empty or unrelated at `open`;
-- text over drawings, labels colliding, anything clipped or off the stage;
-- a question card covering the object it asks about;
-- leftovers from the previous beat, half faded;
-- geometry contradicting the intended values, spacing or area;
-- shapes inside circles or curves crossing the outline; check thin geometry on the full-size `chNN_bII_T.png`, not only on the sheet;
-- text too small to read at half size, or too much text at once;
-- inconsistent colours for the same idea.
+`shot.py` captures open/end frames of every beat as 4-up sheets and reports console errors. Look for an empty or unrelated opening, text over drawings or clipped at the edge, a card covering what it asks about, leftovers half faded, geometry contradicting its values, shapes inside circles or curves crossing the outline (check thin geometry on the full-size `chNN_bII_T.png`, not only the sheet), text too small at half size or too much at once, and the same idea in different colours. `check_blank.py` reports openings empty for more than a second after speech starts. `overlap.py` samples every beat and lists where an arrow runs through text or two texts collide, with times, so you can look at exactly those frames.
-The blank check reports openings empty for more than 1 second after speech starts (`LIMIT=0.6` for a stricter pass). Resolve reported openings in the beat. Preserve ordinary transitions and thinking pauses.
+## Smoothness
-Report the delivery result and any unresolved defects in a few lines. A new visual redesign starts with user feedback.
+`uv run --with playwright SKILL/scripts/perf.py chNN --url …` measures frame times in Firefox, which repaints SVG on the main thread and is the slowest common browser for these pages; headless Chromium hides paint cost. Look at the worst beats and transitions; the remedies are in [engine.md](engine.md#performance-firefox).
-## Targeted interaction tests
+## Interaction tests
-For changes to playback, question types or grading, run existing tests that exercise the changed behavior. If needed, adapt `assets/templates/e2e.py` into `tools/<book>/e2e_chNN.py`; set `URL` to the actual chapter URL. Check the relevant wrong/right feedback, Show answer and continuation, or pause/replay/seek behavior. Shared timing/replay changes warrant the whole book's blank check and existing affected tests; ordinary new chapters use the delivery pass above.
+Adapt `assets/templates/e2e.py` into `tools/<book>/e2e_chNN.py`: it checks playback, that every beat replays the same frame when seeked, that quiz cards stay readable and on stage at two viewport sizes, and walks the answers, practice and finish card. Run it in Chromium and with `BROWSER=firefox`. Run existing tests of approved chapters after changing the book's engine or library.
-For scoring changes, verify a wrong first attempt stays recorded after leaving and revisiting the question, and that restarting clears it. For progress changes, check book isolation and loading with missing or malformed stored data. Make common engine fixes in `assets/engine/` and copy them to the books with `scripts/sync_engine.py`; book-specific settings stay in each book's `lib/book.css`.
+After scoring changes, check a wrong first try stays recorded after revisiting and a restart clears it; after progress changes, check book isolation and missing or malformed stored data. Fix engine bugs at the engine source and copy them to the books with `scripts/engine.py`; book-specific settings stay in each book's `lib/book.css`.
-Test details: keyboard first, plus mouse for changed drag handling; Enter checks and Esc leaves answer boxes; press Esc before S. Multi-row questions score per row. Use R on the finish card (Enter opens the next chapter). Python's server lacks Range requests, so let audio play naturally instead of setting `audio.currentTime`.
+Test details: keyboard first (Enter checks, Esc leaves a box, press Esc before S, R replays on the finish card); a page opened with `?beat=` is not started, so start it before pressing keys; `seek(i, false)` stops before the old panel's fade, so seek playing or evaluate past it; compare text in lower case (CSS uppercases kickers); avoid assertions on totals that grow with the book; Python's server lacks Range requests, so let audio play rather than setting `currentTime`.
diff --git a/.claude/skills/papermorph/references/scenes.md b/.claude/skills/papermorph/references/scenes.md
new file mode 100644
index 0000000..10d1636
--- /dev/null
+++ b/.claude/skills/papermorph/references/scenes.md
@@ -0,0 +1,38 @@
+# Illustrated scenes
+
+For physical, spatial and narrative ideas: people and things act out the idea, the camera shows what matters, and the words live inside the picture (the science book on the showcase site).
+
+## Each moment is one picture
+
+The subject comes first, large and placed where the eye lands; text is part of the picture and appears beside what it names, as it is said. A layout with a title row, a picture somewhere else and notes in a column feels fragmented ("割裂", the user's word) even when every piece is correct.
+
+Worked example, the push in the science book's chapter 10:
+- *Before*: a small pusher and cart at the bottom left, the sentence at the top centre, the word "push" floating far from both, and an arrow above the cart rather than on it. Every piece was right; nothing read as one picture.
+- *After*: the actor three times larger with the cart against her hands; the force arrow starts at the hands and runs through the cart, its label "push · 6 N" on the arrow; the sentence sits just above the actor. The eye goes actor, arrow, words.
+
+Vary the composition with the content (a close-up, a wide shot, a split screen, a view from above) rather than repeating one template; a chapter made of the same frame over and over felt monotonous. Some atmosphere is welcome when it stays light: favour objects and moves that carry the idea, and trim a bystander, dense scenery or a flourish that competes with it.
+
+## Storyboard: layout first, then motion
+
+1. With narration and beats written, place everything for one to three key moments per beat in the real page: real elements at their real sizes, positions written as the moment's values, no tweens yet.
+2. Capture those moments into one sheet (`strip.py chNN OUT force:push,dir net:add … --sheet storyboard`; times may be marks). Write one line per frame in `chapters/chNN.md`: what it says and where the eye goes. That sheet is the storyboard; composition is cheapest to change now.
+3. In the pilot the user reviews the sheet before motion is added. In later chapters it is your own check and stays as evidence in `books/<book>/review/chNN/`.
+4. Add motion and camera so that the picture passes through those compositions, then compare finished frames with the sheet.
+
+## Actors and actions
+
+When the narration says someone pushes, throws or jumps, they perform it with weight and timing, and what they handle moves with them. A figure sliding across the ground like a statue reads as a still picture, not an action; the user objected to that strongly.
+- Drive gait frames from the distance travelled, so the feet keep pace with the ground.
+- Keep contact as a shared position: the prop follows the hand position of the current frame; a ball is caught, held and released through it.
+- Time poses to narration marks (wind-up before "kick", contact on it), and derive motion constants from the marks when an action must land on a word.
+- When a sprite set has too few poses, draw frames from a simple skeleton rather than going without the action ([assets.md](assets.md)).
+
+## The camera tells the story
+
+Establish the scene, push in at the moment of contact, pull back for the result, follow a moving subject, switch views (side to top, split screen) to reveal structure. One purposeful move per beat is usually enough. Labels that must stay readable live in screen space and track their object (`cam.track`). See [engine.md](engine.md#world-clock-and-camera).
+
+## True at every moment
+
+Motion, arrows, labels and numbers state the same thing at the same moment. A force is drawn while it acts and disappears when contact ends; an accelerating object keeps accelerating while its label says so, so size the demonstration to the narration rather than clamping it at the frame edge; readouts come from the same function of time as the motion. Check worked numbers as the subject, not just as arithmetic. Scale realism is not needed; clarity for the reader is.
+
+Still frames hide frozen actors and drifting timing; watch each action in motion before calling it done ([review.md](review.md#watch-it-in-motion)).
diff --git a/.claude/skills/papermorph/references/site.md b/.claude/skills/papermorph/references/site.md
index 6246c51..6107535 100644
--- a/.claude/skills/papermorph/references/site.md
+++ b/.claude/skills/papermorph/references/site.md
@@ -10,17 +10,17 @@ Set `SKILL` to the installed skill folder. Run once for a new slug; use an exist
BOOK_ID=history
BOOK_SITE="site/$BOOK_ID"
BOOK_WORK="books/$BOOK_ID"
-mkdir -p "$BOOK_SITE/lib" "$BOOK_SITE/ch01" "$BOOK_WORK/chapters" "content/$BOOK_ID/ch01" "tools/$BOOK_ID"
-python3 "$SKILL/scripts/sync_engine.py" "$BOOK_SITE" # the shared engine into lib/, plus lib/book.css for this book's settings
+mkdir -p "$BOOK_SITE/lib" "$BOOK_SITE/img" "$BOOK_SITE/ch01" "$BOOK_WORK/chapters" "$BOOK_WORK/images/inbox" "content/$BOOK_ID/ch01" "tools/$BOOK_ID"
+python3 "$SKILL/scripts/engine.py" "$BOOK_SITE" # the engine into lib/, plus lib/book.css for this book's settings
cp "$SKILL/assets/templates/book.html" "$BOOK_SITE/index.html"
cp "$SKILL/assets/templates/unit-art.js" "$BOOK_SITE/unit-art.js"
cp "$SKILL/assets/templates/chapter.html" "$BOOK_SITE/ch01/index.html"
cp "$SKILL/assets/templates/narration.en.json" "content/$BOOK_ID/ch01/narration.en.json"
```
-Use the agreed primary language: rename the narration source, load `audio/<lang>/timings.js`, and set `CHAPTER.language` to match (default `en`). Choose the voice and translate the template's visible UI text as needed before the pilot.
+Use the pilot chapter's number in place of `ch01` when the pilot is not the first chapter. Use the agreed primary language: rename the narration source, load `audio/<lang>/timings.js`, and set `CHAPTER.language` to match (default `en`). Take `voice` and `rate` for each narration file from `style.json`, and translate the template's visible UI text as needed before the pilot.
-Each book has its own engine copy (kept in step with `sync_engine.py`, see [engine.md](engine.md)), source materials, narration and optional tests. The engine and cover derive the same progress key from the book's URL folder. Keep existing books on their current paths; their legacy progress remains intact.
+Each book has its own engine copy (kept in step with `engine.py`, see [engine.md](engine.md)), source materials, narration and optional tests. The engine and cover derive the same progress key from the book's URL folder. Keep existing books on their current paths; their legacy progress remains intact.
A chapter returns to its book's index. Preserve cover → contents → chapter navigation and the return from contents to cover. The book opens directly at `/<book>/`; it needs no parent index page. Keep existing books' navigation when editing them.
@@ -29,7 +29,7 @@ A chapter returns to its book's index. Preserve cover → contents → chapter n
One page: no hash or `#book` shows the cover, `#contents` or `#chNN` the contents; a lesson's home button returns to `#chNN`, and the card grows into the lesson frame through a view transition.
- Edit the title, kicker, lede, the faint chalk phrases on the cover (a few formulas or lines from the book), and the `<title>`.
-- `UNITS`: `[unit title, [[chapter title, minutes], …]]`; chapters are numbered in order. Add a chapter when its lesson is ready; also set the previous chapter's `CHAPTER.next = '../chNN/'`.
+- `UNITS`: `[unit title, [[chapter title, minutes], …]]`; chapters are numbered in order from `START` (`{ unit: 1, chapter: 1 }`; a book whose scope starts mid-way, e.g. at unit 3, chapter 9, keeps the original numbers). Add a chapter when its lesson is ready; also set the previous chapter's `CHAPTER.next = '../chNN/'`.
- `HUES`: one colour per unit, cycling.
## Unit sketches (`unit-art.js`)
@@ -45,7 +45,7 @@ Keep the existing infinity guide by default. For an agreed custom guide, adapt `
Serve the static output over HTTP for audio playback:
```sh
-python3 -m http.server 8765 -d site
+python3 SKILL/scripts/serve.py 8765 site # no-store, so edits are never hidden by the browser cache
```
Open `http://localhost:8765/<book>/`. Confirm the cover opens the contents, ready chapter links load their lessons, and lessons return to the book's contents. Deliver `site/<book>/` with its HTML, scripts, styles and audio, the preview command and entry URL, available chapter count and unresolved issues. Source PDFs, extracted pages, narration drafts and development environments are not part of the static book.
diff --git a/.claude/skills/papermorph/scripts/check_blank.py b/.claude/skills/papermorph/scripts/check_blank.py
index 50f9627..5aef543 100644
--- a/.claude/skills/papermorph/scripts/check_blank.py
+++ b/.claude/skills/papermorph/scripts/check_blank.py
@@ -9,7 +9,7 @@
book_dir holds the chNN folders; --url is where that folder is served. For each lesson beat
(question beats are skipped) whose picture stays empty longer than LIMIT seconds (default 1)
near its start, prints: chapter, beat index, beat id, empty from, empty until, seconds.
-No output means no opening blank. Exit status 1 when something is found.
+Otherwise it prints one line saying none were found. Exit status 1 when something is found.
"""
import argparse, asyncio, os, sys
from pathlib import Path
@@ -22,7 +22,7 @@ PROBE = r"""
const b = BEATS[i], tm = TIMINGS[b.id], first = (tm.cues[0] || [0])[0];
const visible = () => { // drawn leaves whose opacity, multiplied up to the scene, is above .05
let n = 0;
- for (const e of scene.querySelectorAll('text,path,circle,rect,ellipse,line,polygon')) {
+ for (const e of scene.querySelectorAll('text,path,circle,rect,ellipse,line,polygon,image')) {
if (e.closest('.qlayer')) continue;
let o = 1, x = e;
while (x && x !== scene) { o *= +(x.getAttribute('opacity') ?? 1); if (x.style && x.style.visibility === 'hidden') o = 0; x = x.parentNode; }
@@ -59,6 +59,7 @@ async def main(book: Path, chapters, url):
await browser.close()
for row in found:
print(*row)
+ if not found: print(f"no opening blanks in {', '.join(chapters)}")
return 1 if found else 0
diff --git a/.claude/skills/papermorph/scripts/overlap.py b/.claude/skills/papermorph/scripts/overlap.py
new file mode 100644
index 0000000..1363912
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/overlap.py
@@ -0,0 +1,132 @@
+#!/usr/bin/env python3
+"""Arrow/text overlap finder: samples every lesson beat and reports where an arrow runs through text, or text sits on text.
+
+ uv run --with playwright overlap.py ch09 ch10 [--url http://localhost:8765/<book>/] [--step 0.25] [--json OUT.json] [--beat ID]
+
+An arrow is any path whose last subpath is a three-point head ending where the shaft ends (e.g. `M x y L x2 y2 M … L x2 y2 L …`).
+Points every 3 px along each visible arrow (shaft and head, widened by half the stroke) are tested against the ink
+box of each visible text (getBBox trimmed to the glyph band, tested in the text's own, possibly rotated, frame).
+Text pairs count when their ink boxes overlap by more than 4 px on every axis. Hits are merged into time ranges per
+beat and element pair; look at those frames with strip.py. Runs in Firefox.
+"""
+import argparse, asyncio, json, sys
+from playwright.async_api import async_playwright
+
+MEASURE = r"""
+([i, step]) => {
+ seek(i, false);
+ const stage = document.getElementById('stage'), inv = stage.getScreenCTM().inverse();
+ const vis = el => { // effective opacity, 0 if hidden
+ let o = 1;
+ for (let e = el; e && e !== stage; e = e.parentNode) {
+ if (e.style && (e.style.display === 'none' || e.style.visibility === 'hidden' || e.style.opacity === '0')) return 0;
+ const a = e.getAttribute && e.getAttribute('opacity'); if (a !== null && a !== undefined) o *= +a;
+ if (o < .15) return 0;
+ }
+ return o;
+ };
+ const isArrow = d => {
+ const sub = d.trim().split(/(?=M)/); if (sub.length < 2) return false;
+ const head = sub[sub.length - 1].match(/-?\d*\.?\d+(?:e-?\d+)?/g), body = sub[sub.length - 2].match(/-?\d*\.?\d+(?:e-?\d+)?/g);
+ if (!head || head.length !== 6 || !body) return false;
+ // body end: last coordinate pair, or for 'H x' the x with the M's y
+ const hv = sub[sub.length - 2].includes('H');
+ const ex = +body[body.length - (hv ? 1 : 2)], ey = hv ? +body[1] : +body[body.length - 1];
+ return Math.abs(+head[2] - ex) < .5 && Math.abs(+head[3] - ey) < .5;
+ };
+ const toStage = (el) => { const m = inv.multiply(el.getScreenCTM()); return (x, y) => [m.a * x + m.c * y + m.e, m.b * x + m.d * y + m.f]; };
+ const dur = P.end, out = [];
+ for (let t = 0; t <= dur + 1e-6; t += step) {
+ P.t = t; evalTo(t);
+ const texts = [], arrows = [];
+ for (const el of scene.querySelectorAll('text')) {
+ const s = el.textContent.trim(); if (!s || !vis(el)) continue;
+ const b = el.getBBox(); if (!b.width) continue;
+ const f = toStage(el), size = parseFloat(el.getAttribute('font-size')) || 30;
+ // ink band: text sits on its local baseline y = 0 (positions are transforms); caps reach ~0.72 em above it and
+ // descenders ~0.15 em below. The bbox (full em box) is taller than the ink.
+ const top = -.72 * size, bot = .15 * size;
+ const m = inv.multiply(el.getScreenCTM()), sc = Math.hypot(m.a, m.b);
+ const q = [[b.x + 1, top], [b.x + b.width - 1, top], [b.x + b.width - 1, bot], [b.x + 1, bot]].map(([x, y]) => f(x, y));
+ const xs = q.map(p => p[0]), ys = q.map(p => p[1]);
+ if (Math.max(...xs) < 0 || Math.min(...xs) > 1600 || Math.max(...ys) < 0 || Math.min(...ys) > 900) continue;
+ // q: the ink box corners on stage (rotated text stays a rotated box); mi maps stage points back to text space
+ texts.push({ s, q, mi: m.inverse(), x0: b.x + 1, x1: b.x + b.width - 1, top, bot, sc });
+ }
+ let k = 0;
+ for (const el of scene.querySelectorAll('path')) {
+ const d = el.getAttribute('d'); if (!d || !isArrow(d)) continue;
+ const id = k++;
+ if (!vis(el) || el.style.visibility === 'hidden') continue;
+ const L = el.getTotalLength(); if (L < 4) continue;
+ const f = toStage(el), m = inv.multiply(el.getScreenCTM()), sc = Math.hypot(m.a, m.b);
+ const hw = (parseFloat(el.getAttribute('stroke-width')) || 4) * sc / 2;
+ const col = el.getAttribute('stroke'), pts = [];
+ for (let u = 0; u <= L; u += 3) { const p = el.getPointAtLength(u); pts.push(f(p.x, p.y)); }
+ arrows.push({ id: `${col}#${id}`, pts, hw });
+ }
+ for (const a of arrows) for (const r of texts) {
+ const g = a.hw / r.sc; // half the stroke, in text units
+ if (a.pts.some(([x, y]) => { const u = r.mi.a * x + r.mi.c * y + r.mi.e, v = r.mi.b * x + r.mi.d * y + r.mi.f;
+ return u > r.x0 - g && u < r.x1 + g && v > r.top - g && v < r.bot + g; }))
+ out.push([+t.toFixed(2), 'arrow', a.id, r.s]);
+ }
+ // text pairs: separating-axis test on the two ink boxes, needing 4 px of overlap on every axis
+ const proj = (q, ax) => { const d = q.map(([x, y]) => x * ax[0] + y * ax[1]); return [Math.min(...d), Math.max(...d)]; };
+ const axes = q => [0, 1].map(i => { const dx = q[i + 1][0] - q[i][0], dy = q[i + 1][1] - q[i][1], n = Math.hypot(dx, dy) || 1; return [dx / n, dy / n]; });
+ for (let p = 0; p < texts.length; p++) for (let q = p + 1; q < texts.length; q++) {
+ const A = texts[p], B = texts[q];
+ if ([...axes(A.q), ...axes(B.q)].every(ax => { const [a0, a1] = proj(A.q, ax), [b0, b1] = proj(B.q, ax); return Math.min(a1, b1) - Math.max(a0, b0) > 4; }))
+ out.push([+t.toFixed(2), 'text', A.s, B.s]);
+ }
+ }
+ return out;
+}
+"""
+
+async def run(pg, base, ch, step, only):
+ await pg.goto(f"{base}{ch}/?beat=0&t=0"); await pg.wait_for_timeout(800)
+ beats = await pg.evaluate("BEATS.map(b => [b.id, !!b.ask])")
+ res = {}
+ for i, (bid, ask) in enumerate(beats):
+ if ask or (only and bid not in only): continue
+ hits = await pg.evaluate(MEASURE, [i, step])
+ groups = {}
+ for t, kind, a, b in hits: groups.setdefault((kind, a, b), []).append(t)
+ rows = []
+ for (kind, a, b), ts in groups.items(): # merge into ranges
+ rng, s0, prev = [], ts[0], ts[0]
+ for t in ts[1:]:
+ if t - prev > step * 1.5: rng.append((s0, prev)); s0 = t
+ prev = t
+ rng.append((s0, prev))
+ rows.append({"kind": kind, "a": a, "b": b, "ranges": rng, "n": len(ts)})
+ if rows: res[bid] = rows
+ return res
+
+async def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("chapters", nargs="+"); ap.add_argument("--url", default="http://localhost:8765/")
+ ap.add_argument("--step", type=float, default=.25); ap.add_argument("--json"); ap.add_argument("--beat", action="append", default=[])
+ o = ap.parse_args()
+ args, step, jout, only, base = o.chapters, o.step, o.json, set(o.beat), o.url.rstrip("/") + "/"
+ async with async_playwright() as p:
+ b = await p.firefox.launch(firefox_user_prefs={"media.autoplay.default": 0})
+ pg = await b.new_page(viewport={"width": 1440, "height": 900})
+ errs = []; pg.on("pageerror", lambda e: errs.append(str(e)))
+ allres = {}
+ for ch in args:
+ res = allres[ch] = await run(pg, base, ch, step, only)
+ na = sum(1 for rows in res.values() for r in rows if r["kind"] == "arrow")
+ nt = sum(1 for rows in res.values() for r in rows if r["kind"] == "text")
+ print(f"== {ch}: {na} arrow/text, {nt} text/text pairs in {len(res)} beats")
+ for bid, rows in res.items():
+ for r in rows:
+ rg = ", ".join(f"{a:g}" if a == c else f"{a:g}-{c:g}" for a, c in r["ranges"])
+ print(f" {bid:14} {r['kind']:5} {r['a'][:28]!r:32} {r['b'][:40]!r:44} t={rg}")
+ await b.close()
+ if errs: print("PAGE ERRORS:", errs)
+ if jout: json.dump(allres, open(jout, "w"), indent=1)
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/.claude/skills/papermorph/scripts/perf.py b/.claude/skills/papermorph/scripts/perf.py
new file mode 100644
index 0000000..2fe01f8
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/perf.py
@@ -0,0 +1,46 @@
+#!/usr/bin/env python3
+"""Frame timings in Firefox for every lesson beat of a chapter: the clock runs on wall time (no audio) for 2 s from
+three moments in each beat (start, middle, near the end), plus every beat transition. Prints mean / p95 / max frame
+time and frames over 50 ms; the worst cases come last.
+
+ uv run --with playwright perf.py ch11 [OUT.txt] [--url http://localhost:8765/<book>/]
+"""
+import argparse, asyncio, sys
+from playwright.async_api import async_playwright
+SETUP = r"""
+() => { window.__d = []; let last = performance.now();
+ const loop = now => { window.__d.push(now - last); last = now; requestAnimationFrame(loop); }; requestAnimationFrame(loop); }
+"""
+RUN = r"""
+async ([i, t, ms]) => {
+ seek(i, true); P.afail = true; P.audio && P.audio.pause(); P.t = t < 0 ? P.end + t : t;
+ await new Promise(r => setTimeout(r, 300)); window.__d = [];
+ await new Promise(r => setTimeout(r, ms));
+ const d = window.__d.slice(1).sort((a, b) => a - b), n = d.length;
+ return { mean: +(d.reduce((a, b) => a + b, 0) / n).toFixed(1), p95: +d[Math.floor(n * .95)].toFixed(1), max: +d[n - 1].toFixed(1), over50: d.filter(x => x > 50).length };
+}
+"""
+async def main(ch, out, base):
+ async with async_playwright() as p:
+ b = await p.firefox.launch(firefox_user_prefs={"media.autoplay.default": 0})
+ pg = await b.new_page(viewport={"width": 1512, "height": 982})
+ await pg.goto(f"{base}{ch}/?beat=0&t=0"); await pg.wait_for_timeout(800)
+ await pg.evaluate(SETUP)
+ beats = await pg.evaluate("BEATS.map(b => [b.id, !!b.ask, TIMINGS[b.id].dur])")
+ res = []
+ for i, (bid, ask, dur) in enumerate(beats):
+ if ask: continue
+ for t in (.3, dur / 2, dur - 2.2):
+ res.append((f"{bid} @{t:.1f}", await pg.evaluate(RUN, [i, t, 2000])))
+ if i < len(beats) - 1: res.append((f"{bid} -> next", await pg.evaluate(RUN, [i, -1.0, 2200])))
+ await b.close()
+ res.sort(key=lambda r: (r[1]["over50"], r[1]["mean"]))
+ lines = [f"{k:28s} mean {v['mean']:5.1f} p95 {v['p95']:5.1f} max {v['max']:6.1f} >50ms {v['over50']}" for k, v in res]
+ txt = "\n".join(lines); print(txt)
+ if out: open(out, "w").write(f"Firefox (Playwright), 1512x982, {ch}\n" + txt + "\n")
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("chapter"); ap.add_argument("out", nargs="?"); ap.add_argument("--url", default="http://localhost:8765/")
+ a = ap.parse_args()
+ asyncio.run(main(a.chapter, a.out, a.url.rstrip("/") + "/"))
diff --git a/.claude/skills/papermorph/scripts/serve.py b/.claude/skills/papermorph/scripts/serve.py
new file mode 100644
index 0000000..43c46bb
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/serve.py
@@ -0,0 +1,26 @@
+#!/usr/bin/env python3
+"""Local preview without browser caching, so an edited engine or chapter is never hidden by a stale copy.
+
+ python3 serve.py 8765 site # then open http://localhost:8765/<book>/
+
+python3 -m http.server sends no Cache-Control and has a backlog of 5, which drops connections when a page opens
+many files at once; this server sends no-store and queues up to 128.
+"""
+import functools, http.server, sys
+
+class NoStore(http.server.SimpleHTTPRequestHandler):
+ def end_headers(self):
+ self.send_header("Cache-Control", "no-store")
+ super().end_headers()
+
+class Server(http.server.ThreadingHTTPServer):
+ request_queue_size = 128
+ daemon_threads = True
+
+if __name__ == "__main__":
+ if len(sys.argv) != 3:
+ print(__doc__)
+ sys.exit(0 if sys.argv[1:] in (["-h"], ["--help"]) else 2)
+ port, root = int(sys.argv[1]), sys.argv[2]
+ print(f"serving {root} at http://localhost:{port}/ (no-store)", flush=True)
+ Server(("", port), functools.partial(NoStore, directory=root)).serve_forever()
diff --git a/.claude/skills/papermorph/scripts/sprites.py b/.claude/skills/papermorph/scripts/sprites.py
new file mode 100644
index 0000000..926dbea
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/sprites.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python3
+"""Common image steps for a book's processing script, whatever the style. Import it, or use the commands:
+
+ uv run --with pillow sprites.py scale IN.png OUT.png --k 8 # integer nearest-neighbour scale
+ uv run --with pillow sprites.py recolor IN.png OUT.png --map ffd83d=bba8ee # exact colour swaps (repeat --map)
+ uv run --with pillow sprites.py art ROWS.txt OUT.png --k 8 # pixel art from text rows
+ uv run --with pillow sprites.py sheet OUT.png FRAMES.json # frames -> one sheet + layout
+
+ROWS.txt: palette lines "X=#rrggbb", then one text row per pixel row; "." is transparent.
+FRAMES.json: {"walk": ["walk1.png", "walk2.png"], "stand": ["stand.png"]}; every frame has the same size. Writes the
+sheet (a row per animation) and OUT.json {"w", "h", "anims": {name: {"row", "n"}}} for a nested-<svg> viewBox player.
+Scale pixel art last, after recolouring, so colours stay exact.
+"""
+import argparse, json
+from pathlib import Path
+from PIL import Image
+
+hexc = lambda h: tuple(int(h.lstrip("#")[i:i + 2], 16) for i in (0, 2, 4))
+
+def scale(im, k):
+ return im.resize((im.width * k, im.height * k), Image.NEAREST)
+
+def recolor(im, mapping):
+ """mapping: {(r, g, b): (r, g, b)}; exact matches on opaque pixels only."""
+ im = im.convert("RGBA"); px = im.load()
+ for y in range(im.height):
+ for x in range(im.width):
+ c = px[x, y]
+ if c[3] and c[:3] in mapping: px[x, y] = (*mapping[c[:3]], 255)
+ return im
+
+def art(rows, pal):
+ """rows: strings, one char per pixel; pal: {char: (r, g, b)}; '.' is transparent."""
+ im = Image.new("RGBA", (max(map(len, rows)), len(rows)))
+ for y, r in enumerate(rows):
+ for x, ch in enumerate(r):
+ if ch != ".": im.putpixel((x, y), (*pal[ch], 255))
+ return im
+
+def sheet(anims):
+ """anims: {name: [Image, ...]} -> (sheet, layout)."""
+ w, h = next(iter(anims.values()))[0].size
+ cols = max(len(f) for f in anims.values())
+ S = Image.new("RGBA", (w * cols, h * len(anims)))
+ layout = {"w": w, "h": h, "anims": {}}
+ for row, (name, frames) in enumerate(anims.items()):
+ for k, f in enumerate(frames): S.paste(f, (k * w, row * h))
+ layout["anims"][name] = {"row": row, "n": len(frames)}
+ return S, layout
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("cmd", choices=["scale", "recolor", "art", "sheet"]); ap.add_argument("a"); ap.add_argument("b")
+ ap.add_argument("--k", type=int, default=1); ap.add_argument("--map", action="append", default=[])
+ o = ap.parse_args()
+ if o.cmd == "scale": scale(Image.open(o.a), o.k).save(o.b, optimize=True)
+ elif o.cmd == "recolor":
+ m = dict(tuple(map(hexc, s.split("="))) for s in o.map)
+ scale(recolor(Image.open(o.a), m), o.k).save(o.b, optimize=True)
+ elif o.cmd == "art":
+ lines = [l.rstrip("\n") for l in open(o.a) if l.strip()]
+ pal = {l[0]: hexc(l[2:].strip()) for l in lines if len(l) > 2 and l[1] == "="}
+ scale(art([l for l in lines if not (len(l) > 2 and l[1] == "=")], pal), o.k).save(o.b, optimize=True)
+ else:
+ spec = json.load(open(o.b)); base = Path(o.b).parent
+ S, layout = sheet({n: [Image.open(base / f).convert("RGBA") for f in fs] for n, fs in spec.items()})
+ S.save(o.a, optimize=True); Path(o.a).with_suffix(".json").write_text(json.dumps(layout))
diff --git a/.claude/skills/papermorph/scripts/strip.py b/.claude/skills/papermorph/scripts/strip.py
new file mode 100644
index 0000000..2e1b25d
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/strip.py
@@ -0,0 +1,78 @@
+#!/usr/bin/env python3
+"""Frames of a chapter's beats on contact sheets, rendered from the beat clock: storyboard sheets and motion strips.
+
+ uv run --with playwright --with pillow strip.py ch12 OUT [specs ...] [--sheet NAME] [--url URL] [--browser chromium]
+
+ push:2.3,dir,end chosen moments of beat 'push': seconds, a narration mark (dir, dir+0.5), mid or end
+ push/0.25 a motion strip: every 0.25 s across the beat (push alone: every 1 s)
+ push/0.25@w also a motion WebP of the beat (0.25 s steps)
+ --sheet storyboard put every frame into one sheet OUT/storyboard.jpg (layout-first storyboard)
+
+Without --sheet each beat gets OUT/strip_<beat>.jpg. Frames are labelled "beat t" and shown at 1/3 size, four
+a row. Firefox by default: it is the slowest common browser and the one to judge by. --url is where the book is served.
+"""
+import argparse, asyncio, re, sys, tempfile
+from pathlib import Path
+from playwright.async_api import async_playwright
+from PIL import Image, ImageDraw
+
+def sheet(ims, path, cols=4):
+ cols = min(cols, len(ims)); W, H = ims[0].size
+ S = Image.new("RGB", (W * cols, H * ((len(ims) + cols - 1) // cols)), (20, 30, 27))
+ for k, im in enumerate(ims): S.paste(im, ((k % cols) * W, (k // cols) * H))
+ S.save(path, quality=84)
+
+async def main(a):
+ out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
+ tmp = Path(tempfile.mkdtemp()) / "f.png"
+ async with async_playwright() as p:
+ b = await (p.firefox.launch(firefox_user_prefs={"media.autoplay.default": 0}) if a.browser == "firefox" else p.chromium.launch())
+ pg = await b.new_page(viewport={"width": 1600, "height": 960})
+ errs = []; pg.on("pageerror", lambda e: errs.append(str(e)))
+ await pg.goto(f"{a.url}{a.chapter}/?beat=0&t=0"); await pg.wait_for_timeout(800)
+ async def shot(t, scale):
+ await pg.evaluate(f"P.t = {t}; evalTo({t})"); await pg.wait_for_timeout(60)
+ r = await pg.evaluate("(() => { const r = document.getElementById('stage').getBoundingClientRect(); return [r.x, r.y, r.width, r.height]; })()")
+ await pg.screenshot(path=str(tmp), clip={"x": r[0], "y": r[1], "width": r[2], "height": r[3]})
+ im = Image.open(tmp).convert("RGB")
+ return im.resize((im.width // scale, im.height // scale))
+ allims = []
+ for spec in a.specs:
+ webp = spec.endswith("@w"); spec = spec.removesuffix("@w")
+ m = re.fullmatch(r"([^:/]+)(?::(.+)|/([\d.]+))?", spec)
+ if not m: sys.exit(f"bad spec {spec!r}")
+ bid, moments, step = m.groups()
+ i = await pg.evaluate(f"BEATS.findIndex(b => b.id === '{bid}')")
+ if i < 0: sys.exit(f"no beat {bid!r}")
+ tm = await pg.evaluate(f"TIMINGS['{bid}']"); dur = tm["dur"]
+ def when(x):
+ mk = re.fullmatch(r"([A-Za-z_]\w*)([+-][\d.]+)?", x)
+ if x in ("mid", "end"): return dur / 2 if x == "mid" else dur - .05
+ if mk and mk[1] in tm.get("marks", {}): return tm["marks"][mk[1]] + float(mk[2] or 0)
+ return float(x)
+ await pg.evaluate(f"seek({i}, false)"); await pg.wait_for_timeout(300)
+ st = float(step or 1)
+ ts = [when(x) for x in moments.split(",")] if moments else [k * st for k in range(int(dur / st) + 1)]
+ ims = []
+ for t in ts:
+ im = await shot(t, 3); ImageDraw.Draw(im).text((6, 4), f"{bid} t={t:.2f}", fill=(255, 230, 120)); ims.append(im)
+ if a.sheet: allims += ims
+ else: sheet(ims, out / f"strip_{bid}.jpg")
+ if webp:
+ fr, t = [], 0.0
+ while t <= dur:
+ fr.append(await shot(t, 2)); t += .25
+ fr[0].save(out / f"motion_{bid}.webp", save_all=True, append_images=fr[1:], duration=250, loop=0, quality=60)
+ print(bid, len(ims), "frames")
+ if a.sheet and allims: sheet(allims, out / f"{a.sheet}.jpg"); print("sheet", out / f"{a.sheet}.jpg")
+ await b.close()
+ if errs: print("PAGE ERRORS:", errs); return 1
+ return 0
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("chapter"); ap.add_argument("out"); ap.add_argument("specs", nargs="+")
+ ap.add_argument("--sheet"); ap.add_argument("--url", default="http://localhost:8765/")
+ ap.add_argument("--browser", default="firefox", choices=["firefox", "chromium"])
+ a = ap.parse_args(); a.url = a.url.rstrip("/") + "/"
+ sys.exit(asyncio.run(main(a)))
diff --git a/.claude/skills/papermorph/scripts/tts.py b/.claude/skills/papermorph/scripts/tts.py
index 0ef4356..d62684c 100644
--- a/.claude/skills/papermorph/scripts/tts.py
+++ b/.claude/skills/papermorph/scripts/tts.py
@@ -207,4 +207,7 @@ async def main(src, out_dir):
if __name__ == "__main__":
+ if len(sys.argv) != 3:
+ print(__doc__)
+ sys.exit(0 if sys.argv[1:] in (["-h"], ["--help"]) else 2)
asyncio.run(main(*sys.argv[1:3]))