Skip to content

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

feat(skill): package a built book as SCORM 1.2 or 2004 for an LMS

JEMe1c0288c8083
diff --git a/.claude/skills/papermorph/SKILL.md b/.claude/skills/papermorph/SKILL.md
index fecff1e..c515bb3 100644
--- a/.claude/skills/papermorph/SKILL.md
+++ b/.claude/skills/papermorph/SKILL.md
@@ -43,7 +43,7 @@ Start with intake whenever `books/<book>/style.json` does not exist yet; reuse a
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.
+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. For an LMS, package it as SCORM ([site.md](references/site.md#scorm-package-optional)).
## Chapter loop
diff --git a/.claude/skills/papermorph/assets/scorm/launch.html b/.claude/skills/papermorph/assets/scorm/launch.html
new file mode 100644
index 0000000..92e16a7
--- /dev/null
+++ b/.claude/skills/papermorph/assets/scorm/launch.html
@@ -0,0 +1,22 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>__TITLE__</title>
+<style>
+ html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
+ iframe { display: block; width: 100%; height: 100%; border: 0; }
+</style>
+<script>
+// Package settings, written by the skill's scripts/scorm.py.
+window.PAPERMORPH_SCORM_CONFIG = __CONFIG__;
+</script>
+<script src="scorm-host.js"></script>
+</head>
+<body>
+<!-- The book runs inside this frame, so moving between chapters never ends the LMS session. -->
+<iframe id="book" title="__TITLE__" allow="autoplay; fullscreen"></iframe>
+<script>PapermorphSCORM.start(document.getElementById('book'));</script>
+</body>
+</html>
diff --git a/.claude/skills/papermorph/assets/scorm/scorm-bridge.js b/.claude/skills/papermorph/assets/scorm/scorm-bridge.js
new file mode 100644
index 0000000..cad8342
--- /dev/null
+++ b/.claude/skills/papermorph/assets/scorm/scorm-bridge.js
@@ -0,0 +1,51 @@
+// Connects a Papermorph book page to the SCORM host in launch.html. scripts/scorm.py adds it to every page:
+// in the contents page's <head>, and in each chapter right after lib/engine.js (before the chapter calls boot()).
+// Outside the package wrapper it does nothing, so the book still works as a plain web book.
+'use strict';
+(function () {
+ let host = null;
+ try { host = parent !== window && parent.PapermorphSCORM; } catch {}
+ if (!host) return;
+
+ // 1. Seed the book's own progress store from the LMS, so the contents page and the chapter
+ // see the learner's saved checkmarks. This file sits in the book folder, the same folder the default key names;
+ // in a chapter, the engine's own key (BOOK_PROGRESS_KEY, which honours lib/book.css --progress-key) wins.
+ const KEY = typeof BOOK_PROGRESS_KEY === 'string' ? BOOK_PROGRESS_KEY
+ : 'animebook:progress:' + new URL('.', document.currentScript.src).pathname;
+ try { localStorage.setItem(KEY, JSON.stringify(host.progress())); } catch {}
+
+ // 2. In a chapter, every progress change and every finish goes to the host as well.
+ // engine.js's top-level functions and constants are shared globals, so they can be wrapped here.
+ if (typeof progress === 'function' && typeof finishCard === 'function') {
+ const own = progress;
+ progress = function (f) {
+ const p = host.progress();
+ f(p);
+ host.save(p);
+ own(f); // keep the page's localStorage copy in step
+ };
+ const card = finishCard;
+ finishCard = function () {
+ card.apply(this, arguments);
+ let right = 0, total = 0;
+ for (const v of Object.values(typeof SCORE === 'object' ? SCORE : {})) { right += v.right; total += v.total; }
+ host.finished(CHAPTER.number, right, total);
+ };
+ } else if (/\/ch\d\d\/[^/]*$/.test(location.pathname)) {
+ console.error('[scorm] This chapter has no progress()/finishCard() to hook; the Papermorph engine may have changed. Completion will not reach the LMS.');
+ }
+
+ // 3. LMS file servers often don't serve a folder's index.html for a folder URL like "ch02/",
+ // so point every same-site folder link at its index.html.
+ const fix = href => href.replace(/^([^?#:]*\/)(?=[?#]|$)/, '$1index.html');
+ const sameSite = href => { try { return new URL(href, location.href).origin === location.origin; } catch { return false; } };
+ const fixLink = a => {
+ const href = a.getAttribute('href');
+ if (href && sameSite(href)) { const f = fix(href); if (f !== href) a.setAttribute('href', f); }
+ };
+ document.addEventListener('click', e => { const a = e.target.closest?.('a[href]'); if (a) fixLink(a); }, true);
+ document.addEventListener('DOMContentLoaded', () => {
+ document.querySelectorAll('a[href]').forEach(fixLink);
+ if (typeof CHAPTER === 'object' && CHAPTER?.next && sameSite(CHAPTER.next)) CHAPTER.next = fix(CHAPTER.next);
+ });
+})();
diff --git a/.claude/skills/papermorph/assets/scorm/scorm-host.js b/.claude/skills/papermorph/assets/scorm/scorm-host.js
new file mode 100644
index 0000000..bd00d9d
--- /dev/null
+++ b/.claude/skills/papermorph/assets/scorm/scorm-host.js
@@ -0,0 +1,151 @@
+// SCORM host for a Papermorph book. Runs in launch.html, the one page the LMS launches.
+// It opens the LMS session once, keeps the book's progress, and reports it to the LMS.
+// Book pages reach it as parent.PapermorphSCORM through scorm-bridge.js.
+'use strict';
+(function () {
+ const CFG = window.PAPERMORPH_SCORM_CONFIG;
+ const TOTAL = CFG.chapters.length;
+ const NUMS = new Set(CFG.chapters.map(c => c.n)); // the book's chapter numbers (they need not start at 1)
+ const known = n => Number.isInteger(n) && NUMS.has(n);
+
+ /* ---------- finding and talking to the LMS ---------- */
+ // SCORM 2004 exposes API_1484_11 and SCORM 1.2 exposes API, on a parent frame or the opener.
+ function findAPI(name) {
+ const look = w => {
+ for (let i = 0; w && i < 12; i++) {
+ try { if (w[name]) return w[name]; } catch { return null; } // a cross-origin frame ends the search
+ if (w.parent === w) break;
+ w = w.parent;
+ }
+ return null;
+ };
+ return look(window) || (window.opener ? look(window.opener) : null) ||
+ (window.top && window.top.opener ? look(window.top.opener) : null);
+ }
+
+ const v2004 = CFG.version === '2004';
+ const raw = findAPI(v2004 ? 'API_1484_11' : 'API');
+ const lms = raw && (v2004 ? {
+ init: () => raw.Initialize(''), get: k => raw.GetValue(k), set: (k, v) => raw.SetValue(k, String(v)),
+ commit: () => raw.Commit(''), finish: () => raw.Terminate(''), err: () => raw.GetLastError(),
+ } : {
+ init: () => raw.LMSInitialize(''), get: k => raw.LMSGetValue(k), set: (k, v) => raw.LMSSetValue(k, String(v)),
+ commit: () => raw.LMSCommit(''), finish: () => raw.LMSFinish(''), err: () => raw.LMSGetLastError(),
+ });
+ let live = false;
+ if (lms) live = String(lms.init()) === 'true';
+ if (!live) console.warn(`[scorm] No SCORM ${CFG.version} API found; progress is kept for this visit only.`);
+ const get = k => live ? String(lms.get(k) ?? '') : '';
+ const set = (k, v) => {
+ if (!live) return;
+ if (String(lms.set(k, v)) !== 'true') console.warn(`[scorm] ${k} = ${v} refused (error ${lms.err()})`);
+ };
+
+ /* ---------- the learner's state ---------- */
+ // Kept in suspend_data as {done: [chapter numbers], last: chapter number, s: {chapter: [right, total]}}.
+ // s holds each chapter's best first-try score; it stays well under SCORM 1.2's 4096-character limit.
+ let S = { done: [], last: 0, s: {} };
+ try {
+ const saved = JSON.parse(get('cmi.suspend_data') || 'null');
+ if (saved && typeof saved === 'object') S = {
+ done: Array.isArray(saved.done) ? saved.done.filter(known) : [],
+ last: Number.isInteger(saved.last) ? saved.last : 0,
+ s: saved.s && typeof saved.s === 'object' ? saved.s : {},
+ };
+ } catch { console.warn('[scorm] Unreadable suspend_data; starting fresh.'); }
+
+ const pad = n => String(n).padStart(2, '0');
+ function score() {
+ let r = 0, t = 0;
+ for (const [right, total] of Object.values(S.s)) { r += right; t += total; }
+ return t ? Math.round(100 * r / t) : null;
+ }
+
+ function report() {
+ const finished = S.done.length >= TOTAL;
+ const pct = score();
+ const passed = CFG.mastery == null || (pct ?? 0) >= CFG.mastery;
+ set('cmi.suspend_data', JSON.stringify(S));
+ if (S.last) set(v2004 ? 'cmi.location' : 'cmi.core.lesson_location', 'ch' + pad(S.last));
+ if (pct != null) {
+ const base = v2004 ? 'cmi.score.' : 'cmi.core.score.';
+ set(base + 'min', 0); set(base + 'max', 100); set(base + 'raw', pct);
+ if (v2004) set('cmi.score.scaled', (pct / 100).toFixed(4));
+ }
+ if (v2004) {
+ set('cmi.progress_measure', (S.done.length / TOTAL).toFixed(4));
+ set('cmi.completion_status', finished ? 'completed' : 'incomplete');
+ if (CFG.mastery != null && finished) set('cmi.success_status', passed ? 'passed' : 'failed');
+ } else {
+ set('cmi.core.lesson_status', !finished ? 'incomplete' : CFG.mastery == null ? 'completed' : passed ? 'passed' : 'failed');
+ }
+ // One objective per chapter, so LMS reports can show which chapters a learner finished.
+ CFG.chapters.forEach((ch, i) => {
+ const o = `cmi.objectives.${i}.`, done = S.done.includes(ch.n), cs = S.s[ch.n];
+ set(o + 'id', 'ch' + pad(ch.n));
+ if (cs && cs[1]) {
+ const p = Math.round(100 * cs[0] / cs[1]);
+ set(o + 'score.min', 0); set(o + 'score.max', 100); set(o + 'score.raw', p);
+ if (v2004) set(o + 'score.scaled', (p / 100).toFixed(4));
+ }
+ if (v2004) set(o + 'completion_status', done ? 'completed' : 'incomplete');
+ else set(o + 'status', done ? 'completed' : 'incomplete');
+ });
+ if (live) lms.commit();
+ }
+
+ /* ---------- session start and end ---------- */
+ const t0 = Date.now();
+ if (live) {
+ if (v2004) {
+ if (get('cmi.completion_status') === 'not attempted' || get('cmi.completion_status') === 'unknown') set('cmi.completion_status', 'incomplete');
+ set('cmi.exit', 'suspend');
+ } else {
+ if (get('cmi.core.lesson_status') === 'not attempted') set('cmi.core.lesson_status', 'incomplete');
+ set('cmi.core.exit', 'suspend');
+ }
+ lms.commit();
+ }
+
+ function sessionTime() {
+ const s = Math.max(0, Math.round((Date.now() - t0) / 1000));
+ const hh = Math.floor(s / 3600), mm = Math.floor(s / 60) % 60, ss = s % 60;
+ return v2004 ? `PT${hh}H${mm}M${ss}S` : `${String(hh).padStart(4, '0')}:${pad(mm)}:${pad(ss)}`;
+ }
+ let ended = false;
+ function end() {
+ if (!live || ended) return;
+ ended = true;
+ set(v2004 ? 'cmi.session_time' : 'cmi.core.session_time', sessionTime());
+ // Always suspend, even when finished, so a learner who comes back to review still sees their checkmarks.
+ set(v2004 ? 'cmi.exit' : 'cmi.core.exit', 'suspend');
+ lms.commit();
+ lms.finish();
+ }
+ addEventListener('pagehide', end);
+ addEventListener('beforeunload', end);
+
+ /* ---------- the interface book pages use ---------- */
+ window.PapermorphSCORM = {
+ live,
+ // A copy of {done, last}, in the shape the book's own progress() works on.
+ progress: () => ({ done: S.done.slice(), last: S.last }),
+ // The book changed its progress (opened or finished a chapter).
+ save(p) {
+ S.done = [...new Set((p.done || []).filter(known))].sort((a, b) => a - b);
+ if (Number.isInteger(p.last)) S.last = p.last;
+ report();
+ },
+ // A chapter's finish card appeared; [right, total] are its first-try answers. Keep the best attempt.
+ finished(n, right, total) {
+ if (known(n) && !S.done.includes(n)) S.done = [...S.done, n].sort((a, b) => a - b);
+ const old = S.s[n];
+ if (total > 0 && (!old || right / total > old[0] / old[1])) S.s[n] = [right, total];
+ report();
+ },
+ start(frame) {
+ // Every launch opens on the cover; its Continue button uses the saved last chapter.
+ frame.src = 'book/index.html';
+ },
+ };
+})();
diff --git a/.claude/skills/papermorph/assets/scorm/test/check_scorm.py b/.claude/skills/papermorph/assets/scorm/test/check_scorm.py
new file mode 100644
index 0000000..e7241d1
--- /dev/null
+++ b/.claude/skills/papermorph/assets/scorm/test/check_scorm.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+"""End-to-end check of a SCORM package in the mock LMS, in a headless browser.
+
+ uv run --with playwright SKILL/assets/scorm/test/check_scorm.py dist/<book>-scorm2004.zip
+ uv run --with playwright SKILL/assets/scorm/test/check_scorm.py dist/<book>-scorm12.zip
+
+No server is needed: the check answers every request itself from the zip and mock-lms.html, and, as many LMS file
+servers do, returns 404 for folder URLs. It checks that the session opens, that a chapter card opens its lesson
+(folder links rewritten), that reaching the finish card reports the chapter to the LMS, and that a reload resumes
+with the chapter's checkmark. No files are generated.
+"""
+import asyncio
+import json
+import sys
+import zipfile
+from pathlib import Path
+from urllib.parse import urlparse, unquote
+
+from playwright.async_api import async_playwright
+
+HERE = Path(__file__).resolve().parent
+ORIGIN = "http://lms.papermorph.test"
+
+
+async def main(zpath):
+ z = zipfile.ZipFile(zpath)
+ names = set(z.namelist())
+ version = "1.2" if "adlcp_rootv1p2" in z.read("imsmanifest.xml").decode() else "2004"
+ cfg = json.loads(z.read("launch.html").decode().split("PAPERMORPH_SCORM_CONFIG = ", 1)[1].split(";\n", 1)[0])
+ first = cfg["chapters"][0]["n"]
+ errors = []
+
+ async def answer(route):
+ path = unquote(urlparse(route.request.url).path)
+ if path == "/mock-lms.html":
+ return await route.fulfill(path=HERE / "mock-lms.html")
+ name = path.removeprefix("/pkg/")
+ if path.startswith("/pkg/") and name in names:
+ kind = {".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".mp3": "audio/mpeg",
+ ".json": "application/json", ".png": "image/png", ".webp": "image/webp", ".svg": "image/svg+xml"}
+ return await route.fulfill(body=z.read(name), content_type=kind.get(Path(name).suffix, "application/octet-stream"))
+ await route.fulfill(status=404, body="") # folder URLs included, as on many LMS file servers
+
+ async with async_playwright() as pw:
+ browser = await pw.chromium.launch(args=["--autoplay-policy=no-user-gesture-required"])
+ page = await browser.new_page(viewport={"width": 1600, "height": 960})
+ page.on("pageerror", lambda e: errors.append(str(e)))
+ page.on("console", lambda m: m.type == "error" and not m.text.startswith("Failed to load resource") and errors.append(m.text))
+ page.on("response", lambda r: r.status >= 400 and not r.url.endswith("/favicon.ico") and errors.append(f"{r.status} {r.url}"))
+ await page.route(f"{ORIGIN}/**", answer)
+ await page.goto(f"{ORIGIN}/mock-lms.html?pkg=pkg&v={version}&reset")
+
+ book = lambda: page.frame_locator("#sco").frame_locator("#book")
+ await book().locator(".ch").first.wait_for(state="attached")
+ log = await page.evaluate("LOG.join('\\n')")
+ assert ("Initialize(\"\") -> true" in log) or ("LMSInitialize(\"\") -> true" in log), "the session did not open"
+ print(f"PASS SCORM {version}: session opened, contents shown")
+
+ await book().locator("#cover .btn.go").click() # "Open the book", as a learner does
+ await book().locator(f"#ch{first:02d}").click()
+ lesson = page.frame(url=lambda u: f"/ch{first:02d}/index.html" in u)
+ for _ in range(100):
+ lesson = page.frame(url=lambda u: f"/ch{first:02d}/index.html" in u)
+ if lesson and await lesson.evaluate("typeof P === 'object' && typeof BEATS === 'object'"):
+ break
+ await page.wait_for_timeout(100)
+ assert lesson, "the chapter card did not open its lesson (folder link not rewritten?)"
+ print(f"PASS chapter {first} opened through a folder link")
+
+ await lesson.click("#cover")
+ await lesson.evaluate("seek(BEATS.length - 1, false)")
+ await page.wait_for_timeout(800)
+ cmi = await page.evaluate("CMI")
+ state = json.loads(cmi.get("cmi.suspend_data", "{}") or "{}")
+ assert first in state.get("done", []), f"finish not reported: suspend_data {cmi.get('cmi.suspend_data')!r}"
+ status = "cmi.objectives.0.completion_status" if version == "2004" else "cmi.objectives.0.status"
+ assert cmi.get(status) == "completed", f"objective 0: {cmi.get(status)!r}"
+ print(f"PASS finish card reported: suspend_data {cmi['cmi.suspend_data']}, objective 0 completed")
+
+ await page.goto(f"{ORIGIN}/mock-lms.html?pkg=pkg&v={version}")
+ await book().locator(f"#ch{first:02d}.done").wait_for(state="attached", timeout=10000)
+ print("PASS resume: the chapter's checkmark is back after a reload")
+ await browser.close()
+ assert not errors, errors
+ print("PASS no page errors")
+
+
+if __name__ == "__main__":
+ if len(sys.argv) != 2:
+ sys.exit(__doc__)
+ asyncio.run(main(sys.argv[1]))
diff --git a/.claude/skills/papermorph/assets/scorm/test/mock-lms.html b/.claude/skills/papermorph/assets/scorm/test/mock-lms.html
new file mode 100644
index 0000000..33198b1
--- /dev/null
+++ b/.claude/skills/papermorph/assets/scorm/test/mock-lms.html
@@ -0,0 +1,59 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Mock LMS</title>
+<style>
+ body { margin: 0; display: grid; grid-template-columns: 1fr 380px; height: 100vh; font: 13px/1.4 system-ui, sans-serif; }
+ iframe { width: 100%; height: 100%; border: 0; }
+ aside { overflow: auto; padding: 10px; background: #111; color: #ddd; }
+ pre { white-space: pre-wrap; word-break: break-all; margin: 0 0 10px; }
+ h2 { font-size: 13px; margin: 8px 0 4px; color: #8cf; }
+</style>
+</head>
+<body>
+<iframe id="sco" allow="autoplay; fullscreen"></iframe>
+<aside><h2>CMI data</h2><pre id="cmi"></pre><h2>Calls</h2><pre id="log"></pre></aside>
+<script>
+// A stand-in LMS for local testing: ?pkg=<unzipped package folder>&v=1.2|2004. Data survives reloads (sessionStorage),
+// so reloading the page tests resume; ?reset clears it.
+const q = new URLSearchParams(location.search);
+const pkg = q.get('pkg') || 'pkg', ver = q.get('v') || '1.2';
+const STORE = 'mocklms:' + pkg;
+if (q.has('reset')) sessionStorage.removeItem(STORE);
+const cmi = JSON.parse(sessionStorage.getItem(STORE) || 'null') || (ver === '2004'
+ ? { 'cmi.completion_status': 'unknown', 'cmi.success_status': 'unknown', 'cmi.entry': 'ab-initio' }
+ : { 'cmi.core.lesson_status': 'not attempted', 'cmi.core.entry': 'ab-initio' });
+window.LOG = [];
+let state = 'new';
+const show = () => {
+ document.getElementById('cmi').textContent = Object.entries(cmi).sort().map(([k, v]) => `${k} = ${v}`).join('\n');
+ document.getElementById('log').textContent = LOG.slice(-40).join('\n');
+};
+const call = (name, f) => (...a) => { const r = f(...a); LOG.push(`${name}(${a.map(x => JSON.stringify(x)).join(', ')}) -> ${r}`); show(); return r; };
+const init = () => { if (state !== 'new') return 'false'; state = 'live'; return 'true'; };
+const fin = () => {
+ if (state !== 'live') return 'false';
+ state = 'done';
+ const exit = cmi['cmi.core.exit'] ?? cmi['cmi.exit'];
+ if (exit === 'suspend') { cmi[ver === '2004' ? 'cmi.entry' : 'cmi.core.entry'] = 'resume'; }
+ sessionStorage.setItem(STORE, JSON.stringify(cmi));
+ return 'true';
+};
+const getv = k => cmi[k] ?? '';
+const setv = (k, v) => { if (state !== 'live') return 'false'; cmi[k] = v; return 'true'; };
+const commit = () => { sessionStorage.setItem(STORE, JSON.stringify(cmi)); return 'true'; };
+if (ver === '2004') window.API_1484_11 = {
+ Initialize: call('Initialize', init), Terminate: call('Terminate', fin), GetValue: call('GetValue', getv),
+ SetValue: call('SetValue', setv), Commit: call('Commit', commit), GetLastError: () => '0', GetErrorString: () => '', GetDiagnostic: () => '',
+};
+else window.API = {
+ LMSInitialize: call('LMSInitialize', init), LMSFinish: call('LMSFinish', fin), LMSGetValue: call('LMSGetValue', getv),
+ LMSSetValue: call('LMSSetValue', setv), LMSCommit: call('LMSCommit', commit), LMSGetLastError: () => '0', LMSGetErrorString: () => '', LMSGetDiagnostic: () => '',
+};
+window.CMI = cmi;
+show();
+document.getElementById('sco').src = pkg + '/launch.html';
+</script>
+</body>
+</html>
diff --git a/.claude/skills/papermorph/assets/scorm/test/serve.py b/.claude/skills/papermorph/assets/scorm/test/serve.py
new file mode 100644
index 0000000..4c746db
--- /dev/null
+++ b/.claude/skills/papermorph/assets/scorm/test/serve.py
@@ -0,0 +1,26 @@
+"""Serve a folder the way many LMS file servers do: files only, no index.html for folder URLs.
+
+ python3 SKILL/assets/scorm/test/serve.py <folder> [port]
+
+Put mock-lms.html and an unzipped package (e.g. pkg/) in <folder>, then open
+http://localhost:8781/mock-lms.html?pkg=pkg&v=1.2&reset
+"""
+import sys
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+
+class FilesOnly(SimpleHTTPRequestHandler):
+ def send_head(self):
+ if Path(self.translate_path(self.path)).is_dir():
+ self.send_error(404, 'Folder URLs are not served (as on many LMS file servers)')
+ return None
+ return super().send_head()
+
+
+if __name__ == '__main__':
+ root = sys.argv[1]
+ port = int(sys.argv[2]) if len(sys.argv) > 2 else 8781
+ print(f'http://localhost:{port}/ serving {Path(root).resolve()}')
+ ThreadingHTTPServer(('localhost', port), partial(FilesOnly, directory=root)).serve_forever()
diff --git a/.claude/skills/papermorph/references/site.md b/.claude/skills/papermorph/references/site.md
index fe51d82..75a52cc 100644
--- a/.claude/skills/papermorph/references/site.md
+++ b/.claude/skills/papermorph/references/site.md
@@ -64,3 +64,27 @@ Narration and on-screen text are written in one language first. A second languag
## Video export (optional)
`uv run --with playwright SKILL/scripts/export.py chNN --url http://localhost:8765/<book>/ --out OUT --link <lesson URL>` renders the lesson beats to `OUT/chNN.mp4` (1080p, 30 fps) plus `OUT/chNN.srt` for upload with it. Frames come from seeking the beat clock, so the video matches the page exactly; question beats are left out and the video ends on a card pointing to the interactive lesson. It takes about 1.6× the video's length.
+
+## SCORM package (optional)
+
+For a course in an LMS (Canvas/Quercus, Moodle, Brightspace, Blackboard), package a built book as one SCORM zip:
+
+```sh
+python3 SKILL/scripts/scorm.py site/<book> # SCORM 2004 4th edition, completion only -> dist/<book>-scorm2004.zip
+python3 SKILL/scripts/scorm.py site/<book> --version 1.2 # older LMSs
+python3 SKILL/scripts/scorm.py site/<book> --mastery 80 # also passed/failed at 80 %, once the whole book is finished
+```
+
+`site/<book>/` is not changed; rebuild the zip after changing the book. The LMS launches `launch.html`, which opens one SCORM session and runs the book in a frame, so moving between chapters keeps the session. The build adds `scorm-bridge.js` to the contents page and after `engine.js` in every chapter; it wraps the engine's `progress()` and `finishCard()`, seeds the book's progress from the LMS on each launch (the LMS is the source of truth) and points folder links (`ch02/`) at `index.html`, which many LMS file servers need.
+
+| | SCORM 1.2 | SCORM 2004 |
+|---|---|---|
+| Completion: every chapter's finish card reached | `cmi.core.lesson_status` (`passed`/`failed` with `--mastery`) | `cmi.completion_status`, `cmi.success_status` with `--mastery` |
+| Progress: chapters finished ÷ chapters | — | `cmi.progress_measure` |
+| Score: first-try answers over all quick checks and practice, best attempt per chapter | `cmi.core.score.raw` | `cmi.score.raw`, `cmi.score.scaled` |
+| One objective per chapter (`ch01`, …) with status and score | `cmi.objectives.n.*` | `cmi.objectives.n.*` |
+| Resume (checkmarks, Continue) | `cmi.suspend_data`, `lesson_location` | `cmi.suspend_data`, `cmi.location` |
+
+A chapter counts as finished when its finish card appears, as in the book; a learner can skip there on the step bar, so use `--mastery` when the grade should depend on the answers. Cards that link to another book's folder (`href` in `units`) leave the package and don't work inside an LMS.
+
+Check a package before handing it over: `uv run --with playwright SKILL/assets/scorm/test/check_scorm.py dist/<book>-scorm2004.zip` opens it in `assets/scorm/test/mock-lms.html` (a stand-in LMS that shows every CMI value), opens a chapter through a folder link, reaches its finish card and checks resume. To click through by hand, unzip the package as `pkg/` next to a copy of `mock-lms.html`, run `python3 SKILL/assets/scorm/test/serve.py <folder> 8781` (no folder URLs, like an LMS) and open `http://localhost:8781/mock-lms.html?pkg=pkg&v=2004&reset`; reload without `&reset` to test resume. Before learners use it, upload it to SCORM Cloud (a free account), the usual test of a real LMS. Audio makes up most of a package: check the LMS's upload limit. Canvas grades only the overall result; it doesn't show the per-chapter objectives.
diff --git a/.claude/skills/papermorph/scripts/scorm.py b/.claude/skills/papermorph/scripts/scorm.py
new file mode 100644
index 0000000..5e5bbdb
--- /dev/null
+++ b/.claude/skills/papermorph/scripts/scorm.py
@@ -0,0 +1,216 @@
+#!/usr/bin/env python3
+"""Package a built Papermorph web book (site/<book>/) as a SCORM 1.2 or 2004 zip for an LMS.
+
+ python3 scorm.py site/<book> # SCORM 2004 4th edition, completion only -> dist/
+ python3 scorm.py site/<book> --version 1.2 # SCORM 1.2, for older LMSs
+ python3 scorm.py site/<book> --mastery 80 # also passed/failed at 80 %
+ python3 scorm.py site/<book> --title "PSY101: Motivation" --out OUT
+
+The package launches launch.html, which opens one SCORM session and runs the book in a frame.
+scorm-bridge.js is added to each book page to report progress. The site folder itself is not changed.
+
+Tracking:
+ completion every chapter's finish card has been reached
+ score first-try answers across all chapters' quick checks and practice (best attempt per chapter), 0-100
+ objectives one per chapter (ch01, ch02, ...) with its own status and score
+ --mastery also report passed/failed against this score once the book is finished
+"""
+import argparse
+import json
+import re
+import sys
+import zipfile
+from html import escape
+from pathlib import Path
+from xml.sax.saxutils import quoteattr
+
+RUNTIME = Path(__file__).resolve().parent.parent / 'assets' / 'scorm'
+BRIDGE = 'scorm-bridge.js'
+ENGINE_TAG = re.compile(r'(<script src="\.\./lib/engine\.js"></script>)')
+CHARSET_TAG = re.compile(r'(<meta charset="utf-8">)', re.I)
+# Audio and images are already compressed; zipping them again only costs time.
+STORED = {'.mp3', '.m4a', '.ogg', '.mp4', '.webm', '.png', '.jpg', '.jpeg', '.webp', '.gif', '.woff', '.woff2'}
+
+
+def chapters(site: Path):
+ """[{n, title}] for every chapter folder, read from the chapter's CHAPTER constant."""
+ out = []
+ for d in sorted(site.glob('ch[0-9][0-9]')):
+ page = d / 'index.html'
+ if not page.is_file():
+ continue
+ html = page.read_text(encoding='utf-8')
+ m = re.search(r'const CHAPTER\s*=\s*\{[^}]*?number:\s*(\d+)[^}]*?title:\s*(["\'])(.*?)(?<!\\)\2', html)
+ if not m:
+ sys.exit(f'{page}: no CHAPTER constant with number and title')
+ out.append({'n': int(m.group(1)), 'title': m.group(3).replace("\\'", "'").replace('\\"', '"')})
+ if not out:
+ sys.exit(f'{site}: no chapter folders (ch01/index.html, ...)')
+ nums = [c['n'] for c in out]
+ if len(set(nums)) != len(nums):
+ sys.exit(f'{site}: two chapters share a CHAPTER.number: {nums}')
+ return out # numbers need not start at 1: a book may keep its source's numbering (ch09, ch10, ...)
+
+
+LINK = re.compile(r'''(?:src|href)=["']([^"'#?]+)''')
+
+
+def outside(site: Path, rel: str, html: str):
+ """Relative files a page loads or links to that lie outside the book folder (they won't be in the package)."""
+ out = set()
+ for ref in LINK.findall(html):
+ if re.match(r'^[a-z][a-z0-9+.-]*:|^//|^/', ref, re.I):
+ continue # absolute URLs and site-root paths: not files of this book
+ target = (site / rel).parent.joinpath(ref).resolve()
+ if site not in target.parents and target != site:
+ out.add(ref)
+ return out
+
+
+def book_title(site: Path):
+ m = re.search(r'<title>(.*?)</title>', (site / 'index.html').read_text(encoding='utf-8'), re.S)
+ return m.group(1).strip() if m else site.name
+
+
+def with_bridge(rel: str, html: str):
+ """The page with scorm-bridge.js added, or None if it isn't a book page."""
+ if rel == 'index.html':
+ out, k = CHARSET_TAG.subn(rf'\1\n<script src="{BRIDGE}"></script>', html, count=1)
+ elif re.fullmatch(r'ch\d\d/index\.html', rel):
+ out, k = ENGINE_TAG.subn(rf'\1\n<script src="../{BRIDGE}"></script>', html, count=1)
+ else:
+ return None
+ if k != 1:
+ sys.exit(f'{rel}: could not find where to add {BRIDGE} (the page layout may have changed)')
+ return out
+
+
+def manifest(book, title, version, mastery, files):
+ ident = re.sub(r'[^A-Za-z0-9_.-]', '-', f'papermorph.{book}')
+ t = escape(title)
+ file_list = '\n'.join(f' <file href={quoteattr(f)}/>' for f in files)
+ if version == '1.2':
+ mastery_xml = f'\n <adlcp:masteryscore>{mastery}</adlcp:masteryscore>' if mastery is not None else ''
+ return f'''<?xml version="1.0" encoding="UTF-8"?>
+<manifest identifier="{ident}" version="1"
+ xmlns="http://www.imsproject.org/xsd/imscp_rootv1p1p2"
+ xmlns:adlcp="http://www.adlnet.org/xsd/adlcp_rootv1p2"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.imsproject.org/xsd/imscp_rootv1p1p2 imscp_rootv1p1p2.xsd http://www.imsglobal.org/xsd/imsmd_rootv1p2p1 imsmd_rootv1p2p1.xsd http://www.adlnet.org/xsd/adlcp_rootv1p2 adlcp_rootv1p2.xsd">
+ <metadata>
+ <schema>ADL SCORM</schema>
+ <schemaversion>1.2</schemaversion>
+ </metadata>
+ <organizations default="org">
+ <organization identifier="org">
+ <title>{t}</title>
+ <item identifier="item_book" identifierref="res_book" isvisible="true">
+ <title>{t}</title>{mastery_xml}
+ </item>
+ </organization>
+ </organizations>
+ <resources>
+ <resource identifier="res_book" type="webcontent" adlcp:scormtype="sco" href="launch.html">
+{file_list}
+ </resource>
+ </resources>
+</manifest>
+'''
+ seq = ''
+ if mastery is not None:
+ seq = f'''
+ <imsss:sequencing>
+ <imsss:objectives>
+ <imsss:primaryObjective objectiveID="book" satisfiedByMeasure="true">
+ <imsss:minNormalizedMeasure>{mastery / 100:.2f}</imsss:minNormalizedMeasure>
+ </imsss:primaryObjective>
+ </imsss:objectives>
+ </imsss:sequencing>'''
+ return f'''<?xml version="1.0" encoding="UTF-8"?>
+<manifest identifier="{ident}" version="1"
+ xmlns="http://www.imsglobal.org/xsd/imscp_v1p1"
+ xmlns:adlcp="http://www.adlnet.org/xsd/adlcp_v1p3"
+ xmlns:adlseq="http://www.adlnet.org/xsd/adlseq_v1p3"
+ xmlns:adlnav="http://www.adlnet.org/xsd/adlnav_v1p3"
+ xmlns:imsss="http://www.imsglobal.org/xsd/imsss"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://www.imsglobal.org/xsd/imscp_v1p1 imscp_v1p1.xsd http://www.adlnet.org/xsd/adlcp_v1p3 adlcp_v1p3.xsd http://www.adlnet.org/xsd/adlseq_v1p3 adlseq_v1p3.xsd http://www.adlnet.org/xsd/adlnav_v1p3 adlnav_v1p3.xsd http://www.imsglobal.org/xsd/imsss imsss_v1p0.xsd">
+ <metadata>
+ <schema>ADL SCORM</schema>
+ <schemaversion>2004 4th Edition</schemaversion>
+ </metadata>
+ <organizations default="org">
+ <organization identifier="org">
+ <title>{t}</title>
+ <item identifier="item_book" identifierref="res_book" isvisible="true">
+ <title>{t}</title>{seq}
+ </item>
+ </organization>
+ </organizations>
+ <resources>
+ <resource identifier="res_book" type="webcontent" adlcp:scormType="sco" href="launch.html">
+{file_list}
+ </resource>
+ </resources>
+</manifest>
+'''
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument('book', type=Path, help='the built book, e.g. site/motivation')
+ ap.add_argument('--version', choices=['1.2', '2004'], default='2004', help='SCORM version (default 2004 4th edition; 1.2 for older LMSs)')
+ ap.add_argument('--mastery', type=int, metavar='PCT', help='passing score 0-100; without it the book reports completed, not passed/failed')
+ ap.add_argument('--title', help='title shown in the LMS (default: the book cover <title>)')
+ ap.add_argument('--out', type=Path, default=Path('dist'), help='output folder (default dist/)')
+ a = ap.parse_args()
+ if a.mastery is not None and not 0 <= a.mastery <= 100:
+ ap.error('--mastery must be between 0 and 100')
+
+ site = a.book.resolve()
+ slug = site.name
+ if not (site / 'index.html').is_file():
+ sys.exit(f'{site}: no index.html; build the book first')
+ chs = chapters(site)
+ title = a.title or book_title(site)
+
+ # Everything that goes in the zip: {path in zip: bytes}.
+ files = {}
+ for f in sorted(site.rglob('*')):
+ if not f.is_file():
+ continue
+ rel = f.relative_to(site).as_posix()
+ if rel.startswith('.') or '/.' in rel or rel.endswith(('.bak', '.tmp')) or '.bak-' in rel:
+ continue
+ data = f.read_bytes()
+ if rel.endswith('.html'):
+ for ref in sorted(outside(site, rel, data.decode('utf-8'))):
+ print(f'warning: {rel} uses {ref}, outside the book folder; it is not in the package', file=sys.stderr)
+ patched = with_bridge(rel, data.decode('utf-8'))
+ if patched is not None:
+ data = patched.encode('utf-8')
+ files['book/' + rel] = data
+ files['book/' + BRIDGE] = (RUNTIME / BRIDGE).read_bytes()
+ files['scorm-host.js'] = (RUNTIME / 'scorm-host.js').read_bytes()
+ cfg = {'book': slug, 'title': title, 'version': a.version, 'mastery': a.mastery, 'chapters': chs}
+ launch = (RUNTIME / 'launch.html').read_text(encoding='utf-8')
+ config = json.dumps(cfg, ensure_ascii=False).replace('<', chr(92) + 'u003c') # no '</script>' inside the script
+ launch = launch.replace('__TITLE__', escape(title)).replace('__CONFIG__', config)
+ files['launch.html'] = launch.encode('utf-8')
+ files['imsmanifest.xml'] = manifest(slug, title, a.version, a.mastery,
+ sorted(k for k in files if k != 'imsmanifest.xml')).encode('utf-8')
+
+ a.out.mkdir(parents=True, exist_ok=True)
+ zpath = a.out / f'{slug}-scorm{a.version.replace(".", "")}.zip'
+ with zipfile.ZipFile(zpath, 'w') as z:
+ # The manifest goes first; some LMS importers look for it at the start of the archive.
+ for name in ['imsmanifest.xml'] + sorted(k for k in files if k != 'imsmanifest.xml'):
+ kind = zipfile.ZIP_STORED if Path(name).suffix.lower() in STORED else zipfile.ZIP_DEFLATED
+ z.writestr(name, files[name], compress_type=kind)
+ size = zpath.stat().st_size / 1e6
+ print(f'{zpath} ({size:.1f} MB, SCORM {a.version}, {len(chs)} chapters, '
+ f'{"mastery " + str(a.mastery) + "%" if a.mastery is not None else "completion only"})')
+
+
+if __name__ == '__main__':
+ main()