Skip to content

Playbook and Three.js code kit for detailed dioramas: classic pixel art, stroked toon or pixel + stroke; two intake gates for look and model sourcing; free orbit, palette snap and ink; animated toy-scale cast; per-entity frame QA.

Update to v5.7.0: three looks, two intake gates, split references

sloemodznd74370719cea
diff --git a/README.md b/README.md
index 8d89e0c..324b1f4 100644
--- a/README.md
+++ b/README.md
@@ -2,13 +2,13 @@
# Diorama
-**A playbook and code kit for building small pixel-art dioramas in Three.js.**
+**A playbook and code kit for detailed Three.js dioramas. It asks two questions before the first mesh: which of three looks to build in, and whether the models come from libraries or from your own geometry.**
[![Stars](https://img.shields.io/github/stars/sloemo01/diorama?style=flat-square&color=1d1d1f&logo=github&label=stars)](https://github.com/sloemo01/diorama/stargazers)
[![Forks](https://img.shields.io/github/forks/sloemo01/diorama?style=flat-square&color=1d1d1f&label=forks)](https://github.com/sloemo01/diorama/forks)
[![Watchers](https://img.shields.io/github/watchers/sloemo01/diorama?style=flat-square&color=1d1d1f&label=watchers)](https://github.com/sloemo01/diorama/watchers)
[![License](https://img.shields.io/github/license/sloemo01/diorama?style=flat-square&color=1d1d1f)](LICENSE)
-[![Skill](https://img.shields.io/badge/skill-v3.8.0-1d1d1f?style=flat-square)](SKILL.md)
+[![Skill](https://img.shields.io/badge/skill-v5.7.0-1d1d1f?style=flat-square)](SKILL.md)
[![three.js](https://img.shields.io/badge/three.js-r170-1d1d1f?style=flat-square&logo=three.js&logoColor=white)](https://threejs.org)
<p>
@@ -26,19 +26,85 @@
</div>
-A diorama here is a tiny staged scene on a slab: a locked three-quarter camera, a
+A diorama here is a tiny staged scene on a slab: a resettable three-quarter hero camera with free user orbit, a
flat cut-out against white paper, a 64 colour palette with ordered dither and an
inked contour, and toy-scale people with real joint animation. The subject changes
(pool, night market, bank job, arena battle); the slab, the cast and the
-presentation stay.
+presentation stay for the default pixel preset.
+
+**Optional stroked toon / illustrated miniature:** fine charcoal contours,
+four-step shaded solid parts, small bevels, coherent attachments and detailed
+subject-specific prop clusters. It works across subjects, not just machinery.
+**Choosing the look:** the agent asks one question at the start of every project —
+pixel art (default), stroked toon, or pixel + stroke hybrid — and builds in the
+answer. An explicit style in the request is the answer; a reference image or the
+word "toon" is not; silence resolves to pixel and is recorded as a delegated
+default, with no later switch. The implementation is in
+`templates/stroked-toon.js`, with consent and rendering fields in
+`templates/DESIGN.md`. This is a Three.js
+rendering recipe, not reused Anatomy CSS or SVG. Free orbit is mandatory in every preset; figure-frame UI remains optional outside educational mode; see the preset section in `SKILL.md`.
+
+**Choosing the sources:** the second question is how models get made. Hybrid is the
+default: search for fitting commercially usable assets, download and use them, then
+hand-build the missing or scene-specific pieces. The alternatives are internet models
+throughout, and fully agent-modelled geometry. Either way the licence must permit
+commercial use, modification and redistribution inside the delivered scene, so NC, ND,
+editorial and unstated terms are rejected. Every role's decision and its licence
+evidence land in `refs/SOURCES.md` and `CREDITS.md`.
Everything is deterministic. The scene is a pure function of `t`, so any frame can
be frozen, screenshotted and compared. A screenshot is evidence, not a lucky
capture.
-`SKILL.md` is the whole playbook: it carries a research-first workflow, the look
-and animation bars, the pipeline, the recipes, the QA harness and the pitfalls,
-in one self-contained file. Everything else here is copy-in code that supports it.
+`SKILL.md` is the playbook: research-first workflow, the look and animation bars,
+the pipeline, the recipes, the QA harness and the pitfalls. It stays the source of
+truth. `references/` holds the same material split into on-demand topic files for
+long sessions, and everything else here is copy-in code that supports it.
+
+## Educational scenes and inspection (5.7)
+
+Educational mode is a first-class exception to narrative cast/ritual/system quotas:
+one accurately built mechanism, one causal sequence and clean off-white (`#f7f7f5`).
+The default surface is one opaque white card in a reserved 360px right column, which
+becomes a bottom dock below 880px; an explicitly requested placement keeps those tokens
+and controls. Narrative scenes get none of it: no card, lesson steps, part picker,
+dashboard or floating labels unless an explanation was asked for. Click a real part for
+one short explanation, and the same labelled picker supports keyboard selection,
+including pieces hidden inside the housing. Selection lifts the chosen material while
+the rest dims, from reversible overrides that restore the exact original materials, and
+feature edges are built from `EdgesGeometry` on the live meshes rather than a wireframe
+pass. Selecting a part triggers one short camera and target transition, cancelled
+immediately by user orbit or keyboard navigation; Back restores the previous view and
+Reset keeps the hero pose. Component manifests, real through-bores and
+ratio/kinematic/contact tests stop simplification from quietly deleting working parts.
+Delivery needs frozen-frame, motion, orbit, mobile and accessibility evidence, not a
+promise that an agent complied.
+
+All presets rotate by default, with no separate orbit consent. `templates/orbit.js` supplies reset, keyboard orbit and drag-versus-click handling. `pixel-stroke` is chosen through that same one-question gate; `templates/pixel-stroke.js` renders toon materials and selective geometry contours into an explicit low-res target then nearest upscales once. No PixelPost/Sobel double edges; DOM UI stays native resolution. Stroke thickness must be checked in target pixels and after screen upscale.
+
+## Motion graphics
+
+Arrows, flames and flow are geometry, not texture. The v3.12.0 four-stroke work hardened them with a
+full-cycle, frame-by-frame pass: a spline through the
+cutaway speared the valve disc, only the arrow *centre* was clamped so heads
+poked through the crown, two stacked rows read as double-headed chevrons, scales
+ran past 1.0 and defeated the legibility gate, the force arrow outlived its
+flame, and the ignition flash blew the head to white. The rules are: derive each
+effect from the current free volume (never a port centreline), fit the
+direction-dependent cone extent, anchor to the real valve/crown surface, use one
+arrow per stroke, normalize the authored length, couple the effect to its source,
+declare every Y constant in one local space, cap the flash, and accept only after
+a 15°-step contact sheet plus a 720° vertex containment sweep. Earlier findings
+still apply: tested +Z axis, no `depthTest:false`, no sub-pixel specks,
+free-band sizing, compact flames, un-outlined FX and phase-bound lifetimes.
+`templates/flow-primitives.js` is the copy-in helper: tested +Z arrows, a
+free-band fitter and a legibility gate. See "Motion Graphics Primitives" in
+`SKILL.md` and the effects block in `templates/DESIGN.md`.
+
+<p align="center">
+<img src="media/education-ui-right.png" width="62%" alt="Educational mechanism with one right-side dock">
+<img src="media/education-selection-focus.png" width="34%" alt="Selected part glowing while the rest dims">
+</p>
## The scenes
@@ -84,7 +150,7 @@ Repo: https://github.com/sloemo01/diorama
https://github.com/sloemo01/diorama/archive/main.tar.gz
tar xzf diorama.tar.gz && mv diorama-main "<target>"
3. Prove the install before describing it: SKILL.md, README.md,
- templates/, verify/ and LICENSE at the root, and print the
+ references/, templates/, verify/ and LICENSE at the root, and print the
commit hash (git -C "<target>" rev-parse --short HEAD) or the
archive date. If you have no shell or no network, say so and
stop. If the download failed or a file is missing, say so and
@@ -92,7 +158,7 @@ Repo: https://github.com/sloemo01/diorama
4. If you have a skills directory or plugin folder, install it
there so you can load it by name in later sessions; otherwise
treat "<target>" as the folder.
-5. Read before you build: all of SKILL.md, then
+5. Read before you build: all of SKILL.md, references/INDEX.md, then
templates/DESIGN.md, templates/SOURCES.md, templates/CREDITS.md,
templates/qa/README.md, the header comment of every file in
templates/, and the worked examples under verify/. SKILL.md is
@@ -123,11 +189,14 @@ and can be deleted after the clone.
| --- | --- |
| `SKILL.md` | The whole playbook: research gate, look contract, detail and animation bars, pipeline, recipes, QA, pitfalls. Start here. |
| `templates/` | Copy-in modules: palette, post pass, camera, lighting, geometry, props, rig, poses, vehicle transfer, paths, combat, creature, water, effects, build script. |
+| `templates/flow-primitives.js` | Tested +Z arrow primitive, free-band fitter and legibility gate for motion graphics. |
| `templates/DESIGN.md` | The design sheet you fill before modelling. |
| `templates/SOURCES.md` | The research log you fill before modelling: query, what was found, decision. |
| `templates/CREDITS.md` | The licence ledger for every imported model, clip or texture. |
| `templates/creature.js` | Rigged-actor combat: stage-local aiming, bone-space effect anchors, upright billboards, hit severities, send-out geometry. |
-| `templates/qa/` | Eight verification scripts that check a build against frozen frames and printed numbers, including a per-entity frame recorder. |
+| `references/` | The playbook split by topic, indexed in `references/INDEX.md`: sourcing, representation, inspection, construction gates, service, vehicles, effects, verification. |
+| `templates/qa/` | Eight verification scripts that check a build against frozen frames and printed numbers, including a per-entity frame recorder, plus unit and browser regressions for the inspection and mechanism helpers. |
+| `archive/` | Retired material kept for reference: the removed Pixel Art V2 renderer and its supporting parts. |
| `verify/water/` | A worked scene that exercises the water modules, with the screenshots the QA loop produced. |
| `verify/climb/` | A unit test for the vehicle transfer maths. |
| `verify/creature-battle/` | What a two-actor fight build proved: aiming, effect anchoring, send-out and hit numbers. |
@@ -145,7 +214,7 @@ and can be deleted after the clone.
as a verb, cast, systems, five beats with timestamps, detail budget.
4. Copy the modules you need into `src/core/` and `src/scene/`, then a `config.js`
that holds the scene's numbers. `verify/water/src/` is the reference layout.
-5. Block out in grey at the locked camera before any production pass, then run the
+5. Block out in grey at the reset hero camera before any production pass, then run the
pipeline: palette, materials, detail, animation, effects, post.
6. Verify with `templates/qa/` before calling it done, and check the research gate
in `Build And Ship` (reference sheets, `SOURCES.md`, `CREDITS.md`, per-beat
@@ -158,7 +227,7 @@ nothing is the most common way a commission fails:
- **Shape.** Pull the real thing on video, step it into contact sheets at 8 to 12
fps, read them, and write the grammar down before touching geometry.
-- **Assets.** Check the user's disk, then the CC0 and CC-BY libraries (Quaternius,
+- **Assets.** Check the user's disk, then the Polyfork catalogue, then the CC0 and CC-BY libraries (Quaternius,
KayKit, Poly Pizza, Kenney, Sketchfab with the downloadable plus CC0 filter,
Smithsonian, Poly Haven, ambientCG, Mixamo and the Quaternius animation
library). A rigged download beats four hundred lines of primitives at close
@@ -176,7 +245,7 @@ them.
## How it works
- **One camera solve.** The camera is fitted to the slab's bounding box once, at a
- fixed three-quarter azimuth, with a `subjectScale` margin. No orbit controls.
+ fixed three-quarter azimuth, with a `subjectScale` margin. Free orbit controls and reset in every preset; no auto-spin.
- **Two passes, one look.** The render is drawn into a small buffer, then gamma,
grade, a 64 entry palette snap, ordered dither, an ink contour and a nearest
neighbour upscale happen in that fixed order.
@@ -230,9 +299,9 @@ defects the harness found and the numbers after the fix.
## Using it as a skill
`SKILL.md` carries skill frontmatter (`name`, `description`, `version`), so a
-skill-capable coding agent can load it as-is. It is self-contained: no external
-reference documents, everything needed to build a diorama is in the file plus
-`templates/`.
+skill-capable coding agent can load it as-is. It reads on its own; `references/`
+carries the same guidance split by topic for long sessions, and `templates/` carries
+the copy-in code.
If you just want to read it, start at `Research Before You Model`, then
`One Prompt, One Build` and `The Look Contract`.
diff --git a/SKILL.md b/SKILL.md
index bb7ff84..782bb07 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -1,7 +1,7 @@
---
name: diorama
-description: Use when building a pixel diorama in Three.js — one-prompt autonomous builds with staged systems, detailed props, real animation, and social/service choreography.
-version: 3.8.0
+description: "Full long-form guide for detailed rotatable Three.js dioramas. Narrative scenes are scene-first with no educational UI unless requested. Classic pixel, stroked-toon and pixel+stroke are rendering choices, not educational modes. Explanatory commissions use the separate educational contract. Includes composition, cast, animation, craft, sourcing and construction."
+version: 5.7.0
author: Nehal Kanak (sloemo)
license: MIT
platforms: [linux, macos, windows]
@@ -9,25 +9,138 @@ platforms: [linux, macos, windows]
# Diorama
-A diorama is a tiny staged scene on a slab: a locked three-quarter camera, a
-flat cut-out against white, a palette-snapped pixel grid with an ink contour, and
-toy-scale people with real joint animation. Any subject works (pool, market,
-kitchen, bank job, launch pad, aquarium). The slab and the cast stay; the props
-change.
+## Current intake contract (5.7.0 — authoritative)
-**This file is the whole guide.** It carries no external reference documents:
-everything needed to build a diorama is here, plus copy-in modules and a design
-sheet template in `templates/`.
+For a new commission, ask **look first, model sourcing second**, using the two gates below. These gates override older three-preset lists, automatic internet-first instructions and one-prompt assumptions elsewhere in this long guide and its references. Do not ask setup questions when merely editing the skill. Explicit answers in the brief skip the corresponding question; existing-project repairs retain recorded choices. An unanswered question is pending, not consent. Rendering and sourcing are independent of narrative/educational purpose.
-Read `Research Before You Model`, `One Prompt, One Build`, `The Look Contract`,
-`The Detail Bar`, `The Animation Bar` and `Pipeline` first. Then read the sections for the systems
-you are actually building; the rest is reference. Do not spend the first pass
-reading every vehicle or water note for a kitchen scene.
+Three looks are available: `pixel` (Classic Pixel Art; recommended), `stroked-toon`, `pixel-stroke`. Generic “pixel art”, “classic”, “old pixel style” and explicit delegation (“you choose”) resolve to `pixel`. All looks preserve free orbit. An unanswered style gate waits.
+
+Three sourcing modes are available: `internet-full`, `hybrid` (recommended), `authored-only`. Generic “use internet models” resolves to `hybrid` unless the user requests downloaded models throughout. Older `internet-first` records map to `hybrid` on repairs. Sourcing requirements below apply only to modes that acquire external assets; authored-only skips model acquisition, not subject research, quality or geometry/contact checks.
+
+## Profile boundary and retained additions (5.0 — read first)
+
+This is the **restored full-length guide**, not the compact 4.x replacement. Keep its detailed composition, subject recipes, scene furniture, cast, animation, service/queue, vehicle, effects, framing and craft guidance. The following profile/sourcing updates override older wording only where explicitly stated.
+
+### Scene purpose is independent of rendering
+
+**Default `sceneProfile: narrative`.** A place, landscape, amusement park, town, fantasy scene or interactive scene is not an educational mechanism. Pixel, stroked-toon and pixel+stroke choose the renderer, NOT the profile. Asset choice, a working ride or click interactions do not make a scene educational. Choose `educational` when the user asks to explain/teach how something works, its anatomy or causal sequence. If intent is genuinely mixed, ask once; otherwise infer and record it without another forced setup question.
+
+**Narrative has no educational UI by default.** Do not import or instantiate `education-v8.css`, `education-dock.mjs`, an Explore/How it works panel, lesson steps, part picker, explanatory dashboard, floating callout labels or scattered teaching text for an ordinary diorama. This exclusion applies in ALL three render presets. Leave the scene/page visually clean. Free orbit and discreet functional pause/reset/accessibility controls remain permitted; diegetic park signs and shop names are scene geometry, not a teaching overlay. Optional title/readout furniture mentioned later is opt-in, not a toon/hybrid default. No debug panel in delivery.
+
+**Educational only:** canonical V8 right card/mobile dock, causal lessons, part inspection and connected explanatory callouts apply to explanatory commissions, not to all scenes. Explicit UI-free requests still override the panel default: explanation can be delivered through the requested scene behavior and accompanying prose. Narrative scenes with explicitly requested ride/part inspection get the requested scoped interaction, not an automatic lesson dashboard. Explicit requested informational labels are allowed, but do not add unrelated teaching surfaces. Record `uiMode: none | minimal-controls | requested-inspection | educational` and why; never satisfy a UI test by adding unwanted UI.
+
+Regression examples: “amusement park in pixel + stroked toon” → narrative + pixel-stroke + no education UI. “Interactive amusement park” → narrative; interaction alone adds no lessons. “Explain a roller coaster's operation” → educational, chosen style independently. “Amusement park with inspectable rides” → narrative + requested inspection only. A scene with no educational intent must not fail QA for lacking V8, lessons, labels or a card column.
+
+### Default occupied-space pass: actions, seating and scenery
+
+Prevent intersections before adding detail or spawning copies, for people, animals, imported rigs, buildings, props and rides in BOTH profiles/all presets. Use `references/action-clearance.md`, `templates/action-clearance.mjs` and `templates/pose-bounds.mjs` with the actual production evaluator; this adds no educational UI.
+
+1. **Reserve full space, not origins:** building/awning/door parcels, open access paths, actor swept widths and reach, tails/wings/horns, carried items and neighbouring actors. Reuse fitted rigs/clips from internet assets, but reject an asset/clip that cannot fit the required seat/action without distortion. Split accessible structures into actual wall/door/roof pieces; an enclosing hollow-building AABB is only a broad-phase candidate, not solid occupancy. Use deterministic lanes, queue slots, crossing priorities and seat reservations, not random nudges after overlap.
+2. **Solve real contact/action frames:** approach → align → bend/lower → supported sit → stand/exit; pelvis, knees, feet and hands follow real seat/ground/handle frames. Don't sit by dropping a standing model through the chair. Ride occupants inherit the seat's moving frame once. Permit only exact named intended body↔support/joint contacts, with action window and bounded depth; never exempt an entire actor, chair, species or same-owner subtree. Check support gaps separately—an allowed collision contact does not prove the person isn't floating.
+3. **Check the live pose across the whole action:** refresh skeleton/morph vertices and world frames, then use measured conservative body-region capsules/boxes plus structural pieces. Bind-pose bounds/root-point distances miss moving limbs; undersized colliders and omitted tails/carry props are failures. Broad-screen nearby pairs; refine loose bounds instead of deleting objects to lower candidate counts. Production audits supply independently specified `requiredIds`; missing actors/proxies or unverified coverage cannot pass. Test nonadjacent self-parts too, while explicitly declaring valid anatomical/structural joints. Proxy overlap is not automatically actual mesh penetration.
+4. **Test critical times and fixes:** sample full cycles, loop seam, approach/contact/departure, largest reach, sitting/standing, crossings and door swing. Include exact events and refine using relative tip motion/clearance, not only endpoints or an attractive frame. `sampledOnly:true` is bounded sampled evidence, not continuous collision freedom. Move a real wrist/tail/knee into an obstacle, overlap building parcels and synchronize a crossing; the SAME production predicate must flag the fault and pass after repair. Review worst-contact side/back/top crops plus an action strip. Never hide bodies, shrink proxies, fade through walls or freeze the requested action to claim a pass. One source-driven QA runner, cached static obstacles, nearby-pair broad phase and worst-few reporting keep this practical.
+
+### Default asset workflow: search, acquire and USE fitting models
+
+Ask the Model Sourcing Gate after the look is resolved, for BOTH profiles. Follow the recorded `internet-full`, `hybrid` or `authored-only` choice; do not silently impose internet-first. In the first two modes, reuse valid local assets but still search for missing major roles. The acquisition requirements in this section apply to those two modes; authored-only intentionally builds geometry and does not need a failed model search to justify it.
+
+**A search is not the deliverable.** Before detailed hand-modelling, find candidates for the hero and major supporting roles, review the actual per-asset terms and appearance, download the chosen permitted model/dependencies, inspect an actual import, and USE it in the scene when it fits. A fitting, licensed asset must not be ignored in favour of primitive-only reconstruction merely because hand-building is familiar. Nor does importing one token tree satisfy sourcing a park's otherwise hand-built rides/buildings/cast. Record decisions for the main roles in the existing SOURCES/CREDITS/design ledger.
+
+**Fit means diorama-quality, not merely downloadable:** correct subject/representation and silhouette, coherent kit/palette/proportions, adequate construction detail, usable parts/rig/clips for the requested motion or inspection, viable triangle/draw-call/texture budget, and compatibility with the chosen pixel/toon/hybrid rendering. Judge the real model from more than a thumbnail. Normalize scale/axes/origin, adapt colours/materials without losing important markings, preserve rigs/part identity, fit to the scene and review a rendered close-up. A realistic/PBR asset is not automatically disallowed if it can be adapted well; an unrelated low-poly substitute is not automatically suitable. Follow the original long-form craft, composition and motion standards after importing.
+
+**Rights remain mandatory:** prefer FREE assets whose explicit terms permit commercial use, modifications and redistribution/embedding in the delivered scene. Read original asset/license evidence; retain credits/license/change notices where required. NC, ND, editorial, personal/educational-only and missing rights do not pass. Custom/ShareAlike/other terms require compatibility review, not a fake CC0 label. No purchases, subscriptions or paid downloads without explicit user approval. Check separately licensed dependencies. Commercial permission is not scientific accuracy or trademark/other-rights clearance.
+
+**Source order:** use the user's Polyfork-first sweep for narrative kits/props, then the relevant original-author/model-library sources in this guide; if Polyfork misses, continue to appropriate alternatives rather than declare that the internet has none. Educational subjects use their bounded exact-subject search and extra accuracy/structure gate. Reuse a compatible kit for coherence. Do not crawl every provider indiscriminately or repeatedly search the same noun. Actual search/download/import evidence stays on disk; never fabricate searches, licenses or successful loads.
+
+**Hand-model only the justified gap:** necessary missing/custom geometry, unsuitable candidates after source/fit checks, or interfaces/animation adaptations not supplied by an imported model. Selection or movement alone is NOT a reason to reject an asset: use real part/pivot wrappers where feasible. Retain an all-authored approach when the user explicitly asks for it. If browsing/downloads are unavailable, disclose the limitation and fallback; never say the search found nothing when it never ran. A quality mismatch, unclear license or lack of useful motion is a documented reason to reject, not a reason to force a bad download.
+
+**Proof before completion:** for each major role record search/source, chosen asset or rejection/fallback reason, license evidence, actual downloaded file/path/hash and import/style/motion result. A compliant matching candidate found → acquired and used; no suitable candidate → honest specific fallback. Verify the chosen asset actually exists in the final scene, not just in assets/. Offline/standalone delivery packages every permitted dependency and is tested without network; a warm cache or CDN loader is not self-contained. Sourcing adds NO education panels, callouts or other UI to narrative scenes.
+
+### Preserve the approved 4.x additions without shortening this guide
+
+- **Representation:** actual subject by default, not a classroom surrogate. Follow `references/representation.md`: Earth means a planet, not a globe on a stand. Ask real subject / physical teaching model / explanatory abstraction / you choose only if materially ambiguous; preserve explicit choices. Keep representation, render preset, purpose, scene/object context and Inside independent. Natural subjects do not acquire invented platforms, frames or machinery merely because this guide contains mechanical examples.
+- **Narrative sourcing:** preserve the user's Polyfork-first catalogue sweep, kits/matching, source decisions and scale/palette integration in `references/external-models.md`. This extends the older model-library section; do not fall back to primitive-only scenery without checking suitable assets.
+- **Educational sourcing:** the named teaching object/parts may be verified external geometry. Use the bounded candidate search and accuracy/import wrapper in `references/educational-models.md`, not a narrative full-catalogue crawl. Add authored semantic IDs, interfaces, pivots and explanation where needed.
+- **Rights:** all downloaded assets must permit commercial use, modification and redistribution in the delivered scene. Free download is not permission. Use `templates/educational-asset-gate.mjs` with reviewed evidence/credits and actual file hashes; CC0/CC-BY can pass, unknown/custom terms require review, NC/ND/editorial/incompatible terms do not pass. Verify dependencies and offline bundling; a remote CDN load is not an offline standalone artifact. This rights gate overrides older library summaries, including casually accepted restrictive licenses.
+- **Construction:** retain `templates/construction-kit.js` and `templates/interface-checks.js`; reserve working pockets, derive contact stacks from shared datums, check actual geometry and repeats. Keep the original detailed construction/selection chapters. Material/selection/annotation checks apply only to implemented/requested features; no forced annotation system to satisfy QA. AABB overlap is a candidate, not certified penetration. Use scoped real mutations, not bespoke injected-object detectors. Available helpers are supplemental, not proof of a whole scene.
+- **Maintenance:** do not mutate the installed skill after each scene automatically. An explicit maintenance request and filesystem approval are required. Preserve original/current backups. Historical changelogs document prior versions; they do not override this release.
+
+A diorama is a tiny staged scene with a resettable three-quarter hero camera and
+free user orbit. The default pixel preset uses a white cut-out, palette-snapped
+pixel grid and ink contour; the other presets follow their own presentation
+contracts. Narrative scenes retain the slab and toy-scale animated cast;
+educational scenes use the exception below.
+
+Classic Pixel Art is the recommended new-project look. **Stroked toon / illustrated miniature**
+(`stroked-toon`) and the **pixel + stroke hybrid** (`pixel-stroke`) are optional
+rendering presets for any subject, not a coffee-machine genre. **Ask which of the
+three to build in at the start of every project** — see `Render Preset Gate` —
+because the look changes presentation only, never the subject, story, research
+requirements, choreography or construction standard, and nobody should have it
+chosen silently on their behalf.
+
+**Profile precedence (read first):** For an educational explanation, read
+`Educational Mechanism Profile` before the narrative defaults. One mechanism and
+one causal sequence replace ALL mandatory cast/ritual/multiple-system/story-prop
+quotas throughout this guide. Clean off-white and the single V8 right card/mobile dock replace empty
+paper or decorative figure UI (explicit placement requests remain supported). Construction and mechanical correctness are never
+waived. For EVERY preset, free user orbit is mandatory; fixed/hero views below
+refer to deterministic QA/reset poses, not a locked interaction camera.
+
+**This file restores the full guide.** The supplemental references named in the 5.0 additions carry later approved sourcing/representation rules; copy-in modules and the detailed design sheet remain in `templates/`.
+
+**Execution index — do not read every genre recipe first.** Resolve the preset
+and profile, then use the fast-path table. Read `Research Before You Model` and
+`The Detail Bar` (including whole-object completeness) for every build. Narrative
+builds additionally use `One Prompt, One Build`, `The Animation Bar` and their
+chosen rendering recipe; educational builds go directly to the canonical UI/
+inspection and construction contracts. `The Look Contract` is pixel-only.
+
+| Before advancing | One source of truth / required evidence |
+| --- | --- |
+| First mesh | Filled `templates/DESIGN.md`: complete object, essential parts, source provenance and shared mating frames |
+| Repeated assembly | `Construction regression gates`: every instance, actual axes/bores and end-plane separation; not one good sample |
+| Requested selection | `Canonical educational UI and inspection contract`: reuse selection behavior only as requested; no narrative education card/lessons/labels. Verify visible emphasis, keyboard equivalent and exact restoration |
+| Claimed pass | `Verification`: nonempty actual geometry, expected counts, negative injections and fresh build hash tied to the report |
+
+This table indexes existing acceptance rules; detailed tests live only in the
+sections named here. Read other subject recipes only when the build uses them.
+
+## Render Preset Gate (ask once, every project)
+
+Before the first mesh or presentation work, ask using the structured-choice tool when available. Keep labels and one-sentence consequences visible:
+
+> **Which look should I build this in?**
+>
+> 1. **Classic Pixel Art (Recommended)** — The original finer palette-snapped miniature look with ink contours and ordered dither.
+> 2. **Stroked Toon / Illustrated Miniature** — Smooth bevelled parts, stepped shading and fine charcoal outlines.
+> 3. **Pixel + Stroke** — Toon shading and outlines on a low-resolution pixel grid.
+
+Map answers respectively to `pixel`, `stroked-toon`, `pixel-stroke`. Generic “pixel art”, explicit classic and explicit delegation select `pixel`; silence waits. A reference image alone does not settle a materially ambiguous request. Do not repeat the question per material or repair. Record the answer verbatim in DESIGN, including the preset ID and renderer implementation. Every preset supports free orbit and deterministic hero reset; no second orbit question. After the look answer, ask the sourcing question next unless already answered. While either is pending, inspect local files and research the subject, but do not start detailed geometry, model downloads or a presentation implementation that commits the unanswered choice.
+
+## Model Sourcing Gate (ask next, once per project)
+
+> **How should I create the models?**
+>
+> 1. **Hybrid — source + custom-build (Recommended)** — Search for commercially usable models, download and use the ones that fit, then model missing or scene-specific pieces myself.
+> 2. **Internet models throughout** — Search for and use commercially usable downloaded models for all major roles; focus my work on assembly, styling, rigging and animation.
+> 3. **Fully agent-modeled** — Build all scene geometry myself for a unified custom look, without downloading third-party models.
+
+This is a separate question after style, not a hidden assumption or a confused “pixel hybrid” choice. Use stable question ID `asset-strategy`, single-select, and map answers to `hybrid`, `internet-full`, `authored-only`. Record exact user wording. Explicit delegation selects hybrid; silence waits. Explicit requests for original/procedural geometry answer authored-only; an offline deliverable alone does NOT mean authored-only (permitted assets can be packaged locally).
+
+- **Hybrid:** actually search for every missing major role and use fitting licensed candidates; fill documented gaps with authored geometry. A token imported prop does not satisfy sourcing the hero/cast/buildings. Do not search and then hand-build suitable assets out of habit.
+- **Internet models throughout:** source the hero and all major supporting roles. Scale/material changes, pivots, adapters, collision proxies and simple joining/support geometry are allowed; quietly hand-building a missing hero is not. If no fitting licensed major asset exists, report the specific gap and offer a subject substitute or permission to switch that role to hybrid. Do not guarantee a full matching library before searching, and do not force an unsuitable model just to fill a quota.
+- **Fully agent-modeled:** author all visible model geometry, including hero and supporting roles. Subject/photo/motion references and coding/rendering libraries remain allowed; this choice does not mean “no internet research”. Do not download model packs, use an imported model as a hidden starting point, or downgrade the detail/animation/contact bar. User-provided models require an explicit exception if this mode is selected.
+- **Commercially usable, not merely commercially available:** in BOTH internet modes verify the actual per-asset license permits commercial use, modification and redistribution/embedding in the delivered scene. Prefer free CC0/compatible CC-BY; preserve required credits, modifications and license notices, check dependencies and package offline. Unknown rights, NC, ND, editorial/personal-only and incompatible licenses fail. Availability for sale is not a rights check. No purchases or subscriptions without separate explicit approval. Explain this briefly with the question; do not overwhelm it with legal boilerplate.
+- **Honest exceptions:** unavailable search/download access is not “nothing suitable found”. Disclose the limitation and ask before changing a selected sourcing mode. New choices do not waive subject accuracy or mandatory verification and add no educational UI.
+
+**Pre-build decision receipt:** after both answers, state one short line such as “Classic Pixel Art · hybrid sourcing · narrative · minimal controls”, then record the choices in DESIGN. Before delivery reconcile each major role against its chosen source mode and record native render dimensions, scaling and style crops. Missing answers, unsupported render-preset claims or unapproved sourcing switches cannot pass QA.
### Fast path by scene
| If the commission is... | Read next, in this order |
| --- | --- |
+| explicit explanation / guided how-it-works (not a machine or cutaway view alone) | Educational Mechanism Profile → Universal Inspection Controls → chosen render preset → Machine Grammar → Verification (profile-aware) |
| market, food truck, bakery, cafe, shop, laundromat | Cast → Clothed Cast: Heads, Layers, Hands → Service And Queue → Machine Grammar → Carrying, Loading And Mounting → Verification |
| heist, defence, combat | Detail Bar → Tool/Tower recipes → System And Combat Animation → Combat Readability → Verification |
| creature battle, game scene, anime/movie fight | Research Before You Model → Field Notes: Two-Creature Combat → Creature Anatomy → System And Combat Animation → Combat Readability → Verification |
@@ -36,16 +149,20 @@ reading every vehicle or water note for a kitchen scene.
| stage, festival, parade | Cast → Secondary Motion → Crowd Variation → System Grammar → Verification |
| farm, garden, nature | Creature Anatomy → Ambient Loops → Effects → Verification |
-The universal shape still applies: place + repeated ritual + interruption +
-consequence. The fast path only decides which reference notes to read first.
+The narrative shape is place + repeated ritual + interruption + consequence.
+Educational scenes instead use mechanism + causal sequence + observable result;
+do not add a fictional interruption or cast. The fast path selects the relevant
+reference notes, not extra narrative requirements.
## When to Use
+- Educational "how does this work?" mechanisms, cutaways and step-through
+ causal explanations; use the Educational Mechanism Profile, not cast quotas.
- "Make a small diorama / miniature scene / pixel scene of X"
- A clip or still shows a flat cut-out scene with chunky pixels and little
people, and the ask is to match that look
- An existing 3D scene needs the pixel-art presentation (palette, dither, ink,
- locked angle) rather than a smooth render
+ reset hero angle plus orbit) rather than a smooth render
- The figures need believable motion: walking, climbing into a car, sitting,
swimming, diving, and it has to survive close inspection
- The ask is for a *staged diorama*, not a model: several systems, a cast, a goal or boss,
@@ -54,8 +171,8 @@ consequence. The fast path only decides which reference notes to read first.
siege"); this skill is designed to turn that into a complete commission
without an interview
-Don't use for full-resolution product renders, photoreal scenes, or anything
-that needs free orbit controls.
+Don't use for photoreal scenes or full-resolution photographic product renders.
+Every scene MUST support free user orbit by default, including pixel, stroked-toon and pixel-stroke. No separate orbit consent exists. Keep a deterministic hero angle for QA/reset, never auto-spin.
## Research Before You Model
@@ -99,7 +216,7 @@ Rules that come out of doing this repeatedly:
### 2. Model sourcing: check the libraries before you build
-Hand-building a creature from primitives is the *last* option, not the first. A
+Internet-first sourcing applies to ALL major scene roles, not only creatures. Acquire and use fitting commercially licensed models by default; hand-build only a documented gap or explicit original-geometry request. Hand-building a creature from primitives is the *last* option, not the first. A
rigged download with real deformation and usable clips beats four hundred lines
of spheres the moment the camera comes within a metre. Search first, and keep a
record of what you searched.
@@ -249,12 +366,15 @@ questionnaire. Make the creative decisions, state them in one short assumption
line, and build the whole diorama. Do not stop at a plan, a blockout or a design
sheet and wait for approval.
-The only reasons to ask are credentials, a destructive action, or a path that
-would overwrite the user's work. Everything else is a default.
+The only reasons to ask are credentials, a destructive action, a path that
+would overwrite the user's work, **or the `Render Preset Gate`**. That gate is a
+deliberate exception to autonomous assumptions: one question, once per project,
+before the first mesh. Everything else is a default.
### Step 0, before the assumption line
-Run the three lookups in `Research Before You Model` first:
+Ask the `Render Preset Gate` question first, then run the three lookups in
+`Research Before You Model`:
1. Step the real subject into frames and write down its motion grammar.
2. Walk the sourcing ladder for every hero asset (disk, CC0, CC-BY, hand-build),
@@ -411,8 +531,7 @@ blockout towers with one fire animation.
- **One project, one build loop.** Scaffold once, then build, shoot and fix in
place. Do not rewrite the entry file for a detail that lives in a prop module.
-- **Build only what the locked camera sees.** Spend the polygon and part budget
- on the +Z face and the top; simplify the back.
+- **Build for orbit inspection.** Prioritise the hero view, but construct every exposed back, support, cavity and joint coherently.
- **Cut systems before detail.** A tight build with two rich towers and five
animation layers reads better than six thin towers with one recoil.
- **Use the templates.** Camera, post, palette, lighting, the cast rig and the
@@ -456,7 +575,7 @@ do not ask the user to complete it.
has no visible consequence, cut it.
4. Pick five beats and five QA timestamps. A beat without a timestamp is not
staged.
-5. Block out in grey at the locked camera and shoot the five beats at 1:1.
+5. Block out in grey at the reset hero camera and shoot the five beats at 1:1.
This is a staging check, not a production pass: no palette, no post, no
materials. Redesign staging before committing to it.
6. Once the blockout reads, run the production pipeline below. Palette is the
@@ -465,13 +584,437 @@ do not ask the user to complete it.
The rest of this file is the recipe for each pass.
+## Educational Mechanism Profile (first-class exception)
+
+**UI and inspection authority:** `Canonical educational UI and inspection contract`
+below owns placement, controls, lessons, selection, focus and restoration. Follow
+it rather than inferring defaults from older screenshots. The render preset gate
+and free orbit apply unchanged.
+
+Choose `sceneProfile: educational` for explicit explanations, guided technical cutaways and how-it-works teaching requests—not a machine subject, rotation or a cutaway view alone. This profile takes precedence over ALL narrative quotas below: no mandatory cast, disruption, ritual, landmark, three systems, ambient loops, five actor layers or decorative story props. One accurately constructed mechanism and one clear causal sequence is sufficient. Do not invent a crowd or combat to satisfy the router. Research and construction accuracy remain mandatory; simple UI never means missing mechanical parts.
+
+- **UI, selection and lessons:** when enabled/requested, use the canonical contract below; explicit UI-free briefs omit panels/lesson controls. No second toolbar, competing material cache or explanatory clock.
+- **Component manifest is a hard delivery artifact:** record each essential part's ID, assembly/parent, function, supporting joint/bearing/fastener, input/output connection, motion law, units, source and tolerance, mesh/group mapping, selectable anchor and proof frame. Include otherwise obscured shafts, cams, rods, links, valve gear, ports, supports and housings when functionally relevant. Explicitly state omissions and symbolic simplifications before acceptance; never substitute a label for missing construction.
+- **Mechanics are coupled, not independently looped:** derive all driven transforms from a shared phase/driver. Write and test actual ratios, directions, phase offsets, link lengths, kinematic equations, contact/clearance and event timing. For an engine, for example, verify crank:cam 2:1 over a 720° four-stroke cycle, connecting-rod length and piston stroke, valve lift/seat contact and opening order; do not copy these ratios into unrelated mechanisms. Check contacts across motion, not only at the hero frame.
+- **Nothing passes through another solid:** this is a hard acceptance rule for EVERY profile and preset, including educational scenes. Test non-contact pairs over the complete motion range and at contact transitions, not just one still. Declare intended joints/contact surfaces and numeric tolerances; all other swept bodies must keep positive clearance. Include complete geometry (tips, tails, bevels, fasteners and attachment arms), not only centres/anchors. In an engine, test actual piston-crown/valve-head/spark-plug bounds and actual cam/follower surfaces at dense phase samples. Do not move independent parts with unrelated sine waves, hide a collision with a cutaway, turn off depth testing, or use transparency/labels to pretend it is fixed. First solve the constraint or alter the geometry. Every shaft, piston, rod or sliding member that crosses a fixed wall/flange needs a REAL bored hole, slot or cutaway opening with measured swept clearance; a solid shelf with a dark circle painted on it is a failure. Test the moving body against the actual structural mesh at the crossing plane, including the lowest/full-travel pose. Ignition flames, gas arrows and pressure indicators must also stay in the moving free volume: their full tips/tails/width must not cross the piston, liner, valves or plug. Keep depth testing on; an explicit x-ray teaching mode must be separately selected and clearly identified, never the default. Capture before/contact/after frames from at least two useful orbit angles. A failed or unrun penetration check blocks acceptance.
+- **Hard acceptance, not promises about agents:** reject delivery until the manifest has no unexplained missing essentials; numeric invariant tests pass at boundaries and dense cycle samples; repeated `freeze(t)` yields identical state; desktop/phone hero frames and front/back/high orbit crops are reviewed; a motion strip proves causal order, contact and no interpenetration; controls, pointer-drag vs click, keyboard selection/focus and reset are tested. Store actual commands/results and tolerances in `qa/report.json`. An unrun check is UNVERIFIED, never a pass. These gates make omissions detectable; no skill can guarantee every future agent complies.
+- **Profile-aware QA:** retain finite geometry, console, deterministic time, contact and motion checks for every preset. Pixel uses palette/dither checks; toon uses native contour/material checks; hybrid checks low-res target + nearest upscale + only one outline pipeline. Educational off-white (and the canonical single UI surface only when enabled) replace white-empty-paper/cast/ritual quotas explicitly; do not silence unrelated failures. Fixed-camera assertions apply only after `orbit.reset()`, never during user inspection.
+
+## Canonical educational UI and inspection contract
+
+This is the single authority for educational UI, selection and lesson behavior. **EDUCATIONAL / EXPLICITLY REQUESTED FEATURES ONLY: ordinary narrative scenes skip this chapter and its UI tests. Requested narrative inspection may reuse only its selection behavior; do not add the card, lessons or teaching labels.**
+The exact V8 tokens/hierarchy below remain the 3.16 visual contract.
+
+**Use code, not an interpretation of “shadcn-style”.** For new educational scenes WITH the educational UI enabled (not an explicit UI-free brief), copy `templates/education-v8.css` and build the DOM hierarchy below. UI-free educational scenes skip this chapter's DOM and UI tests; narrative scenes do not inherit it.
+This is the canonical visual contract extracted from the V8 explorer, independent
+of the chosen 3D render preset. Default to its ONE right card / mobile bottom dock;
+do not substitute the older bottom/center examples as new-build defaults.
+An explicitly requested bottom/center dock may change placement only, retaining
+these tokens, controls and hierarchy. Existing repairs preserve requested placement.
+The older `education-dock.css` is a minimal helper, NOT the V8 visual reference;
+do not use it as the visual starting point for new educational builds.
+
+Evidence: the grandfather-clock drift used beige/brass UI, a separate top-left
+title, translucent blurred panel and fixed top-to-bottom height. None follows
+from a clock subject. Brass belongs on the clock, not on its application chrome.
+
+### Exact visual values (copy the CSS; do not restyle per subject)
+
+- Page `#f7f7f5`, opaque card `#fff`, ink `#18181b`, muted `#71717a`,
+ border `#e4e4e7`, secondary `#f4f4f5`, focus/accent `#2563eb`.
+- System sans, base 14px/1.5. Desktop heading 21px/1.35, weight 650,
+ letter spacing -0.6px; mobile 19px. Supporting copy and buttons 12px.
+- Desktop `.viewer`: grid `minmax(0,1fr) 360px`, right padding 24px,
+ height 100dvh, vertically centered card. Stage is the first grid cell, NOT
+ a fullscreen canvas underneath an overlay. Card is content-height, max
+ `calc(100dvh - 48px)`, 22px padding, 18px gap, 14px radius, 1px border,
+ shadow `0 1px 3px #18181b08, 0 8px 32px #18181b03`.
+- Below/equal 880px: one column, rows `minmax(0,1fr) auto`; dock max-height
+ 48dvh, full width, top corners 14px, padding 16px 18px plus safe-area bottom.
+ Measure the actual remaining stage for camera fit and renderer sizing.
+- Two segmented tabs: secondary background, 4px inset, 9px outer radius;
+ selected tab white with subtle shadow. Primary playback is dark ink/white,
+ not subject-coloured. Controls 36px desktop / 40px mobile; maintain adequate
+ touch targets (44px hit regions where needed without crowding the row).
+- No beige/brown UI substitutions, serif/display fonts, uppercase eyebrow,
+ translucent glass, backdrop blur, heavy shadow, detached title, always-open
+ technical sections, extra dashboards or full-height panel. Do not grow a short
+ card to fill its max-height. Subject geometry/materials remain subject-specific.
+
+### DOM skeleton and state adapter
+
+```html
+<main class="viewer">
+ <div class="stage-wrap">
+ <canvas id="stage" tabindex="0" aria-label="Interactive mechanism; drag to orbit"></canvas>
+ <p class="gesture">Drag to orbit · scroll to zoom · click a part</p>
+ </div>
+ <aside class="panel" aria-label="Mechanism controls and explanation">
+ <div class="panel-top">
+ <header class="panel-head">
+ <div class="title-row"><h1>Subject name</h1><span class="badge">Interactive</span></div>
+ <p class="lede">Short input → change → output summary.</p>
+ </header>
+ <div class="tabs" role="tablist" aria-label="Mode">
+ <button id="tab-explore" role="tab" aria-selected="true" aria-controls="explore-panel">Explore</button>
+ <button id="tab-learn" role="tab" aria-selected="false" aria-controls="learn-panel" tabindex="-1">How it works</button>
+ </div>
+ <div class="controls" role="group" aria-label="Playback">
+ <button class="btn primary" id="play">Pause</button>
+ <button class="btn icon" id="prev" aria-label="Previous step">‹</button>
+ <button class="btn icon" id="next" aria-label="Next step">›</button>
+ <button class="btn icon" id="home" aria-label="Reset view">↺</button>
+ <button class="btn toggle" id="xray" aria-pressed="false">Inside</button>
+ </div>
+ </div>
+ <section id="learn-panel" role="tabpanel" aria-labelledby="tab-learn" hidden>
+ <p class="section-note">One short instruction.</p>
+ <div class="lesson-steps" role="group" aria-label="Causal steps"><!-- subject steps --></div>
+ </section>
+ <div class="readout">
+ <p class="phase-title" id="phaseTitle"></p>
+ <p class="phase-meta" id="phaseMeta"></p>
+ <p class="explain" id="explainText"></p>
+ </div>
+ <button class="link" id="clearPart" hidden>← Back to cycle</button>
+ <section id="explore-panel" role="tabpanel" aria-labelledby="tab-explore">
+ <label class="label" for="parts">Inspect a part</label>
+ <select id="parts"><option value="">Choose a part…</option></select>
+ </section>
+ <details class="disclosure help"><summary>About this model</summary>
+ <p class="section-note">Simplifications and keyboard help.</p>
+ </details>
+ <p class="sr-only" role="status" aria-live="polite" id="announcer"></p>
+ </aside>
+</main>
+```
+
+Adapt subject names, number of lesson steps, part IDs, explanatory text and
+physical units only. Omit Inside for a mechanism with no enclosing shell; never
+add a fake x-ray toggle. Optional scrubber/Back lives in this same surface, not a
+second toolbar. Use line SVG icons matching the supplied CSS in production.
+Implement tab click plus ArrowLeft/Right/Home/End roving tabindex, hidden panel
+state, and semantic buttons/select/range. Bind controls to the actual evaluator:
+`play/pause`, `freeze(step.phase)`, `orbit.reset`, reversible `inside`,
+`selectPart(id)` and `clearSelection`. A lesson change freezes synchronously and
+updates explanation from that state; it must not trigger automatic camera motion.
+The skeleton/CSS is not a functioning controller; do not ship inert controls.
+
+### Three regression gates
+
+1. **Computed-style/structure:** at 1280×800 assert one card, one h1 INSIDE it,
+ 360px card column, opaque white card, exact neutral tokens, no backdrop filter,
+ content-height card, closed About and Explore selected initially. At 390×844
+ and 320×640 assert one bottom dock, no horizontal overflow and an uncovered
+ nonzero stage. Inject beige tokens, detached title and full-height panel; each
+ must fail the check. Record measured values, not just “V8-like”.
+2. **Rendered evidence:** review desktop, phone and 200% zoom screenshots plus
+ selected/restored states. Check actual background pixels against the authored
+ paper (not merely body CSS), tiny-part readability, stage/card separation and
+ front/back/high camera fits. For V8 matching use `#f7f7f5` consistently in CSS,
+ renderer clear/scene and ground composition; user-requested white overrides all
+ those together. A screenshot is not mechanical clearance proof.
+3. **Interaction:** keyboard-only tabs/steps/picker/reset, paused orbit, drag vs
+ selection, Inside lifecycle and shared-material restoration must pass existing
+ per-scene gates. Store commands, values and proof paths in `qa/report.json`;
+ missing browser/computed-style/visual checks remain UNVERIFIED.
+
+### Selection, focus and lesson adapter
+
+Raycast actual visible geometry: nearest eligible hit wins, respecting nearer
+opaque occluders. Map the hit mesh to both its assembly ID and its actual piece
+ID; assembly selection and clicked-mesh selection are distinct scopes. The
+single labelled keyboard piece picker must expose the same pieces/actions,
+including hidden pieces; never silently broaden a click to an entire assembly.
+Show one short explanation in the card. An optional single label uses a live
+geometry-local anchor and hides behind camera, offscreen or when occluded.
+
+A deliberate canvas/picker Inspect selection may make one short useful camera
+AND OrbitControls-target transition to live selected bounds. Avoid end-on shafts
+and blocking housings; use an authored reveal/cutaway for hidden pieces and
+report remaining occlusion honestly. Save the prior view for Back; Reset restores
+the hero. User orbit/pointer/keyboard navigation cancels the tween immediately.
+Reduced motion uses an immediate useful view. Never auto-spin, chase moving parts
+or restart focus per frame. Lesson step selection instead pauses and synchronously
+freezes the real evaluator, highlights its part and updates phase/text/readout
+without moving the camera; only an explicit Inspect action focuses. Scrubbing
+updates the lesson from evaluated state, not an independent clock. Announce
+intentional changes politely, not each frame.
+
+Use semantic buttons/select/range, visible focus and non-colour part-name cues;
+canvas arrows orbit and R resets. Tabs implement roving focus and keyboard
+navigation; no focus trap. Drag/multitouch is orbit, not click (use the movement
+threshold/cancel handling in `templates/orbit.js`); UI gestures never bubble into
+the stage. Paused and reduced-motion modes retain inspection.
+
+### Soft glow and holographic inspection — implementation recipe
+
+This is an **inspection overlay**, not a new render preset, bloom pass or a way to hide modelling errors. Use the same mechanism for a selected gear, valve, pump impeller, drawer slide or anatomical structure. The V8 selection implementation is the calibration evidence: restrained warm material lift, dimmed context, transparent outer castings and selective gold feature edges. Do not interpret “glow” as a white emissive blob.
+
+**1. Preserve and derive, never mutate the shared originals.** Build a registry once from the actual selectable meshes, BEFORE adding overlays. Store each exact original material reference, including arrays of material slots; a mesh's slot array itself must also be restored by identity. Derive cached variants from each source UUID plus mode. Clone `userData` and `outlineParameters` before changing outline alpha, since nested objects may otherwise be shared. Keep toon ramps, texture maps, roughness and existing supported preset properties. Restore the originals before applying each new selection/X-ray state, not by attempting to reverse colour arithmetic.
+
+Use `templates/inspection.js` rather than duplicating a second material controller.
+Its API is `createInspection(THREE, {parts, contextMeshes, resolveVisibility,
+onChange, style})`, with `select({partId, mesh})`, `clear()`, `refresh()`,
+`dispose()` and `piecePickerEntries(partId, {visibleOnly:false})` (includes hidden
+pieces for keyboard inspection). Validate actual mesh membership before selection.
+The helper supports rigid meshes only; reject skinned/instanced/morph assumptions.
+`resolveVisibility` returns named `hiddenPartIds`/`hiddenMeshes` plus `description`
+for an authored cover removal. Hiding requires `shell:true`, or an explicit
+`inspectionOccluder:true` part plus an active selection and nonempty cutaway
+description; that latter exception may remove an upper gear/bridge to expose a
+lower part, never hide construction failures. Optional `ghostPartIds`/`ghostMeshes`
+are accepted only for `shell:true`. Selected assemblies/pieces remain visible;
+context meshes (floor/stand/UI) cannot hide, ghost or dim.
+Unknown parts, duplicate ownership, empty geometry and unsupported material or
+deformation paths fail explicitly. Never request a whole-mechanism ghost. The host owns
+camera focus, picking and V8 DOM; the helper owns emphasis/restoration, not UI or
+mechanical certification. Cached variants derive per original material and mode; never
+from the currently displayed variant. Lift colour gently; write emissive values
+only where the original material supports them. Dim context as opaque solids.
+Only the explicit housing reveal below may change transparency/depth-write.
+
+**2. Reveal only manifest-authorized occluders; ghosting is shell-only. Never defeat depth on the selected part.** Declare `internalPartIds` and `occludingShellIds` per subject in the component manifest. For an internal selection, remove authored covers or optionally ghost only declared outer housings that obscure it; keep the selected part solid, retain non-selected internals as dim solids, and leave floor/stand/UI alone. A global Inside toggle applies that same named reveal plan without dimming all internals. A selected housing stays highlighted rather than ghosting itself. Unlisted opaque solids must still occlude correctly: `renderOrder` does not override the depth buffer. For an internal blocker, author an explained selection-only `inspectionOccluder:true` removal plan; the independent Inside toggle still affects shells only. Hidden siblings need a piece-level plan and cannot remove the selected scope. Do not set `depthTest=false`, use additive whole-body overlays, or fade all solids to pretend a mechanism is correctly constructed. Picker rays ignore generated edges and ghost-shell hits, but respect remaining opaque foreground objects; click and picker share the same selection action.
+
+**3. Make the hologram from feature edges, attached to the live part.** Do not use `wireframe:true`: that exposes triangle diagonals. Use `EdgesGeometry(source.geometry, 32)` and a restrained `LineBasicMaterial` (`color:0xffc35c`, `opacity:0.5`, `transparent:true`, `depthTest:true`, `depthWrite:false`, `toneMapped:false`). Normal blending, no bloom. Exclude slivers, ring grooves, gaskets and tiny bolts when edges become noise; the V8 thresholds were minimum dimension 0.018 units and, for cast housings, volume 0.006 units³. Those are **model-scale-dependent starting values**, not universal dimensions. Use one physical edge overlay on the selected component only, not a second full-scene OutlineEffect/Sobel pipeline. Its surface outline may need suppression to avoid doubled contours. WebGL line width is generally one device pixel: do not promise a controllable CSS-pixel width through `linewidth`.
+
+Attach each owned edge overlay as an identity-transform child of its live source
+mesh; mark it as an inspection overlay and exclude it from raycasting. On change,
+remove and dispose owned overlays, never source geometry or shared maps.
+
+This child pattern follows moving rigid geometry without copying a stale pose. If an overlay must be a sibling/world-space object, synchronise its transform from the source every evaluation; copying position/quaternion once is insufficient when the source mesh moves. `EdgesGeometry` does **not** automatically follow vertex deformation or per-instance transforms: skinned/morphed/instanced subjects need a deformation-aware shader/overlay or a clearly declared unsupported path. Never claim those supported because a rigid V8 example works. Do not dispose the source geometry, shared source maps, shared toon ramps or original materials; dispose only owned variants/edge geometries and owned overlay materials. Keep overlay generation bounded to selection changes, never create/dispose hundreds of edge objects every frame.
+
+**State and restoration contract.** One selection controller owns this effect. Resolve in order: restore exact originals → remove previous edges → compute selected/internal/Inside state → ghost selected occluding housings → highlight selected meshes → dim remaining mechanism meshes → attach selected edges. Re-apply from originals when Inside changes. Leaving How it works restores its earlier Inside state and removes its tutorial tint; clearing selection retains an independently enabled Inside toggle. Picker, canvas, keyboard and lesson adapters must not compete by writing materials from separate uncoordinated caches. Clear/reset/teardown restores material references, opacity/depth/blending/outline state, selection/readout and authored camera state; only teardown disposes long-lived caches. Respect reduced motion; avoid automatic pulsing, scanlines or flashing. Keep the part name and keyboard focus as non-colour cues.
+
+**Historical evidence (not project dependencies):** `quartz-watch/shots/highlights/dialPost1.png`,
+`quartz-watch/shots/highlights/dialPost2.png`, `quartz-watch/shots/highlights/dialPost3.png`,
+`quartz-watch/shots/highlights/dialPost4.png`, `quartz-watch/shots/highlights/individual-piece.png`,
+`quartz-watch/shots/highlights/rotor.png`, `quartz-watch/shots/highlights/reduction.png`,
+`quartz-watch/qa/highlights-report.json` and `quartz-watch/qa/construction-report.json`.
+These record this repair, not files future users must have. Twenty-six assembly
+glow states had numerical tests/captures; only a subset received visual review.
+Do not present that as universal contrast certification.
+
+**Evidence and test — selection contract (3.18).** Quartz-watch selection was
+almost invisible, posts were end-on/occluded, and adding emitter properties to
+MeshBasicMaterial caused a `shader.value` error. Use `templates/inspection.js`,
+with `templates/qa/inspection.test.mjs` and
+`templates/qa/inspection-browser.mjs`; use the API above. Assert assembly versus actual clicked-piece identity,
+keyboard equivalence, nearest opaque occlusion, and obvious visible glow with
+retained shape/colour (never a white blob) in desktop/phone crops. Test shared
+and array materials, Basic/toon, two frozen phases, moving/orbiting, rapid changes,
+Inside/clear/Back/Reset/lesson exit, interrupted focus and reduced motion. Restore
+exact original material AND slot-array identities, shadow flags and `visible`
+state, plus original material properties; test source immutability and owned-only
+disposal with stable overlay/material counts. Basic materials must never gain
+`emissive` or `emissiveIntensity`, even temporarily; feature-test capability before
+writing, and assert absent properties remain absent. Verify shader compilation
+and no console errors in the fresh browser build. Scalar/material tests alone do
+not establish visible contrast, depth correctness or useful focus.
+
+## Repair acceptance: enclosure, fit and reference UI (3.15)
+
+Use this short checklist for existing educational scenes before re-reading narrative
+recipes. Evidence: the LEAP-1B repair was requested because its permanent section
+exposed the core, its fit cropped the model, its beige background and crowded panel
+did not match the requested V8 reference. These checks supplement mechanical QA;
+passing enclosure rays or a screenshot does not certify a complete mechanism.
+
+1. **Closed first, explicit Inside.** Unless a permanent section is commissioned,
+ cold load and hero Reset show the complete opaque housing, no tutorial tint,
+ Inside off. Build the missing casing as real connected wall geometry while
+ preserving inlet/outlet openings; a toggle cannot repair absent geometry.
+ Inside is a named semantic button in the single surface. Internal picker or
+ lesson selection may explicitly activate it, but must update its pressed state;
+ leaving the lesson restores the preceding Inside state. Clearing selection
+ preserves an independently enabled Inside state. **Test:** load → Inside on/off
+ → internal selection → clear → lesson exit → Reset; check visible ancestors,
+ nearest opaque ray hits, exact material restoration and open-mouth rays.
+2. **Fit the assembly in the space actually available.** Measure canvas layout
+ after the dock/panel; use actual complete assembly bounds including covers,
+ supports and swept extrema, not a default slab. Fit the safe rectangle with
+ padding; if UI overlays the canvas, solve its offset as well as distance.
+ With direction target→camera, depth is `distance - along`, so each fit bound
+ contributes `abs(transverse)/tanHalf + along` (not minus along). Do not clamp
+ distance below the solved fit or distort portrait aspect. Re-measure on layout,
+ disclosure, resize/orientation and zoom changes without hijacking user orbit.
+ **Test:** project covered/exposed swept bounds at desktop, tablet, 390×844,
+ 320×640 and 200% zoom, with lesson/disclosure open; front/back/high captures;
+ fail an injected protrusion and verify near-plane/focus fits separately.
+3. **UI repair:** compare the supplied reference before changing placement;
+ apply `Canonical educational UI and inspection contract`, including rendered
+ background, accessible lesson state and desktop/phone/200% zoom gates. Do not
+ copy the reference subject or introduce a second surface.
+
+## Construction regression gates
+
+These construction rules apply across subjects and all render presets; they supplement, not replace, the style gate and profile-aware verification above. They make known failures testable, not impossible.
+
+1. **Specify the mating interface before decorating the part.** Extend the component manifest with units, parent-local frame, shaft/bore/slide axes, shared joint/port anchor IDs, mating surfaces, nominal dimensions and radial/axial tolerances. Derive both mating meshes and their motion from those anchors, not repeated guessed offsets. A bearing eye needs a real through-bore; its beam, cap, bolt and bevel must stop outside that bore. Budget bevel/fillet intrusion in the actual construction method (inward bevels reduce usable bore), axial lane widths, spacers, end float and end stops. Check coaxial alignment and anchor residual after parent transforms. Model the load path through real bearings, brackets, fasteners and a base; route each functional port through an actual connected opening to its destination, not a hose ending inside a solid. Document symbolic/omitted internals. **Evidence:** V8 running-gear repair found a centred rod beam cutting its crankpin despite an annular eye, bank stagger applied to only one mating member, and fillets facing the wrong local axis. **Test:** local-axis/anchor tests, measured bore plus bevel allowance and axial stack tests, section crops from two orbit directions, and traced port/support connections. Record geometry revision and proof frames in the manifest. Copy `templates/mechanism-contract.mjs` and fill the interface and connection sheets in `templates/DESIGN.md`; the helper validates scalar budgets, not arbitrary mesh bores or load strength.
+
+2. **Audit the complete swept assembly, with narrowly scoped intended contact.** Derive every driven pose from one driver and test the actual transformed meshes or documented conservative collision proxies, including beams, caps, fasteners, webs, fillets and supports. Broad-phase boxes alone neither detect holes correctly nor prove clearance. Enumerate potentially interacting pairs and coverage; whitelist only a named pair of mating surfaces with phase window, normal-gap/penetration tolerance and rationale (bearing/journal, meshing teeth, valve/seat), never an entire assembly or all pairs of a part type. All other pairs need the declared positive clearance. Check full travel, extrema, cycle seam, contact transitions and close-approach intervals with refinement; include ports/FX containment. Report method, sample spacing, tolerance, worst phase/pair, exclusions and unresolved regions. Dense sampled vertex/triangle tests are bounded evidence, not continuous exact collision proof: use analytic bounds or conservative continuous checks where available, otherwise retain that limitation explicitly and block unsupported clearance claims. **Evidence:** the V8 12/12 invariant report omitted rod/crank interference; the later rod probe added bore triangle samples, axial lanes, journal vertices, anchor residual and fillet axes. **Test:** intentionally inject a beam-through-bore, wrong-axis fillet, too-wide lane, out-of-window contact and a non-whitelisted overlap; each must fail. Run full-cycle probes plus before/contact/after crops from two angles. `templates/qa/mechanism-contract.test.mjs` tests budget/contact-policy failure detection only; per-scene geometry/sweep checks remain mandatory and UNVERIFIED until run.
+
+3. **Repeated interfaces share anchors and axes (3.18 evidence + test).**
+ Generate ALL repeated mating members from one anchor/axis table, not just the
+ first working example. Quartz-watch pads at radius 12.6 missed posts at 13;
+ rotating a native CylinderGeometry about Y did not redirect its native Y axis.
+ The seconds shaft opposed its hand and the model lacked a physical 60:1 stage.
+ Coplanar shaft-cap fans z-fought. Use transformed local axes (quaternion maps
+ native Y to the declared axis), common anchors, real through-bores and a single
+ end surface or measured axial separation; never hide coplanar caps with depth
+ overrides. Derive ratio/direction from the actual connected transmission, not
+ only a display hand formula. **Test:** with `templates/mechanism-contract.mjs`
+ shared anchors/checkRepeatedInterfaces/checkEndPlanes, enumerate every pad,
+ post, bore, cap and shaft; assert count, transformed axis/anchor residual,
+ radial/axial clearance and physical ratio/direction across the full cycle.
+ The repaired watch measured zero residual at all four pad anchors and 0.08
+ board-bore radial clearance; those are historical measurements, not defaults.
+ Inject one displaced repeat, wrong native axis, sealed bore, reversed shaft,
+ missing reduction and coplanar cap; each relevant check must fail. Review
+ section/end-on and oblique crops; scalars cannot prove real mesh openings.
+ Evidence: the historical construction report and highlight shots above.
+
+Lesson/UI behavior and its tests are defined once in `Canonical educational UI
+and inspection contract`. `templates/education-dock.mjs` remains a dependency-free
+state helper with `templates/qa/education-dock.test.mjs`; its older CSS is not the
+V8 visual authority.
+
+## Universal Inspection Controls
+
+Copy `templates/orbit.js` for EVERY scene and preset. Create it after camera fit with the fitted target; keep animation evaluation independent of camera interaction. Render on control change even when paused. Expose `orbit.reset()` and have the QA freeze wrapper reset it before capture (`freeze(t)` evaluates time synchronously). User pause/freeze UI need not reset their chosen inspection angle. Fit zoom/polar limits to real subject bounds without preventing back/high inspection. No auto-rotation, no camera motion driven by the animation clock. Keep reset + a brief drag/keyboard hint accessible; educational controls and selection follow `Canonical educational UI and inspection contract`.
+
+## Optional Pixel + Stroke Hybrid
+
+`pixel-stroke` is a third style, not the pixel default, and it is selected through the single `Render Preset Gate` question — never inferred, never switched to later without a new answer. Record the answer and do not offer it again during the build. Rotation is mandatory regardless of the answer.
+
+Copy `templates/pixel-stroke.js` plus `templates/stroked-toon.js`. Create WebGLRenderer with antialias false, alpha true. Use `createPixelStroke(renderer, {width:320,height:200})`, its `toon`/`flat` material factories and `render(scene,camera)`. Resize the low-resolution target explicitly with `look.setSize(bufferW,bufferH)` while sizing the renderer to the display aspect; keep target aspect aligned to viewport/camera. Toon lighting/materials plus selective geometry OutlineEffect render into that target, then ONE nearest-neighbour fullscreen upscale. Do not run PixelPost, Sobel ink, a second outline pass or CSS blur over it. Native-resolution DOM UI is outside the target and must remain crisp.
+
+OutlineEffect thickness is a projected effect parameter, NOT a CSS-pixel width. Rasterisation happens at the low-resolution target: a one-target-pixel contour becomes approximately `displayWidth / targetWidth` CSS pixels after upscale (analogous vertically). A thinner subpixel outline can disappear or flicker; measure target and screen crops at desktop/phone, adjust target resolution and selective material stroke together. Disable outlines for inward cavity surfaces, liquids, films, transparent glass, vapour and contact patches; do not double edges. For native toon, measure the native-DPR render instead. Free orbit, construction, manifest and QA requirements are unchanged.
+
+## Optional Stroked-Toon Preset
+
+### 1. Chosen through the gate; preserve the default
+
+Use **stroked toon / illustrated miniature** (`stroked-toon`) only as resolved by
+`Render Preset Gate`; retain its recorded answer during repairs. The gate owns
+consent/default/recording rules—do not ask a second style question here. This
+preset changes presentation, not the subject or choreography; never import
+coffee props or workshop colours into an unrelated scene. Record paper/frame
+and camera choices alongside the preset in `DESIGN.md`.
+
+**Precedence when approved:** the recipe below replaces the pixel-only camera,
+white/no-plinth, palette-snap, edge-shader, Bayer, empty-paper and buffer rules
+where they conflict. Do not combine both post pipelines by default. A thin
+bevelled slab edge and a restrained optional figure frame/title/hint/readout are
+allowed. Locked animation framing, deterministic time, clipping/containment,
+contacts, silhouette readability, detail and animation QA still apply. Orbit is mandatory for all presets; it needs no separate approval. Character
+proportions remain subject-appropriate; don't force toy people into every scene.
+
+### 2. Render solid illustrated parts, not a pixel filter
+
+Copy `templates/stroked-toon.js` into the project. It exports an opt-in Three.js
+helper; it has no dependency on Anatomy CSS, SVG, fonts or the coffee rig.
+
+- **Native crisp rendering:** antialias on; device pixel ratio capped at 2;
+ sRGB output, `NoToneMapping`. Disable PixelPost, palette quantisation, dither,
+ Sobel ink and CSS `image-rendering: pixelated`. Keep a small authored colour
+ family, not a requirement that every final shaded pixel equal a palette entry.
+- **Four-step surface shading:** `MeshToonMaterial` with a 4×1 RedFormat ramp,
+ bytes `[68, 122, 184, 246]`, nearest filters, no mipmaps. These are starting
+ values, not physical light calibration. Give materials distinct local colours:
+ warm/cool off-white, desaturated object hues, dark structure, metal or timber,
+ one restrained accent. Adapt to the setting; warm cream is optional.
+- **Selective fine contours:** Three.js `OutlineEffect`, warm charcoal rather
+ than pure black. Start thickness 0.0024–0.0038 (effect units, not world units
+ or pixels). At the final viewport, aim for a roughly 1–2 CSS-pixel hero contour
+ with finer subordinate edges; tune by screenshots at desktop and phone sizes.
+ Broad silhouettes can be heavier, tiny fasteners lighter. Do not add wireframe
+ or stroke every triangulation. Flat decals, liquid films, transparent glass,
+ steam, contact patches and inward cavity surfaces normally have no outline.
+- **Light for volume:** one warm upper-side key with shadows, a broad hemisphere
+ and weaker cool fill. The helper starts key 2.55, hemi 1.55, fill 0.72; measure
+ and tune for the scene, especially night/water. Tight shadow bounds, 2048 map,
+ PCFSoft shadows, low bias, no acne. Combine cast shadows with small radial-alpha
+ contact patches only where needed; no overlapping dark discs or false rings.
+- **Model the edge:** modest bevels on casing, slab, rails and props; profile
+ lathes for vessels; cylinders with enough segments to read round. Avoid a
+ melted soft-plastic scene or polygonal mugs. Separate outer silhouette from
+ cavity shading: real wall thickness and a bottom, one-sided inward surface,
+ no expanded backface stroke through the interior. Glass must reveal contents;
+ liquid stays inside the wall through the whole fill range. Paper/grain and
+ lighting gradients are allowed; they must not obscure part boundaries.
+- **Compose and inspect:** a long-lens three-quarter view (start fov 26,
+ azimuth 38°, elevation 27.5°), fit to full animated bounds, room for the tallest
+ object and controls. These are a starting point, not a mandatory angle for all
+ subjects. Free user orbit is mandatory in every preset: use OrbitControls,
+ bounded zoom/polar angles, reset view and no pan; detail all exposed sides. No auto-spin.
+ Keep explicitly requested UI outside the subject, subtle, readable and keyboard-accessible. Narrative builds have no title/readout/card/teaching overlays by default; only discreet necessary controls. A title, hint or live state is opt-in figure furniture, not a requirement of toon rendering and not an excuse to import educational or Anatomy CSS.
+
+Minimal integration after user confirmation:
+
+```js
+import * as THREE from 'three';
+import { createStrokedToon } from './core/stroked-toon.js';
+
+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
+const look = createStrokedToon(renderer);
+renderer.setSize(width, height, false);
+const shell = look.toon(0xc4cbb4);
+const inner = look.toon(0xb8bfaa, { outline: false });
+// Add subject-specific lighting and objects; do not also call PixelPost.render.
+look.render(scene, camera);
+// On resize: renderer.setSize(width, height, false); update camera projection.
+```
+
+### 3. Match the craft and detail, not just the shader
+
+Use the Detail Bar's silhouette → construction → story passes, plus this close-up
+acceptance bar. Detail is structural, not a quota of randomly scattered meshes.
+Visual calibration references are `media/stroked-toon-reference.jpg` (overall
+framing/material hierarchy) and `media/stroked-toon-service-reference.jpg`
+(assembly detail). Read them when reproducing this look, but translate their
+craft to the requested subject rather than copying their props or palette.
+The coffee-rig repair is the evidence: a floating lever needed a pedestal;
+interior parts needed supports and connected runs; a ring under the scale read
+as a detached base; outlined cavities and oversized liquid surfaces looked broken.
+
+| Pass | Any-scene requirement | Translate to the subject |
+| --- | --- | --- |
+| Structure | Primary mass, supporting assembly, secondary panels/members | trunk/roots/branches; hull/ribs/deck; torso/joints/gear; wall/roof/trim |
+| Attachments | Every small part has a visible or explainable seat, joint or support | leaf stem, rope knot, hinge pin, bracket, cuff, axle, strap, fastener |
+| Functional detail | Inputs, outputs and working parts connect; contents fit containers | rooted irrigation, connected hoses, docked lines, harness to buckle, wheels to hubs |
+| Surface hierarchy | Large readable forms, medium assemblies, sparse microdetails | seams, fittings, latches, bark scars, stitches, labels, scales; not uniform noise |
+| Nearby life | 3–6 supporting props in purposeful clusters when space/brief permits | campsite kit; cargo/lifebuoys; books/blanket; tools/materials; tracks/nests |
+| Story | At least one specific used/changed detail per hero | wear at contact, repair, folded cloth, spilled contents, missing tile, footprint |
+
+Start with 8–15 meaningful pieces for a small supporting prop and 30–60 for a
+hero; a complex cutaway may need 100–250+ small pieces across its subsystems.
+These are planning ranges, not mesh-count acceptance tests. Reuse geometry and
+materials, merge static siblings only after visibility/animation ownership is
+settled, measure draw calls/fps and reduce invisible detail before construction.
+Preserve clear working paths and negative space. "Feels empty" calls for a few
+related clusters at varied heights, not filling every inch of deck.
+
+**Proof before delivery:** one whole-scene desktop and phone frame; a 1:1 hero
+crop; a cavity/contact crop if relevant; an action strip at known times. Always inspect front, service/back and high angles. Check outline
+width and tiny-part legibility; no floating supports, disconnected endpoints,
+false residue hoops, filled-in hollows, liquid clipping, or outlines on vapour.
+Scan finite vertices, contacts/clearances and moving bounds; check the actual
+readout against the frozen time. Keep `freeze(t)` and reduced-motion support.
+Do not call a symbolic cutaway a verified engineering design. Use the existing
+QA harness for shared checks, but disable or replace its pixel-palette/dither,
+empty-white-paper and fixed-angle assertions for this preset explicitly; do not
+silence unrelated failures. Record the preset and which checks apply.
+
## The Look Contract
-Ten rules. Break one and it stops reading as a diorama.
+The ten rules below define the **default pixel preset**, not the optional
+stroked-toon preset. Approved stroked-toon builds use the explicit overrides
+above; the remaining scene/animation requirements still hold.
-1. **Locked angle.** One three-quarter view, no drift, no orbit. Azimuth 45,
- elevation 33, fov 20.5, target just under the slab centre. When the user says
- "this angle", it means this one, for the whole loop.
+1. **Resettable hero angle + free orbit.** Start azimuth 45, elevation 33, fov
+ 20.5, target just under slab centre. User orbit is enabled in EVERY preset.
+ No auto-spin or timeline camera drift. Reset to this pose before frozen QA.
2. **Flat cut-out.** A slab with no plinth, no soil sides, background null, page
white. Everything below the deck plane hides in the overhang at 33 degrees.
3. **Palette snap.** Every pixel resolves to one entry of a fixed palette. No
@@ -489,7 +1032,7 @@ Ten rules. Break one and it stops reading as a diorama.
boundary. Nothing ever floats on the white page outside the block.
9. **Everything is a pure function of `t`.** No integration that carries state
between frames, no `Math.random`, no drift across the loop.
-10. **Empty paper.** The white page carries no DOM title, caption, HUD or
+10. **Empty paper (narrative profile only; educational dock and universal orbit controls are exceptions).** The white page carries no DOM title, caption, HUD or
instructions. Put copy on a modelled sign/screen or in the browser title; a
label floating on the paper breaks the cut-out.
@@ -508,6 +1051,62 @@ diorama is **three passes**, and every hero object has to survive all three.
shell. If the detail could be removed without changing the read, it is
greeble, not story.
+### Whole-object completeness gates (3.17)
+
+Apply these three gates to every hero object in every profile and render preset,
+including educational cutaways. They extend the existing Detail Bar and component
+manifest; they do not add cast, story-prop or mesh-count quotas to educational scenes.
+Evidence is the user's report of a quartz watch missing its straps and back; no
+independent inspection or root-cause diagnosis of that model is claimed here.
+
+1. **Approve the whole-object silhouette, not only the teaching core.** Before
+ detail, record whether the commissioned subject is a complete object, a detached
+ mechanism or an explicit permanent section; default to the complete named object.
+ Reference the entire object and its proportions, not just its most interesting
+ subsystem. A complete wristwatch needs its case and both strap/bracelet sides,
+ not merely a dial or quartz movement. Simplify small surface detail before
+ deleting identity-defining masses. **Evidence:** the reported watch lacked
+ straps despite its watch subject. **Test:** compare grey whole-object front,
+ side and rear views against recorded references, then review desktop/phone
+ delivery frames with the entire silhouette uncropped. Temporarily hide an
+ essential silhouette assembly (for the watch, either strap side); the review
+ must reject it. A close crop of the core cannot pass this gate.
+
+2. **Construct exterior, rear and attachment chains as real assemblies.** An
+ educational explanation of internals does not waive the casing, rear closure,
+ mounting or wearable attachments. Inventory every orbit-exposed side and trace
+ attachments into their seats/joints. For a strapped watch this includes caseback,
+ lugs/spring-bar connections, both strap halves and the reference-appropriate
+ buckle/keeper or clasp; do not impose those exact fittings on a different design.
+ Keep required construction in the model when an explicit Inside mode reveals
+ internals; a label, dark disc or transparency is not a replacement for absent
+ geometry. Honour a commissioned permanent section and document its boundaries.
+ **Evidence:** the same report named the missing back as well as straps.
+ **Test:** review opaque front/rear/side/high orbit crops and attachment-seat
+ close-ups; inspect mesh/group mappings and actual contact/clearance at joints.
+ Exercise cold load → Inside on/off (if present) → Reset to check restoration.
+ Hide the rear closure or disconnect an attachment in a test copy; the matching
+ presence/connection check and visual review must reject it. Existing motion and
+ non-penetration tests still apply; presence alone does not prove sound mechanics.
+
+3. **Close an explicit completeness matrix before claiming completion.** Fill
+ the matching DESIGN sheet before modelling and reconcile it against the built
+ scene before delivery. Give each expected silhouette, exterior/rear, attachment
+ and functional/internal assembly a stable ID, reference or stated assumption,
+ required/simplified/omitted status with scope rationale, mesh/group mapping,
+ connection and proof view plus actual test result. An omission note alone cannot
+ waive an essential part of the commissioned whole object; build it or obtain an
+ explicit scope change. **Evidence:** the reported missing straps/back show why
+ subsystem detail cannot stand in for whole-object coverage. **Test:** reconcile
+ every expected row with nonempty live geometry and reviewed proof; check that
+ the inventory itself covers the whole reference, not just existing meshes.
+ Deliberately remove a required row's mesh, leave its proof blank, and add an
+ unexplained omission in test copies; each must fail the audit. Store commands,
+ results and proof paths in `qa/report.json`. Missing evidence is UNVERIFIED,
+ a missing required assembly is FAIL, and either blocks a completeness pass.
+ This matrix makes omissions reviewable; it is not automatic certification or
+ a guarantee that future agents will comply.
+
The numbers below are **reference density** from The Hollow Toll, a 21 x 14 m
slab with four towers, two gate guns, five species, 42 units, one boss, 527
events and 183 shots. Treat them as a calibration target, not a cap.
@@ -541,9 +1140,10 @@ will read as a rock, a blob or a placeholder at 30 to 45 px.
turns into noise after the palette snap; fewer turns into a silhouette cut-out.
Use value contrast for construction and hue for story.
-**Detail lives on the camera-facing surfaces.** At the locked angle, model the
-front and the top; simplify the back. A perfect back is wasted geometry. Do not
-add detail under about 1.5 screen pixels: it aliases into speckle, not craft.
+**Detail lives on every orbit-exposed surface.** All presets need coherent backs,
+construction, attachments and cavities; a fixed hero shot is not permission to
+omit parts. Hidden internals may be simplified only if outside the mechanism manifest. Do not add detail
+under about 1.5 screen pixels at the delivery view: it aliases into speckle, not craft.
**Every prop must touch the ground.** Feet, wheels, a base, a contact shadow, a
stain. A prop hovering by two centimetres is the single most common "it looks
@@ -615,8 +1215,9 @@ geometry.
The table mixes two different kinds of number, and treating them alike is how a
new subject comes out wrong.
-**Invariants.** Come from the look itself and hold on every subject: azimuth 45,
-elevation 33, fov 20.5; one locked camera for the whole loop; palette discipline
+**Pixel-preset invariants.** The camera/palette/post values here belong to the
+pixel look, not approved stroked-toon builds. They hold on every pixel subject: azimuth 45,
+elevation 33, fov 20.5; one deterministic reset hero pose for QA plus user orbit; palette discipline
(every material samples a palette entry, the shader array length equals the
palette length); gated dither, ink at 0.13/0.34 mixed 0.62, the palette tie-break;
the rig's proportions and joint signs; 2048 shadow map with a frustum tight to
@@ -637,7 +1238,12 @@ reader trusts it.
## Pipeline
-Each step ends in something you can look at.
+Each step ends in something you can look at. Settle the render preset through the
+`Render Preset Gate` before step 1 — one question at project start, not a mid-build
+decision. In a confirmed `stroked-toon` or `pixel-stroke` build, steps 1–4 use the
+authored colour family, fitted long-lens camera, toon lighting and
+`templates/stroked-toon.js` recipe instead of pixel snap/dither/Sobel post. Steps
+5–10 still apply; use preset-aware QA.
1. **Palette first.** The palette array in `palette.js` plus a named `C` map.
Every material samples a palette hex, nothing else. Done when a grep for
@@ -653,8 +1259,11 @@ Each step ends in something you can look at.
4. **Post pass.** `templates/post.js`: gamma, grade, ink, gated dither, palette
snap, rim dither. Done when a 1:1 crop shows square pixels and a dark contour,
and flat pavement shows no speckle.
-5. **Props.** Flat-colour boxes and lathes, no textures, coarse detail. Done when
- the 1:1 crop reads the object's silhouette without colour.
+5. **Props.** Start with flat-colour boxes and lathes, coarse detail and no
+ textures hiding weak geometry. This is the initial silhouette pass, not the
+ finished detail target. Done when the 1:1 crop reads the object without colour;
+ step 7 adds construction and story. Approved toon may then add restrained
+ decals or grain as described in its recipe.
6. **Cast.** `templates/peopleModel.js` (base) or `templates/peopleModel-street.js`
(clothed) rig, one entry per figure with a base pose. Done when isolated portraits show no gaps, no floating parts, knees
bending the right way.
@@ -719,7 +1328,7 @@ Rules that keep a new subject from becoming a blockout:
output, first consequence, goal/handoff contact, final residue. A social diorama
may use establish, ritual, disruption, handoff, residue. Every object earns its
place by serving one of those five.
-- **Stage for the locked camera.** Put the threshold and the hero action on the
+- **Stage for the hero camera.** Put the threshold and the hero action on the
+Z face; put tall landmarks at the back but offset in screen x so they do not
stack. Put one foreground prop at the near corner for depth and one mid-ground
prop to lead the eye.
@@ -1941,7 +2550,7 @@ Staging rules that came out of real reports:
- **One window per actor, staggered 0.2 s or more.** A shared window climbs two
men into a seat on the same frame, which reads as choreography, and at 0.1 s
they climb through each other.
-- **Separate a pair in screen space, not in world space.** At a locked 45/33
+- **Separate a pair in screen space, not in world space.** At the reset hero 45/33
view, moving a figure further out along the camera axis barely changes where it
lands on screen: it stays stacked over the car's flank and still reads as one
blob, which is why pushing the stand spot from 1.6 m to 2.0 m did not cure a
@@ -2019,7 +2628,7 @@ near one.
frozen splash shows whatever the last played frame left behind. Both templates
expose `reset()`; the harness calls it and re-simulates in fixed steps from
zero, which took a two-frame diff from 334 differing pixels to 18.
-- **Smoke**: camera-derived billboards. The camera is locked, so copy its
+- **Smoke**: camera-derived billboards. The camera can orbit, so update from its current
quaternion once and every puff is a plane facing the lens.
- **Debris with history**: loose notes or paper use a solved arc, a drag term, a
spin about a random-but-deterministic axis, then slerp to flat and lie there for
@@ -2078,7 +2687,7 @@ punishes sub-pixel tricks:
## Combat Readability (towers, bosses, deaths)
A diorama is judged on whether the **cause and the consequence are both
-visible at the locked camera**. Geometry that is correct in world space can
+visible at the reset hero camera**. Geometry that is correct in world space can
still read as a bug on screen. Run these gates before calling a combat beat
finished.
@@ -2312,6 +2921,160 @@ system, on every subject.
scan. `templates/qa/audit.mjs` runs the mechanical ones; the 1:1 crops remain
human evidence.
+## Motion Graphics Primitives (arrows, flames, flow)
+
+Animated arrows and flames are how a mechanism explains cause. They fail
+silently: the build passes, one still looks plausible, and the graphic points
+backwards or sits inside a solid. Treat every primitive as a tiny part with its
+own convention test, in every preset.
+
+- **Declare and test the local forward axis.** A cone built with
+ `CylinderGeometry(radiusTop, radiusBottom, ...)` points along the *top* end.
+ Swapping those two numbers makes every arrow flow backwards while still
+ looking like an arrow. Build the tip at local `+Z`, store `tipLocal` and
+ `tailLocal` in `userData`, and assert: cone base wide and behind, tip a point
+ ahead, and the placement transform maps `+Z` onto the requested tangent.
+- **Never place an arrow on the centreline of an opaque body.** An arrow inside
+ a cast runner is invisible with honest depth testing; the usual "fix" is
+ `depthTest:false`, which turns the scene into x-ray. Two honest options only:
+ cut a real window/section that exposes the gas volume, or place arrows solely
+ in the genuinely open region (port mouth, chamber, outlet). Keep depth test and
+ depth write on; assert `depthTest === true` for effect materials.
+- **A spline through an open cutaway is not a flow route.** An intake path that
+ looked correct in the port still speared the valve disc, because the gas turns
+ around the open valve, not through it. Derive each effect from the *current
+ free volume* (crown to the live valve underside) instead of a fixed centreline,
+ and use one bold arrow per stroke rather than a stream spawned along a curve.
+- **Fit the whole cone, not its centre.** The vertical extent of a
+ cylinder-capped cone depends on its direction: `|dy|·half + flat·head`. For a
+ vertical arrow that is its half length, so clamping only the centre lets the
+ head pierce the crown or the valve. Compute the extent, reduce the scale until
+ the band and the bore both fit, then clamp the centre. Judge "bold" by rendered
+ length (`length × scale`), not by the scale ratio: a long authored arrow in a
+ short band is legitimately scaled down and still reads.
+- **Anchor to a real surface, and normalize the authored length.** Put the intake
+ tail and the exhaust tip `0.008` under the valve head underside
+ (`seat − 0.061 − lift`), span at most `92%` of the band, give a compression
+ chevron its tail on the rising crown (`crown + 0.02`) so it touches the charge
+ it describes, and start a force arrow `0.015` *inside* the flame tip. Author the arrow at its maximum length so `scale ≤ 1`; otherwise a
+ non-normalized `1.14` arrow makes the minimum-scale gate and every sizing test
+ meaningless.
+- **Never stack two rows of the same arrow.** Two overlapping compression rows
+ read as double-headed spikes. Two side-by-side chevrons, or one arrow, not two
+ rows at the same x/z.
+- **Couple the effect to its source.** A pressure arrow that outlives the flame
+ becomes an orphan arrow pointing at nothing. Fade the arrow with the flame
+ kernel and hide both on the same frame.
+- **Every Y constant shares one space.** A group lifted off the plate (here
+ `+0.024`) silently shifts every "absolute" ceiling. Measure the *scene* in the
+ same local space the constants were written in; mixing world and local turned a
+ correct flame into a phantom 24 mm head violation.
+- **A flash must not saturate the frame.** Halo opacity `0.40`, halo scale `0.42`
+ and point-light intensity `2.2` are already generous at diorama scale; the
+ earlier `0.95 / 1.14 / 9.0` blew the whole head to white, and `0.55 / 0.62`
+ still washed the crown orange for two frames. Judge the ignition frame itself,
+ not the frame after it.
+- **A flame may not die as a bead.** The kernel must span the fixed clearance
+ recess at TDC (`0.125` here) and be hidden below `0.12` height. A flame that
+ fades to a two-pixel dot on the valve seat is the flame equivalent of an arrow
+ speck, and a mid-stroke still will not show it.
+- **Audit every 15°, not four hero stills.** Render the full 720° at a tight
+ chamber camera, build one contact sheet per stroke, and read every cell. The
+ spear-through-valve, the double-headed chevrons and the ignition white-out were
+ all invisible in the four "representative" screenshots.
+- **Bound the change between adjacent degrees.** A per-degree delta test on
+ position and scale catches pops that a mid-stroke still hides. Scale a fade so
+ it cannot drop by more than about `0.06` per degree, and hide only when the
+ final scaled size is below the legible threshold.
+- **No effect speck.** A primitive that fades by scale must become invisible
+ before it becomes a 2 px nub. Drive `visible` from the *final scaled size*, not
+ from the envelope alone, and hide below a legible threshold (about 0.3 of the
+ authored arrow length at a normal educational-camera distance; 0.22 is only for
+ very large arrows). Test the fade boundary as well as mid-stroke; a nub reads
+ as a rendering bug.
+- **Size against the real free volume, and check the sign.** Measure the moving
+ ceiling (valve faces, piston crown, lid) each frame, not the closed deck or a
+ cached constant. An inverted subtraction (`floor - tip` instead of
+ `tip - floor`) silently hides every arrow while all numbers stay finite. Assert
+ the available band is positive wherever a primitive is visible, and fit the
+ full tip/tail/width inside it.
+- **A flame is a kernel, not a balloon.** Anchor it at the igniter/plug and let it
+ grow only into the volume the mover releases, except that the kernel always
+ spans the fixed clearance recess at TDC where the released gap is almost zero.
+ A chamber-sized flame hides the pressure graphic, touches the piston and reads
+ as a balloon. Keep it compact, put the force arrow in the free band *below* the
+ flame, and prove the flame bounds against the crown and the head across the
+ whole event.
+- **One idea per primitive.** Three short arrows sharing an origin merge into an
+ unreadable trident; one bold arrow reads instantly. If a fan is genuinely
+ needed, separate tails and heads by at least one head-width and verify it in a
+ 1:1 crop.
+- **No ink outline on tiny FX.** An outline sized for castings swallows a thin
+ shaft and turns coloured arrows into black sticks. Effect materials stay flat
+ and un-outlined; check `outlineParameters.visible === false` and the rendered
+ colour in a crop.
+- **Lifetime is phase-bound and deterministic.** Each group has an explicit
+ window and no history dependence: visible mid-stroke, zero in every other
+ stroke, identical for the same phase in any order. Test mid-stroke counts and
+ a sweep of outside phases.
+- **A hollow outlet is one connected solid.** No floating torus as a rim and no
+ flat cap closing the bore. Lathe one continuous sleeve + rolled lip, overlap
+ the pipe, and prove with a centre-ray (passes through the opening) and an
+ annulus-ray (hits material).
+- **Every crossed fixed wall needs a real opening.** A piston, rod or shaft that
+ passes a flange needs a bored hole/slot with measured swept clearance, not a
+ shelf with a dark circle painted on it. Test the actual structural mesh against
+ every moving surface vertex at the crossing plane, at the lowest/full-travel
+ pose.
+- **Selection:** follow `Canonical educational UI and inspection contract`;
+ an explicit Inspect focus is distinct from a camera-stationary lesson step.
+- **Use the copy-in helper, not a fresh guess:** `templates/flow-primitives.js`
+ carries the +Z convention, the band fitter and the legibility gate.
+- **Regression checks for this section:** forward-axis unit test, tangent
+ alignment, per-stroke visible counts plus zero leakage, minimum legible scale,
+ a 720° vertex sweep against crown/bore/head/valve-disc/stem/plug with the live
+ lift, an adjacent-degree no-teleport bound, flame-kernel and crown bounds,
+ open-outlet and flange rays, a 48-frame contact sheet per stroke, and a
+ screenshot strip of all four strokes from two orbit angles. A missing check is
+ not a pass.
+
+### Recorded failure modes (four-stroke engine, v3.12.0)
+
+These were all present in one finished-looking scene; check for each by name:
+
+1. Reversed cone (`radiusTop`/`radiusBottom`) — arrows flowed backwards.
+2. Arrows on the centreline of solid intake/exhaust runners — invisible, then
+ faked with `depthTest:false`.
+3. Fade boundary left coloured specks (scale 0.016) visible.
+4. Arrow ceiling taken from the deck instead of the valve faces, and inverted
+ downward-room sign — pressure arrows vanished entirely.
+5. Chamber-sized ignition flame hid the pressure arrows and touched the crown.
+6. Three short pressure arrows merged into one trident.
+7. Ink outlines turned small flow arrows into black sticks.
+8. Detached torus "rim" floating off the exhaust pipe; solid cap in the bore.
+9. Solid cylinder-base flange slicing the piston and rod at the bottom of the
+ stroke — the exact "it passes through" report.
+10. Part selection changed colour but did not dim the rest or move the camera.
+11. Intake/exhaust arrows followed a spline through the valve disc — a visible
+ spear through the head. Fix: free-volume arrows, never a port centreline.
+12. Only the arrow *centre* was clamped, so heads poked through the crown and the
+ valve underside. Fix: fit the direction-dependent full extent.
+13. Two stacked compression rows overlapped into double-headed spikes. Fix: one
+ chevron per side.
+14. Arrow scales ran past `1.14` because the authored length was shorter than
+ the desired length, defeating the legibility gate. Fix: normalize length.
+15. The pressure arrow outlived the flame and pointed at nothing. Fix: shared
+ fade with the flame kernel.
+16. World-space tests applied to engine-local constants reported a phantom
+ flame-above-head violation (`+0.024` root lift). Fix: one declared space.
+17. Ignition flash at `opacity 0.95`, `scale 1.14`, `intensity 9.0` blew the
+ whole head to white for the ignition frame. Fix: capped flash.
+18. The flame faded to a two-pixel bead on the valve seat for 20° of crank
+ rotation. Fix: span the clearance recess and hide below a legible height.
+19. Four hero stills missed all of the above; the 15°-step contact sheet and a
+ 6°-step video found them. Fix: the frame-by-frame audit is the acceptance
+ gate.
+
## Verification
- **Build first, then shoot, then prove the edit landed.** A failed bundle leaves
@@ -2319,6 +3082,21 @@ system, on every subject.
untouched, so in both cases every screenshot shows the old app and the fix
looks like it did not land. Read the build's own output line, grep for a
sentinel string from the change, and only then judge the frame.
+- **Non-vacuous, fresh proof (3.18 evidence + test).** Quartz-watch's rounded
+ box reported runtime `type: BoxGeometry`; a type-name filter produced zero
+ magnet samples and `magnetRadius: 0`, falsely passing clearance. Assert expected
+ object counts, nonempty finite sample sets, positive applicable radii and actual
+ geometry attributes/topology before measuring; never trust a constructor label
+ as shape proof. `templates/mechanism-contract.mjs` assertCoverage and
+ `templates/qa/mechanism-contract.test.mjs` cover helper failure detection;
+ scene probes must additionally inject an empty/type-mismatched sample set,
+ zero radius and a known actual-geometry overlap and reject each. Record fresh
+ source/build hash, successful build command, loaded artifact identity, probe
+ method, counts, tolerances, worst pair/phase and evidence paths in the report.
+ Failures or missing browser/visual/sweep coverage remain FAIL/UNVERIFIED.
+ Never infer full mechanical certification from scalar budgets, 26 numerical
+ highlight states, screenshots alone or a stale successful report. Evidence:
+ historical `quartz-watch/qa/construction-report.json`; no workspace dependency.
- **Judge orientation from the transform, not the pixels.** At diorama scale a
back and a front read the same: a 4x-downscaled strip once made a
correctly-facing figure look like he was climbing in backwards, and the
@@ -2328,7 +3106,7 @@ system, on every subject.
- Screenshot 1280x800, 1388x950 (iPad landscape) and 390x844 (phone). Zero page
errors in all three, and the framing holds at each aspect.
- Two shots 1.5 s apart differ (the loop is alive) and the camera position is
- identical (the angle is locked).
+ identical after resetting the hero pose.
- A 1:1 crop shows square pixels, a dark contour, no speckle on flat deck.
- **Pairwise distance sweep** across every multi-actor beat: freeze in 0.3 s
steps, log x/z and the pairs under 0.6 m. Held for two samples means jammed.
@@ -2347,7 +3125,7 @@ system, on every subject.
base and seat. No boot passes through the bars/seat/body, both soles reach the
boards, and the rider root follows the seat after departure.
- **Scale check.** The 30%-smaller request is a camera move; assert
- `actualDistance / fitDistance ≈ subjectScale`, the projected slab width fell
+ `actualDistance / fitDistance ≈ 1 / subjectScale`, the projected slab width fell
by the same factor, `post.size ≈ CSS size × renderScale` (capped), the
slab/world clip/shadow camera and CSS frame are unchanged, and the standalone
still frames on the page.
@@ -2549,9 +3327,14 @@ src/
main.js renderer, scene, clip planes, resize, rAF, ?t= freeze
core/
palette.js N entries + named C map
- post.js PixelPost: gamma, grade, ink, dither, snap, rim
+ post.js PixelPost: gamma, grade, ink, dither, snap, rim (pixel only)
+ stroked-toon.js optional approved OutlineEffect + four-step toon materials
materials.js every material, palette-validated
geometry.js roundedBox, addBox, lathe helpers
+ mechanism-contract.mjs shared anchors, coverage/end-plane budgets + scoped contact policy
+ inspection.js rigid assembly/piece emphasis, reveal authorization, exact restoration
+ ui/
+ education-dock.mjs education-dock.css dependency-free single lesson surface
merge.js mergeSiblingMeshes: one draw per material per group
scene/
camera.js lighting.js street.js bank.js props.js
@@ -2564,6 +3347,8 @@ src/
build.mjs esbuild bundle, index.html, standalone HTML
qa/
shoot.mjs viewports + console errors + named timestamps
+ inspection.test.mjs helper state/identity/ownership and injected failure regressions
+ inspection-browser.mjs synthetic contrast/depth/restoration fixture, three presets
probe-*.mjs one-off numeric probes (facing, anchors, NaN, spawn pose)
audit.mjs scene lint: halos, fades, camera/render scale, exits, FX
portrait.mjs isolated figure/framing shots through a debug camera
@@ -2640,8 +3425,7 @@ looks like.
## Skill Maintenance
-The skill is part of the deliverable. After every shipped diorama, do a ten-minute
-postmortem and write down what the user actually reported, not what you intended.
+Keep a project-local postmortem of what the user actually reported, not what you intended. Installed-skill changes require an explicit maintenance request and filesystem approval; the following rules apply only during authorized maintenance.
1. **Add at most three rules per routine project.** A skill that grows by fifty
small rules becomes unreadable and the next reader skips it; a deliberate
@@ -2797,6 +3581,87 @@ vertical arc so the feet leave the ground.
## Changelog
+- **5.7.0 — Remove Pixel Art V2.** Removes the V2 rendering contract and intake/design options at the user’s request. Classic Pixel Art is the recommended and explicitly delegated default; stroked-toon and pixel+stroke remain. V2 resources are archived, not active instructions. Regression: active intake/design expose exactly three presets, with no V2 dependency. Earlier changelog entries are historical only.
+
+- **5.6.0 — V2 cast and action language.** Adds dedicated rounded-character construction, cast-specific shading and articulated action guidance. Requires garment-attached patterns, actual foot/grip contacts and deterministic action-strip checks for imported or authored cast; existing rigs are starting points, not automatic style passes.
+
+- **5.5.0 — Terrain edge, not just ink.** Makes the irregular scattered-to-white ground perimeter a required V2 feature. Adds an independently authored terrain-only material coverage helper with shadow hooks, integration and edge-crop acceptance notes. Existing projects are not automatically modified; renderer verification remains per build.
+
+- **5.4.2 — Standalone Pixel Art V2.** Removes external reference materials and adapted styles. Retains an independently specified edged/dithered rendering option and the two-step look/sourcing intake. No external implementation is bundled.
+
+
+- **5.4.0 — Two-step commission intake.** Adds selectable Pixel Art V2 versus Classic Pixel, then separate hybrid / internet-throughout / fully agent-modeled sourcing choices. Explicit precedence replaces old automatic internet-first and three-option prompts. V2 requires its own renderer and rendered checks; the classic post template is not falsely advertised as V2. Updates design receipt and sourcing evidence. v5.3.0 preserved.
+
+
+- **5.2.0 — Pose-aware clearance.** Adds actor/animal/building space reservation, seat frames/occupancy and action-path checks to both profiles. Ships sphere/capsule/OBB nearby-pair sampled audits with exact time-window contact rules and independent proxy inventory, plus live CPU skin/morph pose bounds. Regressions cover limbs/tails, seats/backrests, buildings, temporal crossings and missing/invalid coverage. Proxy/sample limits remain explicit; full guide, model-first sourcing and narrative no-education-UI preserved.
+
+- **5.1.0 — Model-first by default.** Requires finding, acquiring and using fitting commercially modifiable/redistributable internet assets for major roles, not merely logging a search. Retains Polyfork-first narrative sourcing and educational accuracy gates; verifies actual import/style/motion and final-scene inclusion. Free-first; paid assets require approval. Hand-building is a justified gap/fallback, not the default. Preserves the full long guide and narrative no-education-UI boundary.
+
+- **5.0.0 — Long-form restoration.** Restores the complete 3.18 guide and detailed design sheet after compact-profile educational UI leaked into ordinary scenes. Narrative by default; no educational card/dock/lessons/callouts without explicit explanatory intent. Keeps Polyfork sourcing, commercial/adaptation/redistribution checks, actual-subject representation and tested construction helpers. Profile-consumer tests are bounded evidence, not a rendered amusement-park benchmark.
+
+- **3.18.0** — Consolidates educational UI/selection/lesson rules into one V8-exact
+ authority with crossrefs; resolves placement, focus, preset-intro, ghost-shell
+ and reciprocal scale contradictions. Three quartz-watch evidence/test contracts:
+ all repeated mating interfaces from shared anchors/axes with real holes and
+ noncoplanar ends; assembly/piece inspection with class-safe reversible state;
+ non-vacuous actual-geometry QA and fresh build identity. Ships rigid inspection
+ and shared-interface helpers with class/ownership/empty-fixture failures and a
+ three-preset rendered contrast/depth/restoration regression; preserves context
+ and authorizes internal occluder removal explicitly. These tests are bounded
+ helper evidence, not full mechanism/UI certification.
+ Missing straps/back remain the existing 3.17 completeness gates, not new rules.
+ Full 3.17.0 preserved as `SKILL.md.bak-v3.17.0`.
+
+- **3.17.0** — Three whole-object completeness gates prompted by the user-reported quartz watch missing straps and back: whole silhouette/scope, exterior/rear attachment construction, and a reconciled completeness matrix with proof and negative checks. Extends the Detail Bar and design template across profiles/presets; preserves prior UI, mechanics and style contracts. Per-scene checks remain required; no model certification is claimed.
+
+- **3.16.0** — Code-defined V8 educational UI contract and copy-in `education-v8.css`: exact neutral tokens, reserved 360px right column/mobile dock, DOM/control hierarchy and measured regression gates. Records grandfather-clock beige/glass/detached-title drift; supersedes ambiguous default-placement wording without changing render presets or mechanics.
+
+- **3.15.0** — LEAP-1B repair checklist: retained preset provenance, closed exterior/explicit Inside/reset lifecycle, UI-safe complete-assembly fit with correct camera-axis sign, and reference-first white compact educational UI. Adds design fields and scoped white-stage CSS. Tests remain per-scene; geometry sampling does not imply full collision certification. v3.14.1 preserved as backup.
+
+- **3.14.1** — Documents the calibrated V8 soft-glow/holographic inspection implementation: isolated material variants, ghost-shell depth policy, selective live-transform feature edges, multi-material restoration, ownership/disposal, and rigid-versus-deformed limitations. Adds matching design/QA acceptance fields; no renderer preset or scene behaviour changed. v3.14.0 preserved as `SKILL.md.bak-v3.14.0`.
+
+- **3.14.0** — Three evidence-backed regression rules: mating interfaces/local axes/shared anchors with bore/bevel/axial budgets and connected ports/supports; full-assembly swept-clearance coverage with surface-scoped intended-contact policy and explicit sampled-proof limits; compact neutral sans educational UI with progressive causal steps bound to frozen scene state. Adds dependency-free mechanism-contract and education-dock templates, scalar/contact-policy and browser helper regressions, design/QA sheets. V8 rod repair and the incomplete earlier 12/12 report are the evidence, not a guarantee of future bug-free construction. v3.13.0 preserved as `SKILL.md.bak-v3.13.0`.
+
+- **3.13.0** — Mandatory `Render Preset Gate`: the agent asks once, at project
+ start, which of the three looks to build in (pixel default, stroked-toon,
+ pixel + stroke hybrid), instead of asking only once it had already decided to
+ try the optional look. An explicit style in the request counts as the answer;
+ naming a look in a reference, or the word "toon" on its own, does not; silence
+ resolves to pixel and is recorded as a delegated default. The grey blockout and
+ the research lookups continue while the answer is pending and only the
+ presentation pass waits. Updates the frontmatter description, the intro,
+ `One Prompt, One Build`, `Step 0`, both preset sections, the pipeline and
+ `templates/DESIGN.md`. v3.12.0 preserved as `SKILL.md.bak-v3.12.0`.
+
+- **3.12.0** — Motion graphics hardened by a full-cycle, frame-by-frame audit of
+ the four-stroke engine: effects are derived from the moving free volume instead
+ of a spline that pierced the valve; the direction-dependent cone extent is
+ fitted rather than only the centre; anchors, length normalization, single-row
+ chevrons and flame-coupled fade are specified; ignition flash is capped; and
+ every Y constant is declared in one local space. Adds the 720° vertex
+ containment sweep, the adjacent-degree no-teleport bound and the 15°-step
+ contact-sheet gate, plus nine new recorded failure modes. v3.11.0 preserved as
+ backup.
+
+- **3.11.0** — Motion-graphics primitives recorded as first-class geometry:
+ forward-axis/tip convention tests, no arrows inside opaque bodies and no
+ depth-test x-ray, minimum legible effect scale, free-volume sizing with a
+ sign check, compact ignition kernels, one-idea arrows, un-outlined FX,
+ phase-bound deterministic lifetimes, connected hollow outlets, real bores
+ through crossed flanges, and reversible selection glow/dim/focus. Adds the
+ ten recorded failure modes from the four-stroke engine. v3.10.0 preserved as
+ backup.
+
+- **3.10.0** — Mandatory user orbit for every preset with deterministic hero reset, no auto-spin; first-class educational mechanism profile, single accessible dock and one live part explanation; component manifest and ratio/kinematic/contact acceptance; optional confirmed low-resolution pixel+stroke helper with one selective outline pipeline. v3.9.0 preserved exclusively as backup.
+
+- **3.9.0** — Optional subject-independent `stroked-toon` illustrated-miniature
+ preset, calibrated from the coffee-rig repairs: explicit ask-and-wait gate,
+ native antialiasing, four-step toon ramp, selective warm ink outlines, bevelled
+ assemblies, sound cavity/contact construction and related prop clusters.
+ Pixel remains the default. Documents overrides to conflicting pixel-only
+ camera/post/empty-paper rules, adds `templates/stroked-toon.js` and design-sheet
+ consent/preset fields. Checks: material/ramp tests, module bundle, unrelated-
+ subject spec review; renderer appearance still needs per-project visual QA.
- **3.8.0** — `qa/frames.mjs`: a per-entity frame recorder. Samples one dense
series per entity across a window, isolates it (branch, siblings or full
scene), fits one camera to its swept bounds so travel stays visible, and scores
diff --git a/archive/v5.6.0-pixel-v2/references/pixel-v2-people.md b/archive/v5.6.0-pixel-v2/references/pixel-v2-people.md
new file mode 100644
index 0000000..84b052e
--- /dev/null
+++ b/archive/v5.6.0-pixel-v2/references/pixel-v2-people.md
@@ -0,0 +1,59 @@
+# Pixel Art V2 people: construction and motion
+
+The cast belongs to the same visual language as the ground: small rounded figures, clear gestures, solid colour bands and deliberate silhouettes. This is a style contract, not permission to replace required anatomy with disconnected beads. Apply it to imported rigs or authored geometry according to the selected sourcing mode.
+
+## Code starting point
+
+Copy `templates/pixel-v2-person.js` into the project's scene code for authored cast. It exports `createV2Person(options)` with rounded garment/head/limb geometry, real joint pivots, hand grip and foot frames, a low-level `pose()` evaluator and deterministic idle/reach/walk-preview samples. No external model or branded dependency is required beyond Three.js. This is independently written code, not extracted third-party source.
+
+```js
+const actor = createV2Person({ shirt: 0xb14b3c, striped: true, height: 1.8 });
+scene.add(actor.root);
+actor.sample(sceneTime, { action: 'reach', phase: actionPhase });
+// Attach a held prop to actor.grips[0] with its correct grip transform.
+// Drive actor.pose(...) from the production foot-lock/contact controller.
+```
+
+`walk-preview` demonstrates alternating articulation only: it is NOT a complete foot-locked travelling gait. Production actions still need targets, support/IK, prop ownership and contact tests below. Imported-model modes retain their sourced rig and adapt it to the same style rather than replacing it silently with procedural people. Cast role metadata must be wired to the actual renderer. Numeric bounds and deterministic pose checks do not establish a rendered visual match.
+
+## Silhouette and proportions
+
+- Start with a roughly six-to-seven-head-tall adult silhouette, subtly enlarged head/hands/shoes and comfortably thick limbs. Avoid chibi heads, cube people and hyperreal skin detail unless requested.
+- Use a compact tapered shirt torso and pelvis, short neck, rounded skull with a small jaw/front plane, and a distinct hair cap offset toward the back/top. A subtle nose or facing plane should make the gaze readable at the logical render size. Do not add noisy facial pixels that disappear at the hero view.
+- Build articulated upper/lower arms and thighs/shins from smoothly tapered rounded segments, with real shoulder/elbow/wrist and hip/knee/ankle frames. Overlap joint volumes enough to avoid gaps during bends, without creating oversized ball joints. Hands are small mitten/palm shapes with a grip direction; shoes have heel, sole and a visible toe pointing along the foot.
+- Keep upper arms just outside the torso and legs sufficiently separated for a visible gap at the hero camera. Avoid merging both hands into a single ambiguous pixel clump. Test front, side and back as well as the hero view.
+- Coordinate palette by role: one clear garment hue, a contrasting lower garment, skin, hair and shoes. Add a second clothing colour or broad stripe only when it remains several logical pixels wide. Hair, collars, cuffs and hems are geometry/material boundaries, not random surface grain.
+
+## Rendering
+
+Mark the entire character subtree as cast and map that role to the actual shader/mask pipeline. `userData.pixelRole = 'cast'` is metadata only: verify the renderer really reads it. Use clean discrete light bands and object-owned dark silhouettes, without terrain grain or ordered dither on skin/clothing. Preserve warm light and cool shadows without flattening all skin tones to one palette entry. Clothing patterns remain attached to the garment when the person turns or bends; do not use world-height stripes that slide across moving limbs.
+
+The existing `peopleModel.js` and street variant are construction starting points, not automatic V2 certification. Adjust their proportions, detail frequency and material roles to this contract. Do not add a second full-resolution outline pass over the pixel grid.
+
+## Articulated action, not decorative bobbing
+
+Use a deterministic pose evaluator with separate root movement and joint motion. Derive pose from absolute scene time and semantic action state; freezing at a timestamp must reproduce the same body, props and contact shadows. Head/body yaw is computed in the actor parent's local space. Counter-rotate the hips and shoulders slightly rather than swinging the whole rigid figure.
+
+### Walk
+
+Use alternating stance and swing. During stance the planted foot stays fixed to its ground contact while the pelvis moves over it. During swing lift the toe, clear the ground, move forward, then lower heel/sole before transferring weight. Solve knees toward a consistent forward pole; opposing arm swing comes from shoulders with a small elbow bend. Add a modest pelvis rise/fall and torso twist subordinate to the foot contacts. Set cycle rate from distance travelled and stride length, not an unrelated sine wave; stop and settle when travel stops. A contact shadow follows the actual support, not a guessed root offset. Do not quantise body motion merely because plants step at a low frame rate.
+
+### Reach, hold and release
+
+Establish shoulder → elbow → wrist chains with an actual target/contact frame. Rotate pelvis/torso and shift weight before extending the arm. Crouch lowers the pelvis through hip/knee bend; leaning alone must not stretch the leg lengths. A carried object inherits a hand/grip frame exactly once. At a handoff/release, transfer ownership at the event frame with a continuous world transform; never duplicate the held object or teleport it between roots. Return the arm through a short recovery pose.
+
+### Crouch, sit and stand
+
+Move pelvis backward/down while knees and ankles flex and the feet remain supported. A seat action has approach, align, lower, supported hold, rise and departure. Do not lower a standing body through the chair. Respect the shared action-clearance/seat contracts, including moving-seat parentage, support gaps and live posed bounds.
+
+### Strong actions
+
+Throw, strike, pump, dive or lift each needs anticipation → weight shift → action/contact → follow-through → recovery. Use an explicit action phase and targets, not a perpetual generic arm swing. Extend or tuck the body through real joint chains; preserve limb lengths. Tool tips, held handles and impact points must agree at the decisive frame. Face the action, not perpetually the camera.
+
+### Idle and variation
+
+Use small occasional head turns, asymmetric resting arms and gentle supported weight shifts. No continual bouncing in place, treadmill walking, synchronised crowd phase or noisy per-frame randomness. Seed variations in height, clothing, stance and timing, while preserving the common proportions and detail density. Pause/reduced-motion should suppress decorative idle movement without breaking a requested interactive action.
+
+## Acceptance
+
+Capture a native-pixel portrait plus a full action strip at anticipation, mid-action, contact and recovery. Verify cast/scenery dither separation, stripe readability, no joint gaps, correct facing, foot sliding/ground penetration, hand/grip contact, loop seam and deterministic freeze. Use the existing production pose-aware clearance evaluator across the whole action. Include the worst side/back view; a pleasing hero frame alone does not pass. Imported clips require the same fitted contact and silhouette checks. Never claim the people are V2-styled solely because the ground or canvas is pixelated.
diff --git a/archive/v5.6.0-pixel-v2/references/pixel-v2.md b/archive/v5.6.0-pixel-v2/references/pixel-v2.md
new file mode 100644
index 0000000..0c16af1
--- /dev/null
+++ b/archive/v5.6.0-pixel-v2/references/pixel-v2.md
@@ -0,0 +1,62 @@
+# Pixel Art V2 implementation checklist
+
+This is an independent visual specification, not an adapter for an external engine or repository. Implement it in the project with the chosen rendering stack.
+
+## Presentation
+
+- Small, readable miniature on white with an orthographic three-quarter hero view.
+- Free orbit, deterministic reset and enough margin for cast shadows and action extremes.
+- A low-resolution logical render target enlarged once with nearest-neighbour filtering; avoid fractional device-pixel blocks where possible.
+- Choose logical dimensions based on essential detail and viewport, not supersampling. Document actual native and displayed dimensions.
+
+## Required ground-perimeter breakup
+
+Use `templates/pixel-v2-ground-edge.js` for a terrain-only, binary pixel coverage fade. It is not object ink outlining. Place a thin ground apron beyond the occupied area; its outer boundary becomes irregular and sparse before reaching white. A rectangular substrate visible underneath will defeat the effect, so do not leave a big straight slab under the apron. Retain requested structural platforms as separate objects.
+
+```js
+import { applyGroundEdge } from './core/pixel-v2-ground-edge.js';
+// ground uses local X/Z coordinates; halfSize matches its actual geometry.
+const edge = applyGroundEdge(ground, {
+ halfSize: [12, 8], band: 0.16, irregularity: 0.055, seed: 3,
+});
+// Keep all contact/support paths inside the fully covered region.
+// edge.dispose() restores the material and releases owned resources.
+```
+
+Copy the helper into the project and apply it to the actual production ground mesh, not a hidden demo. It clones the visible material and supplies matching coverage hooks for directional/spot and point shadow materials. It supports a plain, non-instanced mesh with one built-in Three.js material and standard shader chunks; custom shader/deformation/multiple-material paths need explicit adaptation. Visual and shadow pixel patterns use different coordinates; the coarse footprint is shared, but exact shadow-pixel parity is not claimed. Transparent receivers or separate ground-ID/depth passes must use the same coverage function. Do not run this after compositing the whole scene: that would erase actors and walls near the screen perimeter.
+
+Acceptance: native-resolution edge crop plus hero/side/back images, visible irregular scatter on every unoccluded boundary, solid interior, no underlying hard rectangle, no support loss, stable deterministic noise, no missing custom-depth coverage. Code/template tests alone are not a rendered style pass.
+
+## Shading
+
+- Compact discrete tone bands, warm light, cooler violet shadows.
+- Clear object-owned ink edges from depth/geometry discontinuities. Avoid paper halos and false contours on continuous slopes.
+- Subtle ordered dither on scenery and broad surfaces, with close tone spacing; no noisy global filter.
+- Clean undithered characters and action-critical objects. Use semantic material/object roles or an equivalent reliable separation.
+- Grounded hard directional shadows; retain depth correctness under orbit.
+
+## Implementation kit
+
+Use `templates/pixel-v2.css` for the optional narrative shell and `templates/pixel-v2-utils.mjs` for logical-buffer sizing, ordered thresholds and role-aware shade-band selection. These are independently written helpers, not a complete renderer. Start around 360×280 logical pixels for a small scene and tune against the required detail. Use compact five-band warm/cool ramps; a four-by-four ordered threshold is a good starting point. Keep character patterns several logical pixels wide. Optional plant motion can step around eight times a second while camera and physical motion remain continuous.
+
+Example page structure (wire buttons to the actual scene clock/camera):
+
+```html
+<body class="pixel-v2">
+ <main class="v2-stage">
+ <canvas tabindex="0" aria-label="Diorama. Drag to orbit."></canvas>
+ </main>
+ <nav class="v2-controls" aria-label="Scene controls">
+ <button type="button" id="pause" aria-pressed="false">pause</button>
+ <button type="button" id="reset">reset view</button>
+ </nav>
+</body>
+```
+
+For Three.js, keep the scene/depth render target at logical dimensions. Do not let `setPixelRatio` silently enlarge it. Enlarge the completed image once, using the layout helper's CSS dimensions. Mark cast and ground roles explicitly for the renderer's material/mask path. Reconstruct view depth consistently with the actual camera; compare depth discontinuities with surface slope so a continuous ramp does not become an ink line. Never colour neighbouring white background pixels to simulate a silhouette. Ground shadows on real receiving geometry and reproject them under orbit. Keep these renderer responsibilities separate from page CSS.
+
+## Scene shell and verification
+
+Author the page independently. Narrative scenes use clean white space and discreet functional controls; educational scenes keep their separate UI contract. No branded theme, source-derived stylesheet, reference game UI or external engine is needed.
+
+Test native/enlarged crops of characters, terrain and object edges; desktop/mobile scaling; hero/side/back views; keyboard orbit, pause/reset and reduced-motion. Record failures honestly. The classic post.js template is not an implementation of this preset. A CSS pixelation declaration alone is insufficient.
diff --git a/archive/v5.6.0-pixel-v2/templates/pixel-v2-ground-edge.js b/archive/v5.6.0-pixel-v2/templates/pixel-v2-ground-edge.js
new file mode 100644
index 0000000..93e3578
--- /dev/null
+++ b/archive/v5.6.0-pixel-v2/templates/pixel-v2-ground-edge.js
@@ -0,0 +1,84 @@
+import * as THREE from 'three';
+
+// Pixel Art V2 terrain perimeter. Independently authored.
+// Apply ONLY to a horizontal terrain mesh whose local coordinates are X/Z.
+// Render at logical pixel resolution; enlargement happens after this discard.
+// Use a terrain apron instead of an exposed rectangular slab for the V2 base.
+export function applyGroundEdge(mesh, {
+ halfSize = [12, 8], band = 0.16, irregularity = 0.055, seed = 3,
+} = {}) {
+ if (!mesh?.isMesh || mesh.isSkinnedMesh || mesh.isInstancedMesh || Array.isArray(mesh.material)) {
+ throw new TypeError('Ground edge needs a non-instanced terrain mesh with one material');
+ }
+ if (!(halfSize.length === 2 && halfSize.every(v => Number.isFinite(v) && v > 0)) ||
+ !Number.isFinite(band) || band <= 0 || band >= 0.5 ||
+ !Number.isFinite(irregularity) || irregularity < 0 || irregularity >= band || !Number.isFinite(seed)) {
+ throw new RangeError('Invalid terrain halfSize, edge band, irregularity or seed');
+ }
+ if (mesh.customDepthMaterial || mesh.customDistanceMaterial) {
+ throw new Error('Merge existing custom shadow materials explicitly before applying ground edge');
+ }
+ const original = mesh.material;
+ const uniforms = {
+ v2GroundHalf: { value: new THREE.Vector2(...halfSize) },
+ v2GroundBand: { value: band },
+ v2GroundRough: { value: irregularity },
+ v2GroundSeed: { value: seed },
+ };
+ const declarations = `
+ varying vec2 v2GroundXZ;
+ uniform vec2 v2GroundHalf;
+ uniform float v2GroundBand, v2GroundRough, v2GroundSeed;
+ float v2Hash(vec2 p) { return fract(sin(dot(p,vec2(91.73,237.19))) * 15731.743); }
+ float v2Noise(vec2 p) {
+ vec2 q=floor(p), f=fract(p); f=f*f*(3.0-2.0*f);
+ return mix(mix(v2Hash(q),v2Hash(q+vec2(1,0)),f.x),
+ mix(v2Hash(q+vec2(0,1)),v2Hash(q+vec2(1,1)),f.x),f.y);
+ }
+ float v2GroundCoverage() {
+ vec2 n=abs(v2GroundXZ/v2GroundHalf);
+ // Rounded rectangular footprint. Low-frequency noise changes its contour,
+ // while coverage is a binary per-pixel test rather than transparency.
+ float radius=pow(pow(n.x,6.0)+pow(n.y,6.0),1.0/6.0);
+ float wobble=(v2Noise(v2GroundXZ*.83+v2GroundSeed)-.5)*2.0*v2GroundRough;
+ return 1.0-smoothstep(1.0-v2GroundBand,1.0,radius+wobble);
+ }
+ `;
+ function patch(material, shadow) {
+ const previous = material.onBeforeCompile;
+ const key = material.customProgramCacheKey();
+ material.onBeforeCompile = function(shader, renderer) {
+ previous.call(this, shader, renderer);
+ Object.assign(shader.uniforms, uniforms);
+ shader.vertexShader = 'varying vec2 v2GroundXZ;\n' + shader.vertexShader;
+ shader.vertexShader = shader.vertexShader.replace('#include <begin_vertex>',
+ '#include <begin_vertex>\nv2GroundXZ = position.xz;');
+ shader.fragmentShader = declarations + shader.fragmentShader;
+ // Shadow coverage uses terrain coordinates, never light-map pixel coordinates.
+ // Thus the outline is coherent from every camera and shadow viewpoint.
+ const threshold = shadow
+ ? 'v2Hash(floor(v2GroundXZ*38.0)+v2GroundSeed)'
+ : 'v2Hash(floor(gl_FragCoord.xy)+v2GroundSeed)';
+ shader.fragmentShader = shader.fragmentShader.replace('#include <clipping_planes_fragment>',
+ `#include <clipping_planes_fragment>\nif (v2GroundCoverage() <= ${threshold}) discard;`);
+ };
+ material.customProgramCacheKey = () => key + ':v2-terrain-perimeter:' + shadow;
+ material.needsUpdate = true;
+ return material;
+ }
+ const owned = patch(original.clone(), false);
+ const depth = patch(new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking }), true);
+ const distance = patch(new THREE.MeshDistanceMaterial(), true);
+ mesh.material = owned;
+ mesh.customDepthMaterial = depth;
+ mesh.customDistanceMaterial = distance;
+ return {
+ uniforms,
+ dispose() {
+ if (mesh.material === owned) mesh.material = original;
+ if (mesh.customDepthMaterial === depth) mesh.customDepthMaterial = undefined;
+ if (mesh.customDistanceMaterial === distance) mesh.customDistanceMaterial = undefined;
+ owned.dispose(); depth.dispose(); distance.dispose();
+ },
+ };
+}
diff --git a/archive/v5.6.0-pixel-v2/templates/pixel-v2-person.js b/archive/v5.6.0-pixel-v2/templates/pixel-v2-person.js
new file mode 100644
index 0000000..7cda3a2
--- /dev/null
+++ b/archive/v5.6.0-pixel-v2/templates/pixel-v2-person.js
@@ -0,0 +1,91 @@
+import * as THREE from 'three';
+
+// Independently authored V2 figure. Local +Z faces forward; feet sit at Y=0.
+// Shader integration must interpret userData.pixelRole='cast': metadata alone
+// does not disable a compositor's dither or supply stepped lighting.
+const UP = new THREE.Vector3(0, 1, 0);
+function segment(parent, a, b, radius, material) {
+ const delta = b.clone().sub(a), length = delta.length();
+ const object = new THREE.Mesh(new THREE.CapsuleGeometry(radius, Math.max(.001, length - 2 * radius), 4, 8), material);
+ object.position.copy(a).add(b).multiplyScalar(.5);
+ if (length > 1e-6) object.quaternion.setFromUnitVectors(UP, delta.normalize());
+ object.castShadow = object.receiveShadow = true;
+ object.userData.pixelRole = 'cast';
+ parent.add(object);
+ return object;
+}
+function ball(parent, radius, material, scale = [1, 1, 1]) {
+ const object = new THREE.Mesh(new THREE.SphereGeometry(radius, 12, 8), material);
+ object.scale.set(...scale);
+ object.castShadow = object.receiveShadow = true;
+ object.userData.pixelRole = 'cast';
+ parent.add(object);
+ return object;
+}
+const V = (x, y, z) => new THREE.Vector3(x, y, z);
+export function createV2Person({ shirt = 0xa74538, stripe = 0xe5d7b3,
+ trousers = 0x34364c, skin = 0xc58c67, hair = 0x31252b, shoes = 0xd9d4c6,
+ height = 1.8, striped = false } = {}) {
+ if (!Number.isFinite(height) || height <= 0) throw new RangeError('Positive figure height required');
+ const root = new THREE.Group();
+ root.name = 'v2-person'; root.userData.pixelRole = 'cast';
+ root.scale.setScalar(height / 1.8);
+ const materials = [shirt, stripe, trousers, skin, hair, shoes].map(color => new THREE.MeshLambertMaterial({color}));
+ const [top, band, pants, flesh, cap, sole] = materials;
+ const body = new THREE.Group(); root.add(body);
+ const torso = segment(body, V(0,.84,0), V(0,1.37,0), .19, top);
+ torso.scale.x = 1.12; torso.scale.z = .76;
+ const pelvis = ball(body,.19,pants,[1,.7,.8]); pelvis.position.y=.84;
+ // Broad geometry bands stay in garment space, including under body lean.
+ if (striped) for (const y of [1.04,1.22]) {
+ const ring = new THREE.Mesh(new THREE.CylinderGeometry(.195,.195,.07,12),band);
+ ring.scale.set(1.12,1,.76); ring.position.y=y;
+ ring.castShadow=ring.receiveShadow=true;ring.userData.pixelRole='cast';body.add(ring);
+ }
+ const neck=segment(body,V(0,1.34,0),V(0,1.48,0),.065,flesh);
+ const head=ball(body,.15,flesh,[.92,1.12,.94]);head.position.set(0,1.58,.012);
+ const hairCap=ball(head,.151,cap,[.96,.7,.97]);hairCap.position.set(0,.06,-.018);
+ const nose=ball(head,.027,flesh,[.65,.6,1]);nose.position.set(0,-.006,.14);
+ // Real joint hierarchy; shoulder/hip pitch is local X rotation.
+ function limb(anchor, upperLength, lowerLength, radius, upperMaterial, lowerMaterial, isLeg) {
+ const pivot=new THREE.Group();pivot.position.copy(anchor);body.add(pivot);
+ segment(pivot,V(0,0,0),V(0,-upperLength,0),radius,upperMaterial);
+ const bend=new THREE.Group();bend.position.y=-upperLength;pivot.add(bend);
+ segment(bend,V(0,0,0),V(0,-lowerLength,0),radius*.78,lowerMaterial);
+ const tip=new THREE.Group();tip.position.y=-lowerLength;bend.add(tip);
+ const end=ball(tip,isLeg?.085:.063,isLeg?sole:flesh,isLeg?[1,.65,1.7]:[.85,1.1,.8]);
+ if(isLeg)end.position.z=.055;
+ return {pivot,bend,tip};
+ }
+ const legs=[-.105,.105].map(x=>limb(V(x,.84,0),.39,.395,.078,pants,pants,true));
+ const arms=[-.235,.235].map(x=>limb(V(x,1.32,0),.275,.25,.065,top,flesh,false));
+ function pose({ crouch=0, lean=0, hip=[0,0], knee=[0,0], shoulder=[0,0], elbow=[.13,.13], headYaw=0 }={}) {
+ body.position.y=-Math.max(0,Math.min(1,crouch))*.25;
+ body.rotation.x=lean;
+ for(let i=0;i<2;i++) {
+ legs[i].pivot.rotation.x=hip[i]; legs[i].bend.rotation.x=knee[i];
+ arms[i].pivot.rotation.x=shoulder[i];arms[i].bend.rotation.x=elbow[i];
+ }
+ head.rotation.y=headYaw;
+ root.updateMatrixWorld(true);
+ }
+ // Low-level deterministic pose sample. For travelling walks use a foot-lock/IK
+ // controller: this preview cycle alone is NOT planted-foot locomotion.
+ function sample(time,{action='idle',phase=0,amount=1}={}) {
+ if(!Number.isFinite(time)||!Number.isFinite(phase))throw new RangeError('Finite pose time required');
+ const p=Math.min(1,Math.max(0,phase));
+ if(action==='walk-preview') {
+ const a=Math.sin(time*Math.PI*2),b=-a;
+ pose({hip:[a*.42,b*.42],knee:[-Math.max(0,-a)*.6,-Math.max(0,-b)*.6],shoulder:[b*.28,a*.28]});
+ } else if(action==='reach') {
+ const reach=Math.sin(Math.PI*p)*amount;
+ pose({shoulder:[-reach*1.3,.06],elbow:[.2+reach*.25,.14],lean:reach*.06});
+ } else if(action==='idle') pose({headYaw:Math.sin(time*.6)*.055,shoulder:[.035,-.035]});
+ else throw new Error('Unknown V2 action: '+action);
+ }
+ pose();
+ return {root,body,legs,arms,head,pose,sample,
+ grips:arms.map(a=>a.tip),feet:legs.map(l=>l.tip),
+ dispose(){const geometries=new Set();root.traverse(o=>{if(o.geometry)geometries.add(o.geometry);});for(const g of geometries)g.dispose();for(const m of materials)m.dispose();}
+ };
+}
diff --git a/archive/v5.6.0-pixel-v2/templates/pixel-v2-utils.mjs b/archive/v5.6.0-pixel-v2/templates/pixel-v2-utils.mjs
new file mode 100644
index 0000000..f373199
--- /dev/null
+++ b/archive/v5.6.0-pixel-v2/templates/pixel-v2-utils.mjs
@@ -0,0 +1,28 @@
+// Independent numerical helpers for Pixel Art V2; not a complete renderer.
+export function pixelLayout(width, height, dpr = 1, logicalWidth = 360, logicalHeight = 280) {
+ if (![width, height, dpr, logicalWidth, logicalHeight].every(v => Number.isFinite(v) && v > 0)) {
+ throw new RangeError('Pixel layout dimensions must be finite and positive');
+ }
+ const physicalWidth = Math.max(1, Math.floor(width * dpr));
+ const physicalHeight = Math.max(1, Math.floor(height * dpr));
+ const shrink = Math.min(1, physicalWidth / logicalWidth, physicalHeight / logicalHeight);
+ const bufferWidth = Math.max(1, Math.floor(logicalWidth * shrink));
+ const bufferHeight = Math.max(1, Math.floor(logicalHeight * shrink));
+ const scale = Math.max(1, Math.floor(Math.min(physicalWidth / bufferWidth, physicalHeight / bufferHeight)));
+ return { bufferWidth, bufferHeight, deviceScale: scale,
+ cssWidth: bufferWidth * scale / dpr, cssHeight: bufferHeight * scale / dpr };
+}
+
+// Recursive ordered threshold construction: a stable four-by-four logical grid.
+export function orderedThreshold(x, y) {
+ const cell = (a, b) => ((a ^ b) * 2 + b);
+ const ix = Math.floor(x) & 3, iy = Math.floor(y) & 3;
+ return (4 * cell(ix & 1, iy & 1) + cell(ix >> 1, iy >> 1) + 0.5) / 16;
+}
+
+export function shadeBand(light, x, y, role = 'scenery', levels = 5, strength = 0.45) {
+ if (!Number.isInteger(levels) || levels < 2) throw new RangeError('At least two shade bands required');
+ const value = Math.min(1, Math.max(0, light)) * (levels - 1);
+ const texture = role === 'cast' ? 0 : (orderedThreshold(x, y) - 0.5) * strength;
+ return Math.min(levels - 1, Math.max(0, Math.floor(value + 0.5 + texture)));
+}
diff --git a/archive/v5.6.0-pixel-v2/templates/pixel-v2.css b/archive/v5.6.0-pixel-v2/templates/pixel-v2.css
new file mode 100644
index 0000000..d4a70f6
--- /dev/null
+++ b/archive/v5.6.0-pixel-v2/templates/pixel-v2.css
@@ -0,0 +1,43 @@
+/* Pixel Art V2: optional narrative scene shell. */
+body.pixel-v2 {
+ margin: 0;
+ color: #292731;
+ background-color: white;
+ font: 0.8125rem/1.4 ui-monospace, monospace;
+}
+.pixel-v2 .v2-stage {
+ position: fixed;
+ inset: 0;
+ display: grid;
+ align-items: center;
+ justify-items: center;
+ overflow: clip;
+}
+.pixel-v2 canvas {
+ display: block;
+ image-rendering: pixelated;
+ touch-action: none;
+ cursor: grab;
+}
+.pixel-v2 canvas:active { cursor: grabbing; }
+.pixel-v2 .v2-controls {
+ position: fixed;
+ inset-inline-end: max(1rem, env(safe-area-inset-right));
+ inset-block-end: max(1rem, env(safe-area-inset-bottom));
+ display: flex;
+ gap: 0.75rem;
+ z-index: 2;
+}
+.pixel-v2 button {
+ font: inherit;
+ padding: 0.65rem;
+ color: #77717b;
+ background: transparent;
+ border: none;
+ cursor: pointer;
+}
+.pixel-v2 button:hover { color: #292731; }
+.pixel-v2 :is(button, canvas):focus-visible {
+ outline: 2px solid #746783;
+ outline-offset: 3px;
+}
diff --git a/media/education-selection-focus.png b/media/education-selection-focus.png
new file mode 100644
index 0000000..e11920d
Binary files /dev/null and b/media/education-selection-focus.png differ
diff --git a/media/education-ui-desktop.png b/media/education-ui-desktop.png
new file mode 100644
index 0000000..18dc127
Binary files /dev/null and b/media/education-ui-desktop.png differ
diff --git a/media/education-ui-phone.png b/media/education-ui-phone.png
new file mode 100644
index 0000000..b19d957
Binary files /dev/null and b/media/education-ui-phone.png differ
diff --git a/media/education-ui-right.png b/media/education-ui-right.png
new file mode 100644
index 0000000..38553fb
Binary files /dev/null and b/media/education-ui-right.png differ
diff --git a/media/stroked-toon-reference.jpg b/media/stroked-toon-reference.jpg
new file mode 100644
index 0000000..9928397
Binary files /dev/null and b/media/stroked-toon-reference.jpg differ
diff --git a/media/stroked-toon-service-reference.jpg b/media/stroked-toon-service-reference.jpg
new file mode 100644
index 0000000..c964e44
Binary files /dev/null and b/media/stroked-toon-service-reference.jpg differ
diff --git a/references/INDEX.md b/references/INDEX.md
new file mode 100644
index 0000000..d10dc40
--- /dev/null
+++ b/references/INDEX.md
@@ -0,0 +1,52 @@
+# On-demand reference index
+
+Do not load all entries. Read the exact topic required for the next action. The restored full SKILL.md is primary. Supplemental references extend its approved sourcing/representation rules; narrative scenes skip educational UI and lesson requirements.
+
+- **People/animals/seats, routes and building clearance (5.2)** → `action-clearance.md`, `../templates/action-clearance.mjs`, `../templates/pose-bounds.mjs`
+- **Subject representation: actual thing vs physical aid vs explanatory abstraction (4.6)** → `representation.md`
+- **Educational models: free commercial modification/redistribution + accuracy gate (4.5)** → `educational-models.md`, `../templates/educational-asset-gate.mjs`
+- **Narrative sourcing: sweep the Polyfork CDN before modelling (4.4)** → `external-models.md`
+- **Working-space/contact/scope/live-anchor checks (4.2)** → `interfaces.md`, `../templates/interface-checks.js`
+- **Efficient milestone/QA loop (4.1)** → `build-loop.md`
+- **Ground/floor, proportions, Inside and material realism (4.1)** → `realism.md`
+- **Precision/repair adapter (optional deeper assurance)** → `reliability.md`
+- **Reusable explicit placement, real holes and solved perspective fit** → `../templates/construction-kit.js`
+
+- **Render Preset Gate (ask once, every project)** → `render-preset-gate-ask-once-every-project.md`
+- **When to Use** → `when-to-use.md`
+- **Research Before You Model** → `research-before-you-model.md`
+- **One Prompt, One Build** → `one-prompt-one-build.md`
+- **Starting A New Diorama** → `starting-a-new-diorama.md`
+- **Educational Mechanism Profile (first-class exception)** → `educational-mechanism-profile-first-class-exception.md`
+- **Canonical educational UI and inspection contract** → `education-ui.md + inspection.md`
+- **Repair acceptance: enclosure, fit and reference UI (3.15)** → `repair-acceptance-enclosure-fit-and-reference-ui-3-15.md`
+- **Construction regression gates** → `construction-regression-gates.md`
+- **Universal Inspection Controls** → `universal-inspection-controls.md`
+- **Optional Pixel + Stroke Hybrid** → `optional-pixel-stroke-hybrid.md`
+- **Optional Stroked-Toon Preset** → `optional-stroked-toon-preset.md`
+- **The Look Contract** → `the-look-contract.md`
+- **The Detail Bar** → `the-detail-bar.md`
+- **The Animation Bar** → `the-animation-bar.md`
+- **Numbers That Make It Read** → `numbers-that-make-it-read.md`
+- **Pipeline** → `pipeline.md`
+- **New Subject Intake** → `new-subject-intake.md`
+- **Palette And The Post Pass** → `palette-and-the-post-pass.md`
+- **Camera And Framing** → `camera-and-framing.md`
+- **Scene Furniture** → `scene-furniture.md`
+- **Detail Recipes** → `detail-recipes.md`
+- **The Cast** → `the-cast.md`
+- **Animation** → `animation.md`
+- **System And Combat Animation** → `system-and-combat-animation.md`
+- **Service And Queue** → `service-and-queue.md`
+- **Vehicles** → `vehicles.md`
+- **Effects** → `effects.md`
+- **Combat Readability (towers, bosses, deaths)** → `combat-readability-towers-bosses-deaths.md`
+- **Build And Ship** → `build-and-ship.md`
+- **Surface, Motion And Event FX** → `surface-motion-and-event-fx.md`
+- **Motion Graphics Primitives (arrows, flames, flow)** → `motion-graphics-primitives-arrows-flames-flow.md`
+- **Verification** → `verification.md`
+- **Pitfalls** → `pitfalls.md`
+- **Project Layout** → `project-layout.md`
+- **Skill Maintenance** → `skill-maintenance.md`
+- **Field Notes: Two-Creature Combat** → `field-notes-two-creature-combat.md`
+- **Changelog** → `changelog.md`
diff --git a/references/action-clearance.md b/references/action-clearance.md
new file mode 100644
index 0000000..cff1ad8
--- /dev/null
+++ b/references/action-clearance.md
@@ -0,0 +1,73 @@
+# Occupied space through actions — people, animals and scenery
+
+Applies to authored AND downloaded assets, narrative AND educational, all render presets. An asset looking good alone is not proof it can sit, walk or fit here. Prevent visible intersections through layout/frames/trajectories; don't bolt on a random physics response after the animation has already put two bodies in the same space.
+
+## 1. Reserve space before dressing it
+
+- Buildings/stands: measure complete transformed envelopes, including roof/awning/steps/fences. Reserve independent parcels, door swing, entrances, paths and maintenance access. Use actual doorway/aisle widths versus the travelling body's full width, including carried objects. Don't space houses by origins or visual centres.
+- Separate static structure, dynamic actors and authored contact surfaces. For an accessible building, use wall/column/roof/doorway pieces; its enclosing AABB contains legitimate interior space. A whole-building proxy flag is a candidate requiring decomposition, not evidence to delete the building or ban all occupants.
+- People/animals: reserve torso/head/limb/tail/wing and carried-prop space for the LARGEST relevant pose, not just a T-pose thumbnail, root point or upright body radius. Test final scale and chosen clips before adopting an imported rig. Reroute or choose a suitable rig/clip if the candidate cannot perform the required action.
+- Paths use swept widths and turning/gesture envelopes, not centreline separation. Give queues measured headway and unique standing slots; crossings use deterministic yielding/time reservations. Include fast vehicles, low roofs, railings, benches, doors and departing riders. Prefer fewer well-spaced supporting actors to an overcrowded scene; don't erase the hero action or important detail.
+
+## 2. Seating is a frame/state contract
+
+Each seat has one real local frame plus support height, usable width/depth, backrest plane, footwell, approach/exit path and occupancy interval. A seated actor is not a standing rig translated downward.
+
+Use approach → turn/align → lower pelvis and bend hips/knees → supported sit → stand → exit. Solve pelvis/seat and feet/ground from the ACTUAL rig and surfaces. Check knee/thigh/torso against backrest, armrests, table, rails and neighbouring occupants; sole and pelvis support gaps must also pass the separate contact check. Don't sink feet into the slab to fake a seated silhouette. Occupied-seat reservations prevent two people claiming the same seat. Ride seats and carried objects inherit the moving parent's frame; don't add the same world displacement twice. A seat moving or rotating must carry its rider through the same local-to-world chain.
+
+Allow named intended contact such as pelvis↔seat support, sole↔ground, palm↔carried handle, adjacent anatomical joint or a named structural joint, with explicit phase window and bounded depth. It does NOT exempt the entire person/chair/car, other limbs or other phases. A collision exemption is NOT proof of support: floating above a seat still needs a real face-gap check. Keep any intended combat/contact event similarly scoped.
+
+## 3. Measure actual poses, then choose occupied proxies
+
+Copy `templates/pose-bounds.mjs` and inject the project's THREE:
+
+```js
+const posed = createPoseBounds(THREE);
+// After the actual scene evaluator/mixer has applied this phase:
+const measured = posed.measure(mesh, {includePoints: true});
+// Optional {frame: parent} for local measurements; rigid instances need instanceId.
+```
+
+This reads active indexed/draw-range vertex positions via `getVertexPosition`, including CPU skin/morph deformation, updates bone/world frames and does not silently discard transparent or hidden physical geometry. It ignores stale geometry.boundingBox/constructor dimensions. Shader/displacement/batched or unsupported instance-morph deformation fails explicitly; supply a justified geometry-aware method, not zero occupied space. Material/group ranges can be over-covered. Pose bounds are conservative envelopes, not occupied-solid intersection tests.
+
+For useful fine checks, assign stable semantic proxy IDs to real body regions: torso, head, upper/lower arms, thighs/shins, paws, muzzle/horns, tail/wing segments, bags/carried items. Boxes represent actual structural pieces, not an enclosing hollow room. Set proxy radii/extents from the final imported geometry/poses and compare against real posed vertices and representative contact crops. Don't fabricate thin proxies to make a failing actor pass. Point/bounds samples alone don't prove arbitrary triangle/solid coverage; retain uncertainty for unsupported coverage. Conservative whole-pose bounds are a safe broad screen but may overflag seated/curved subjects. Refine those candidates rather than reporting them as certified mesh penetration.
+
+## 4. Reuse the small proxy checker
+
+`templates/action-clearance.mjs` provides `createActionClearance(THREE)`:
+
+- `sphere(center,radius)`, `capsule(a,b,radius)`, `obb(center,halfSize,quaternion?)` use WORLD units/axes and full radius/half extents. Fresh shape callbacks follow current bone/parent poses; don't cache a standing capsule forever. Convert nonuniformly scaled imports correctly; arbitrary affine shear is not an OBB rotation.
+- `pairCheck(a,b)` returns signed proxy separation/penetration plus method. Capsule distance is segment distance; capsule/box uses analytic outside distance and a deepest-centerline signed bound inside. Box/box SAT gives an axis bound, not exact Euclidean gap or mesh intersection. Use the reported method honestly.
+- `auditPose({parts,requiredIds,time,clearance,contacts})` checks registered near pairs using sweep-and-prune expanded bounds. Same-owner parts are NOT globally ignored. `parts` are `{id,owner,getShape(time)}`; contacts name EXACT `{a,b,start,end,maxPenetration,reason}`. Production scene runs must supply `requiredIds` from the independent design inventory, NOT `parts.map(...)`. Exact matching yields `coverageVerified:true`; omission yields false and cannot certify scene completeness. Missing/duplicate IDs, invalid geometry/data and unbounded/missing contact references fail closed. No exclusion by colour, material, actor type or transparency.
+- `timesForInterval(start,end,{maxStep,eventTimes})` includes endpoints and exact specified events. `auditMotion({source,times,parts,clearance,contacts})` calls synchronous `source.evaluate(t)` before each pose snapshot; use the REAL production driver and wait for assets to load first. Times must be strictly increasing, unique and cover at least two poses; use `auditPose` for a single still. Capture/freeze/restore the previous user time yourself. Each audit has a fixed independent active inventory and one rule per contact pair. Split runs at authored spawn/exit changes or repeated disjoint contact windows, derive active IDs from the schedule (not `visible`), and check both sides of each boundary. Do not widen a contact window or depth merely to suppress a failure.
+
+```js
+const c = createActionClearance(THREE);
+const parts = [
+ {id:'visitor/forearm', owner:'visitor',
+ getShape:()=>c.capsule(elbow.getWorldPosition(new THREE.Vector3()),
+ wrist.getWorldPosition(new THREE.Vector3()), forearmRadius)},
+ {id:'kiosk/wall', owner:'kiosk', getShape:()=>c.obb(wallCenter, wallHalfSize, wallRotation)},
+];
+const times=c.timesForInterval(0,loopDuration,{maxStep:chosenStep,eventTimes:criticalTimes});
+const result=c.auditMotion({source:sceneEvaluator,times,parts,
+ requiredIds:expectedCollisionIds, // independent DESIGN inventory
+ clearance:sceneClearance,contacts:declaredContacts});
+if (!result.clear || !result.coverageVerified) reportAndRepair(result.worstCases);
+```
+
+This example is only two pieces: the actual registry must cover independently declared required actors/appendages/obstacles and their meaningful nearby pairs. A missing actor never becomes “clear” just because it wasn't registered. Separate active-presence intervals (actual enter/exit/pool state) from material visibility; don't remove a currently occupied body to make a checker pass. Explicit adjacent-joint contact can be valid; arm through torso, tail through fence or knees through a table is not.
+
+## 5. Sample the action, not one attractive frame
+
+Check full cycles plus loop seam, approach/contact/departure, largest reach, extremes, seat entry/exit, crossing times, door swing, carried transfers and spawn/exit transitions. Test planted feet/paws against the moving/uneven support as well as other actors. Include both moving bodies at the SAME evaluation time.
+
+Choose time spacing from the smallest relevant feature/clearance and a defensible bound on relative tip motion (including rotations), not an arbitrary “three frames”. Refine near violations and between samples with large limb/prop displacement; check exact state boundaries on both sides. A sampled pass is **sampled evidence**, never continuous collision freedom. `auditMotion` reports `sampledOnly:true`; it does not estimate missing motion bounds, solve trajectories or guarantee against tunnelling between unsampled times. A uniform frame rate alone is not a continuous proof.
+
+Fix the shared causes: seat/rig scale, joint/pivot, path lane/width, building parcel, root-motion duplication, reservation or action timing. Deterministic retiming/yielding is preferable to frame-by-frame jitter or random nudges. Never hide clipping by fading bodies, disabling depth, shrinking colliders, freezing all motion, deleting obstacles or allowing all same-owner/contact pairs.
+
+## 6. One affected QA pass, not another dashboard
+
+Keep one scene QA runner. Cache immutable static obstacle data; broad-screen neighbours, refine only relevant candidates. Test imported clips before spawning many copies, then verify all instances at their final transforms/scales and schedule offsets. Print a count and the worst few pairs/phase/depth; keep full evidence on disk. A proxy-overlap candidate must be resolved against the intended proxy/actual geometry, not optimized into a smaller unexplained count.
+
+Rerun the SAME predicate after real mutations: move a wrist/tail into a wall, move a seated knee into the backrest, overlap two building footprints, align two actors at a crossing, exceed a named seat-contact tolerance. Each must flag for the right reason; restoring the source relation must pass again. Check side/back/top/contact crops and a short action strip for the worst live interaction. These regressions test the helper and supplied fixtures—not every future actor or a new full amusement park. No educational UI or label system is added by collision QA.
diff --git a/references/animation.md b/references/animation.md
new file mode 100644
index 0000000..c1bdb22
--- /dev/null
+++ b/references/animation.md
@@ -0,0 +1,119 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Animation
+
+Every motion is a pure function of `t` or of a distance along a track.
+
+```js
+const swing = Math.sin(phase), cs = Math.cos(phase);
+const kneeL = 0.05 + 0.46*Math.max(0,-cs) + 0.22*Math.max(0, swing);
+const kneeR = 0.05 + 0.46*Math.max(0, cs) + 0.22*Math.max(0,-swing);
+pose = {
+ torso: [lean, swing*0.05, 0],
+ shoulderL: [-swing*arm, 0, -0.09], shoulderR: [swing*arm, 0, 0.09],
+ elbowL: [-0.16 - Math.max(0, swing)*0.28, 0, 0],
+ elbowR: [-0.16 - Math.max(0,-swing)*0.28, 0, 0],
+ hipL: [swing*amp, 0, 0.03], hipR: [-swing*amp, 0, -0.03],
+ kneeL: [kneeL,0,0], kneeR: [kneeR,0,0],
+ ankleL: [-kneeL*0.32,0,0], ankleR: [-kneeR*0.32,0,0],
+};
+```
+
+- Hips above ±0.35 read as a march; 0.30 to 0.34 is a walk, 0.5+ is a run with
+ lean 0.26 and elbows near -0.75.
+- Match travel to stride or feet skate: `footTravel = 2*legLength*sin(amp)`,
+ `speed = footTravel * phaseRate / PI`. A 0.86 leg at 0.34 rad and 5.2 rad/s is
+ about 0.9 m/s. Drive `phase` from distance travelled, not from time, and the
+ walk always matches the path.
+- A track is a Catmull-Rom sampled to an arc-length table with `groundY` heights
+ smoothed by three 1-2-1 passes, so steps read as ramps. `at(d)` returns
+ position and heading.
+- Sit: hip X around -1.35 to -1.50, knee +0.5 to +1.3 so the shin drops
+ vertically, torso back 0.05 to 0.1. Seat height is a measured constant.
+- Climb: hands start above the head, opposite hand and foot move together, hips
+ stay close to the ladder (0.12 to 0.2 m) and swing 0.06 to 0.10. Rung spacing
+ 0.30 m, climb 1.0 to 1.2 m/s, phase driven by height, not time. Feet land on
+ rungs, not between them; the shadow belongs on the ladder/deck, not the slab.
+- One-shot actions (jump, dive, kick) are phase tables with eased poses, never a
+ blend between two loops. Hoist shared easing factors above the branch: a
+ `const` declared in one branch and read in another throws every frame and
+ freezes the figure. Pose targets are full poses, not deltas.
+- Airborne arcs are solved backwards from the impact: for a fixed flight `T`,
+ `vy = (landY - launchY + 4.9*T*T)/T`. A guessed `vy` either lands late or
+ stops in mid-air.
+- The rig root is at the feet, so a rigid-body spin sweeps the model around its
+ toes: rotate about a pivot `C` with `p' = p + C - R*C`, C about 0.55 up.
+
+### Carrying, Loading And Mounting
+
+These are the beats closest to the camera and the ones users report first. A
+prop that teleports, a hand that misses it, or a leg that swings through the
+handlebars destroys the whole miniature.
+
+**Carry.** Keep the prop in world space and solve its transform from the hands
+every frame; do not parent a big prop to a wrist group (it inherits the wrist
+roll and swims).
+
+```js
+const hl = new THREE.Vector3(), hr = new THREE.Vector3();
+J.wristL.getWorldPosition(hl); J.wristR.getWorldPosition(hr);
+const mid = hl.clone().add(hr).multiplyScalar(0.5);
+bag.position.set(mid.x, Math.min(hl.y, hr.y) - 0.42, mid.z);
+```
+
+- Build the prop with its origin at the **bottom centre**. Then a hold offset is
+ a single subtraction, and the same object seats on the ground/crate floor
+ without a second pivot.
+- Two hands for anything heavier than a paper bag. The palms must be within
+ 0.08 m of the prop surface at every sampled frame; log the wrist positions and
+ the prop bounds.
+- Match the carry pose to the weight: heavy box at the belly, shoulders -1.2 to
+ -1.4, elbows -1.2 to -1.4, torso lean 0.2; a light bag hangs from one wrist
+ with the elbow nearly straight.
+- Reduce arm swing while carrying; the legs do the walking. A full arm swing
+ with a box in the hands reads as a puppet.
+- **Handoff:** at contact, set the prop to the receiver's hold for one frame, then
+ blend ownership over 0.2 to 0.3 s. A hard parent switch pops even when the
+ world positions match.
+
+**Loading into a crate or hatch.**
+
+1. Lift the prop above the rim in front of the chest, with both hands on it.
+2. Tuck the prop's x/z over the opening while the hands stay on it.
+3. Lower it until its base reaches the floor; keep the hands on it for a beat.
+4. Release, step back, and only then close the lid, clip the bungee or turn away.
+
+Never translate the prop from hands to slot in one frame, and never let it
+descend outside the crate wall. A bungee or lid that intersects the prop on the
+way in must animate open and closed; hiding it for the whole beat reads as a
+missing part.
+
+**Mounting a scooter, bike or horse.**
+
+Author the mount in the vehicle's local frame, from a measured seat/board, not
+by eye.
+
+- Place the left boot on an outboard running board or peg. If the vehicle has
+ none, add one; standing on the body or the seat reads as a doll being posed.
+- Swing the right leg **out to the side** with hip Z abduction (about +0.9 to
+ +1.25 rad), knee flexed 1.2 to 1.4. Hip X flexion swings the leg forward,
+ through the handlebars; that is the common error.
+- Raise the root in a small arc (0.10 to 0.20 m) so the boot clears the saddle,
+ then drop onto the seat. Do not hop a body-height above it.
+- Seat root = the pelvis mesh's contact point, not the rig origin. Sit with the
+ pelvis on the cushion, both boots on the boards, knees 0.9 to 1.1 rad, toes
+ forward; hands reach the grips with soft elbows. Move the bars to the hands
+ before hyperextending the arms.
+- A rider pose is not the standing pose rotated: torso upright 0.15 to 0.25,
+ hips flexed -0.9 to -1.1, hips abducted ±0.25 to ±0.35, knees 1.0 to 1.1,
+ ankles near -0.05.
+- Keep the vehicle and rider on the same mover after departure, with the rider
+ root attached to the seat anchor; a bob applied to one and not the other
+ separates them.
+
+**Proof.** A nine-frame side strip at 0.15 to 0.25 s spacing: approach, lift,
+over-rim, lower, release, step, leg-swing, seat contact, ride. Shoot it at 1:1
+and log wrists, ankles, prop base and seat. A still cannot prove a mount.
+
diff --git a/references/build-and-ship.md b/references/build-and-ship.md
new file mode 100644
index 0000000..59aa375
--- /dev/null
+++ b/references/build-and-ship.md
@@ -0,0 +1,47 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Build And Ship
+
+`templates/build.mjs` bundles `src/main.js` to `dist/app.js` with esbuild (IIFE),
+writes `index.html` and a standalone HTML with the bundle inlined, escapes
+`</script` in the payload, and passes the replacement as a **function**, not a
+string. `String.replace` expands `$&`, `$'`, `` $` `` and `$1` inside a string
+replacement; a minified bundle routinely contains those sequences, which
+silently injects the `<script src=...>` tag into the middle of the app and
+breaks the standalone file. Always test the standalone over `file://`, not just
+the served page. `--minify` for shipping; expect roughly 780 kB with
+three.js inside.
+
+Freeze and seek come free if everything is a function of `t`:
+
+```js
+const params = new URLSearchParams(location.search);
+const frozen = params.has('t') ? parseFloat(params.get('t')) : null;
+const startAt = params.has('from') ? parseFloat(params.get('from')) : 0;
+window.__diorama = { THREE, scene, camera, renderer, post, director, cast,
+ robbers, cops, mats, TL, CLIP, freeze(t){ frozen = t; draw(t); }, play(){}, view(){} };
+```
+
+`?t=12.4` is the whole QA surface: every screenshot and every diagnosis is a
+frozen frame, so a screenshot never depends on timing luck.
+
+### The research gate, at ship time
+
+A build is not finished until these exist. Check them before the summary:
+
+- [ ] `refs/<subject>/` has at least one contact sheet stepped from real footage.
+- [ ] `refs/SOURCES.md` answers the four questions (shape, motion, asset, proof)
+ with the queries actually run. "Nothing found" is a valid answer only with
+ the query written down next to it.
+- [ ] `CREDITS.md` has a row per imported asset, and every licence is CC0, CC-BY,
+ public domain, or owned by the user.
+- [ ] Every hero asset walked the ladder: disk, CC0, CC-BY, then hand-built. If it
+ was hand-built, the row says so.
+- [ ] The captures for each beat exist, and each one was compared against the
+ reference frame for that beat.
+
+A missing `SOURCES.md` means the research step was skipped, and the scene is
+probably wearing the generic version of its genre.
+
diff --git a/references/build-loop.md b/references/build-loop.md
new file mode 100644
index 0000000..eb8187e
--- /dev/null
+++ b/references/build-loop.md
@@ -0,0 +1,56 @@
+# Small build loop for weak 3D agents
+
+## Default working set
+
+Core + DESIGN + chosen render recipe first. At each milestone read only the required API/subsection. Reuse the renderer, orbit, selection and educational UI; don't ask a weak model to invent all those while designing complicated geometry. `construction-kit.js` supplies explicit placement, actual holes and solved perspective fit; it is not a physics/collision solver. Keep subject-specific construction simple and reference-grounded.
+
+The scene spec drives completeness. Numerical counts refer to functional repeats or required anatomy—not incidental mesh totals. Expected counts are independently declared. Physical leaves and selection scopes are separate even if both use stable semantic IDs.
+
+## Working structure
+
+- `config`: primary dimensions, local frames, required roles, repeated-instance data, three causal states. Derive all dependent dimensions from these values.
+- `build`: parametric assemblies, each returning group, real local ports/support faces, occupied proxies, motion handles and semantic members.
+- `evaluate`: one pure state/phase evaluator using those handles/frames. No independent lesson clock, no global bottle positions that ignore moving parents.
+- `main/ui`: supplied presentation/orbit/inspection adapters and live geometry-derived annotations.
+- `qa/check.mjs`: parameterized checks/captures in one runner; report linked to loaded artifact, baseline checkpoint written once using exclusive creation. More files only for a genuinely separate reusable test, not each camera experiment.
+
+Do not enforce these literal filenames on an existing sound project. Keep responsibilities separate, not a new framework.
+
+For a pocket, joint or moving interface, use `interfaces.md` and the bounded `interface-checks.js` API instead of writing a new validator from scratch. Reserve its local working space first; keep the support load path below/around it. Check siblings inside one assembly as well as separate neighbours.
+
+## Six checks worth doing first
+
+1. **Supports:** actual top/bottom mating-face gap and contact footprint; test one lifted support with the same predicate. Do not change a named bearing datum in one source but leave its collar at an old height.
+2. **Repeats:** all station/bolt/rod frame residuals and expected count. Independent X/Z grid indices; rod collars use the same local rod frame as their bushings.
+3. **Mechanical interfaces:** real bore surface vs shaft/cap envelope and travel, gear shared module/tooth-pitch/ratio, useful actuator range. A valid equation between copied config fields does not prove geometry.
+4. **Transfer/flow:** full bottle/nozzle/path envelope through the actual opening; support across a transfer; real pipe endpoints; test extrema/approach/contact/departure. Transparent products and guards are still physical.
+5. **Presentation/selection:** project full geometry after fitting, inside the actual stage-safe NDC rectangle; assert selected scope is visible, not merely that material pointers changed. Preserve material/map/ramp contents and identities, and evaluator-owned visibility. Test Clear and Reset. No fixed camera-distance exception over a solved fit.
+6. **Callout/state:** displayed text, units and pointer/label rectangle at a relocated/rotated part and two frozen states. Coordinates returning to baseline is only part of this test.
+
+These aren't six new audit frameworks. They are small predicates against a shared model, run early and again only after relevant changes.
+
+## Where to use broad phase
+
+Separate building lots and resting props: full-envelope separation is useful. Nested machines: start with explicit risky pairs and proper analytic occupied shapes. An annular bearing's outer AABB contains its shaft; minimizing its overlap count destroys the mechanism. Do not target a lower number of AABB candidates. Missing member, empty sample or unresolved pair is UNKNOWN, never CLEAR. Candidate identity includes both physical owners and member IDs; don't collapse absent-mesh rows to an empty deduplication key.
+
+Optional `scene-contract.js` can check simple separated rigid fixtures and their axis-aligned support contacts. It does not cover within-one-assembly members, arbitrary bores/gear engagement or continuous motion. Read its own limits if using it; never demand it become a generic mechanism certificate. If an analytic proxy cannot represent an interface, use a known construction/mesh method for that interface, not a blanket assembly/material exemption.
+
+## Short iteration contract
+
+- At the first runnable layout, save three small views (hero/reverse/phone) and the cheap geometry result. If proportions/visibility/ground are wrong, fix primary layout now.
+- Develop the highest-risk interface before repetition/detail. Once it passes, generate all repeats from its frame table and recheck them numerically.
+- After at most two unsuccessful local fixes of the same defect, replace its dimensions/assembly construction from the shared frame. Repeating offsets, deleting supports and widening tolerances are not progress.
+- Reuse one browser/page; parameterize view/time/selection. Don't create `diag-camera2`, `diag-camera3`, `diag-camera4` files or repeatedly launch the whole suite to change one pose.
+- Show only worst five failures in tool output and a short repair note. Full results remain on disk. No long speculative narration between calls.
+- A missing skill API should be fixed once in the reusable kit during maintenance; don't create per-scene shadow versions of the same helper.
+- Final captures: hero, reverse, phone, one critical interface, selected/restored and a short motion strip if moving. Add a view only if it answers a specific unresolved question. A report is evidence storage, not the deliverable's main attraction.
+
+## Real mutation coverage
+
+Use the production check as-is. Baseline → change geometry/state → rerun same check → expected failure → restore → same check passes. Reject a wrong relation, not the presence/name of a test injection. Examples: lift a support and check actual gap; shift one repeated joint and check all residuals; change camera fit and check projected bounds; mutate a shared map and check borrowed source contents. A bespoke `injectedObject.parent === null` detector is not the missing-member validator.
+
+Save the original failure with its artifact hash. Don't overwrite the first evidence or convert empty/missing adjudication into zero hits. Report scoped correctness without demanding structural stress/life/safety calculations the user did not request.
+
+## Rotary trial evidence and what changed
+
+Observed source failures included duplicated foot-bolt positions, an actual bearing/collar height gap, misplaced rod collars, incompatible gear pitch versus driven tooth ratio and guessed selected-camera targets. The first QA suite removed transparent geometry/products from coverage, compared outer radii/centres as if they were occupied-solid clearances, and used bespoke negative detectors. Many diagnostics and eight broad-phase count iterations did not fix the visible selected view. The revised core replaces those incentives with shared frames, first-interface proof, solved fit and a much smaller real-risk loop. A later scoped mount repair did fix the pictured arm-through-pocket: short inner spokes now carry the annular table, fixture plates/bolt heads meet shared seat datums, and the rotating stack meets its bearing face. Its 44 checks and two production-predicate mutations certify only that bounded repair; they do not repair/certify the rest of the machine or prove an unrun exact-model benchmark.
diff --git a/references/camera-and-framing.md b/references/camera-and-framing.md
new file mode 100644
index 0000000..0768c1d
--- /dev/null
+++ b/references/camera-and-framing.md
@@ -0,0 +1,53 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Camera And Framing
+
+```js
+CAMERA = { fov: 20.5, azimuth: 45°, elevation: 33°, target: (0,-0.15,0),
+ fillX: 0.84, fillY: 0.86,
+ subjectScale: 1.0 } // 0.70 = 30% smaller, more paper
+```
+
+The distance is solved, not typed: build a direction vector from the angles,
+project each fit point (slab corners at deck and underside, plus the tallest
+building corners) into camera axes, and bisect the distance until every point's
+`|x|/(depth*tan*aspect)` and `|y|/(depth*tan)` fit inside `fillX` and
+`fillY`. 48 iterations is plenty. `fillX`/`fillY` are the **fit margin**, not the
+page-size control; tune them together, because raising one alone crops the other
+axis on a portrait phone.
+
+**Subject scale is a second, post-fit move.** Solve the fit first, then pull the
+camera back:
+
+```js
+const fit = solveDistance(aspect, points);
+const scale = CAMERA.subjectScale ?? 1;
+const distance = fit / Math.max(0.1, scale);
+camera.userData.fitDistance = fit;
+camera.userData.subjectScale = scale;
+camera.userData.distance = distance;
+```
+
+`subjectScale: 0.70` renders the diorama at 70% width/height — 30% smaller
+linearly and about 49% less screen area — so the paper margin grows. `1.0` is the
+fitted size. Keep the slab, cast, world clip, shadow camera, CSS canvas and
+frame at full size; raise the backing buffer only with `renderScale` (next
+section), never by scaling geometry. Shrinking the geometry also shrinks contact
+shadows and the clip volume; shrinking the frame/canvas changes the 1:1 crop
+and does not change the model's scale. **Move the camera.**
+
+A phone is already height-limited, so 0.70 can make the trucks unreadable. Try
+0.70, then 0.80–0.90 if needed; the scale is per scene, not a universal 30%.
+
+**Verification.** Log both distances and assert
+`actualDistance ≈ fitDistance / subjectScale` within 2%. Also project the slab
+and compare its width to the fitted width: the ratio must be the scale, not just
+the distance. On Dust Kings at 1.73 aspect: fit 67.93, scale 0.70, actual 97.05;
+projected slab width 872 → 611 px (0.70), with slab, clip and shadows unchanged.
+
+`updateCamera(camera, aspect)` on every resize and orientation change, with a
+debounced call after `orientationchange`. A canvas measured at under 2 px is a
+layout race: return early rather than dividing by zero.
+
diff --git a/references/changelog.md b/references/changelog.md
new file mode 100644
index 0000000..7a6a2c5
--- /dev/null
+++ b/references/changelog.md
@@ -0,0 +1,176 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Changelog
+
+- **5.2.0 — Pose-aware clearance.** Adds actor/animal/building space reservation, seat frames/occupancy and action-path checks to both profiles. Ships sphere/capsule/OBB nearby-pair sampled audits with exact time-window contact rules and independent proxy inventory, plus live CPU skin/morph pose bounds. Regressions cover limbs/tails, seats/backrests, buildings, temporal crossings and missing/invalid coverage. Proxy/sample limits remain explicit; full guide, model-first sourcing and narrative no-education-UI preserved.
+- **5.1.0 — Model-first by default.** Requires finding, acquiring and using fitting commercially modifiable/redistributable internet assets for major roles, not merely logging a search. Retains Polyfork-first narrative sourcing and educational accuracy gates; verifies actual import/style/motion and final-scene inclusion. Free-first; paid assets require approval. Hand-building is a justified gap/fallback, not the default. Preserves the full long guide and narrative no-education-UI boundary.
+- **5.0.0 — Long-form restoration.** Restores the complete 3.18 guide and detailed design sheet after compact-profile educational UI leaked into ordinary scenes. Narrative by default; no educational card/dock/lessons/callouts without explicit explanatory intent. Keeps Polyfork sourcing, commercial/adaptation/redistribution checks, actual-subject representation and tested construction helpers. Profile-consumer tests are bounded evidence, not a rendered amusement-park benchmark.
+- **4.6.0** — Actual named subject is the educational default, not a substitute tabletop teaching aid. Explicit real-subject/teaching-model/explanatory modes, ambiguity-only clarification, representation metadata and preservation on repair. Keeps style, scene/object presentation and Inside separate; natural subjects do not acquire invented stands/slabs/mechanical rigs. Semantic decision fixtures and instruction consistency are bounded checks, not a completed scene benchmark. Commercial asset sourcing and Polyfork narrative rules retained.
+- **4.5.0** — Educational builds may use a verified external named object or subsystem, not only context. Adds a bounded three-candidate discovery/accuracy/import wrapper and recorded-evidence policy gate: free commercial adaptation and scene redistribution required, offline bundling/dependencies checked, CC0/CC-BY auto-accepted only with reviewed source evidence and appropriate notices. NC/ND/editorial/unknown permissions fail closed; SA/custom/public-domain/other permissive terms require compatibility review, not false relabelling. Separates rights from teaching/exterior/context readiness; preserves the user's narrative Polyfork sweep. Does not assert automated legal/scientific verification or a real-asset import benchmark.
+- **4.4.0** — Narrative scenes now source the world instead of inventing it: the Polyfork catalogue is swept across every noun before modelling, with a recorded per-noun decision (`sweep.md`), one full metadata enumeration, four query shapes per noun, kit adoption for places, `matching` fan-out, and correct reading of `coverage` (`none`/`poor` versus `filtered_out`). Educational builds keep the opposite rule — the named object is authored; borrowed geometry stays context. Hand-modelling is now the answer for what the sweep proves absent, or what must be selected, moved or explained.
+- **4.3.0** — Adds one routed reference for borrowing context models from the free Polyfork CDN (`external-models.md`): ~2,800 low-poly assets, anonymous hotlink, real metres, origin at y=0, +Z front, flat-shaded vertex colours on one material, GLB or ES module. Covers discovery via `/api/assets` and kit co-location, import-map and `preserveDrawingBuffer` traps, palette retinting under the pixel and toon presets, one recorded uniform scale factor, and merging only unselectable dressing. The named teaching object is still authored, never borrowed. No new audit requirement; entry stays under 14 KB.
+- **4.2.0** — Generalizes the verified carousel mount repair into reserved local working volumes, shared support→fixture contact stacks and all-instance within-assembly checks. Adds a compact dependency-injected interface helper for actual-geometry bounds, bounded box seating, conservative keep-outs, exact scope membership, live local anchors and projected clipping. Its regression suite includes real failing geometry mutations; source integration checks the repaired eight-station carousel and parent relocation. Keeps the entry below 14 KB and the design sheet below 2 KB; adds no mandatory all-pairs solver or screenshot quota. Full-model quality/token savings remain unbenchmarked on the requested weak model.
+- **4.1.0** — Performance/quality correction after the user-run rotary-filler evaluation. Small construction-first milestones, coherent reference-grounded ground/floor/interior/material realism, separate physical/selection registries, reuse of executable base/endpoints/real-hole/perspective-fit constructors, early hero/reverse/phone checks, one parameterized QA runner, two-failed-fix design-reset trigger and unchanged production-validator mutations. All-pairs nested AABB audits become optional, not a count-optimization loop. Source audit found actual misplaced repeated details, bearing gap, incompatible gear pitches, invalid narrow predicates and missing-evidence adjudication. Executable helper and saved-artifact framing tests are bounded evidence; the revised full scene has not been rerun on the requested weak model, and no token/runtime savings are claimed as measured.
+- **4.0.0 (staged; not installed)** — Split the 231,721-byte 3.18 monolith into a routed entry and 38 mapped specialist sections; compact design sheet, rigid scene-contract helper, local-anchor/ownership guidance. Fresh-agent planning and helper tests passed, but the user-run full rotary build exposed excessive audit ceremony and poor visual results. Preserved as a staged backup, not counted as a successful scene benchmark.
+
+- **3.18.0** — Consolidates educational UI/selection/lesson rules into one V8-exact
+ authority with crossrefs; resolves placement, focus, preset-intro, ghost-shell
+ and reciprocal scale contradictions. Three quartz-watch evidence/test contracts:
+ all repeated mating interfaces from shared anchors/axes with real holes and
+ noncoplanar ends; assembly/piece inspection with class-safe reversible state;
+ non-vacuous actual-geometry QA and fresh build identity. Ships rigid inspection
+ and shared-interface helpers with class/ownership/empty-fixture failures and a
+ three-preset rendered contrast/depth/restoration regression; preserves context
+ and authorizes internal occluder removal explicitly. These tests are bounded
+ helper evidence, not full mechanism/UI certification.
+ Missing straps/back remain the existing 3.17 completeness gates, not new rules.
+ Full 3.17.0 preserved as `SKILL.md.bak-v3.17.0`.
+
+- **3.17.0** — Three whole-object completeness gates prompted by the user-reported quartz watch missing straps and back: whole silhouette/scope, exterior/rear attachment construction, and a reconciled completeness matrix with proof and negative checks. Extends the Detail Bar and design template across profiles/presets; preserves prior UI, mechanics and style contracts. Per-scene checks remain required; no model certification is claimed.
+
+- **3.16.0** — Code-defined V8 educational UI contract and copy-in `education-v8.css`: exact neutral tokens, reserved 360px right column/mobile dock, DOM/control hierarchy and measured regression gates. Records grandfather-clock beige/glass/detached-title drift; supersedes ambiguous default-placement wording without changing render presets or mechanics.
+
+- **3.15.0** — LEAP-1B repair checklist: retained preset provenance, closed exterior/explicit Inside/reset lifecycle, UI-safe complete-assembly fit with correct camera-axis sign, and reference-first white compact educational UI. Adds design fields and scoped white-stage CSS. Tests remain per-scene; geometry sampling does not imply full collision certification. v3.14.1 preserved as backup.
+
+- **3.14.1** — Documents the calibrated V8 soft-glow/holographic inspection implementation: isolated material variants, ghost-shell depth policy, selective live-transform feature edges, multi-material restoration, ownership/disposal, and rigid-versus-deformed limitations. Adds matching design/QA acceptance fields; no renderer preset or scene behaviour changed. v3.14.0 preserved as `SKILL.md.bak-v3.14.0`.
+
+- **3.14.0** — Three evidence-backed regression rules: mating interfaces/local axes/shared anchors with bore/bevel/axial budgets and connected ports/supports; full-assembly swept-clearance coverage with surface-scoped intended-contact policy and explicit sampled-proof limits; compact neutral sans educational UI with progressive causal steps bound to frozen scene state. Adds dependency-free mechanism-contract and education-dock templates, scalar/contact-policy and browser helper regressions, design/QA sheets. V8 rod repair and the incomplete earlier 12/12 report are the evidence, not a guarantee of future bug-free construction. v3.13.0 preserved as `SKILL.md.bak-v3.13.0`.
+
+- **3.13.0** — Mandatory `Render Preset Gate`: the agent asks once, at project
+ start, which of the three looks to build in (pixel default, stroked-toon,
+ pixel + stroke hybrid), instead of asking only once it had already decided to
+ try the optional look. An explicit style in the request counts as the answer;
+ naming a look in a reference, or the word "toon" on its own, does not; silence
+ resolves to pixel and is recorded as a delegated default. The grey blockout and
+ the research lookups continue while the answer is pending and only the
+ presentation pass waits. Updates the frontmatter description, the intro,
+ `One Prompt, One Build`, `Step 0`, both preset sections, the pipeline and
+ `templates/DESIGN.md`. v3.12.0 preserved as `SKILL.md.bak-v3.12.0`.
+
+- **3.12.0** — Motion graphics hardened by a full-cycle, frame-by-frame audit of
+ the four-stroke engine: effects are derived from the moving free volume instead
+ of a spline that pierced the valve; the direction-dependent cone extent is
+ fitted rather than only the centre; anchors, length normalization, single-row
+ chevrons and flame-coupled fade are specified; ignition flash is capped; and
+ every Y constant is declared in one local space. Adds the 720° vertex
+ containment sweep, the adjacent-degree no-teleport bound and the 15°-step
+ contact-sheet gate, plus nine new recorded failure modes. v3.11.0 preserved as
+ backup.
+
+- **3.11.0** — Motion-graphics primitives recorded as first-class geometry:
+ forward-axis/tip convention tests, no arrows inside opaque bodies and no
+ depth-test x-ray, minimum legible effect scale, free-volume sizing with a
+ sign check, compact ignition kernels, one-idea arrows, un-outlined FX,
+ phase-bound deterministic lifetimes, connected hollow outlets, real bores
+ through crossed flanges, and reversible selection glow/dim/focus. Adds the
+ ten recorded failure modes from the four-stroke engine. v3.10.0 preserved as
+ backup.
+
+- **3.10.0** — Mandatory user orbit for every preset with deterministic hero reset, no auto-spin; first-class educational mechanism profile, single accessible dock and one live part explanation; component manifest and ratio/kinematic/contact acceptance; optional confirmed low-resolution pixel+stroke helper with one selective outline pipeline. v3.9.0 preserved exclusively as backup.
+
+- **3.9.0** — Optional subject-independent `stroked-toon` illustrated-miniature
+ preset, calibrated from the coffee-rig repairs: explicit ask-and-wait gate,
+ native antialiasing, four-step toon ramp, selective warm ink outlines, bevelled
+ assemblies, sound cavity/contact construction and related prop clusters.
+ Pixel remains the default. Documents overrides to conflicting pixel-only
+ camera/post/empty-paper rules, adds `templates/stroked-toon.js` and design-sheet
+ consent/preset fields. Checks: material/ramp tests, module bundle, unrelated-
+ subject spec review; renderer appearance still needs per-project visual QA.
+- **3.8.0** — `qa/frames.mjs`: a per-entity frame recorder. Samples one dense
+ series per entity across a window, isolates it (branch, siblings or full
+ scene), fits one camera to its swept bounds so travel stays visible, and scores
+ every entity: `energy` (flat means frozen), `step` (NDC jump means teleport),
+ `empty` frames, `OFFSCREEN`, with `STATIC=` for actors meant to hold still. Each
+ entity gets a contact sheet plus a row in `report.json`, and the script exits
+ non-zero on any flag. New `Per-entity frame recording` section in Verification.
+ New `Long builds and context` section: compaction is lossy, so state lives in
+ `DESIGN.md`, `SOURCES.md`, `CREDITS.md`, `report.json` and the beat table, and a
+ post-compact agent re-runs the harness instead of trusting its summary.
+- **3.7.0** — Research-first release, from the Pikachu vs Charizard battle
+ diorama. New `Research Before You Model` section: step the source footage into
+ contact sheets and write the motion grammar down before modelling, prefer
+ game footage over fan cuts, and check free commercial-use libraries (Poly
+ Pizza, Sketchfab CC0/CC-BY, Quaternius, Kenney, user-supplied AI meshes) before
+ hand-modelling a creature; `CREDITS.md` + licence gate + `fitModel` pipeline +
+ forward-axis probing; shots-as-acceptance-test. New `Field Notes: Two-Creature
+ Combat` section: stage-local aiming with a numeric facing sweep, bone-space
+ effect anchors, upright billboard basis, explosion vocabulary (no cones/bars/
+ scaffolding, per-layer scaling, one continuous stream), latching effect anchors
+ to the impact point, send-out vs recall grammar (throw → arc → open → burst →
+ full-size exit → ball returns; red beam only on recall), and severity-scaled
+ hit reactions about the blow axis. Project layout gains `refs/` and
+ `CREDITS.md`.
+- **3.6.0** — Renamed to Diorama throughout: the playbook, templates and QA docs
+ now call the artifact a diorama. No code behaviour changed.
+- **3.5.1** — Camera-scale rule made explicit: `subjectScale` is a post-fit
+ multiplier (`0.70` = 30% smaller linearly), while `fillX`/`fillY` stay a fit
+ margin. The camera template now exposes `fitDistance` and `subjectScale`;
+ `qa/audit.mjs` now proves `distance ≈ fitDistance / subjectScale` when those
+ two fields are exposed, and `post.size ≈ CSS × renderScale` when the post
+ exposes it. Added the
+ Dust Kings calibration (fit 67.93 → actual 97.05, projected slab 872 → 611 px)
+ and a rule against shrinking the geometry or canvas frame to create margin.
+ `PixelPost` gains a `renderScale` argument; Dust Kings renders at 1.25× (buffer
+ 1640 × 950 on a 1312 × 760 CSS canvas) so the smaller diorama keeps its edge
+ detail without changing page size. The resolution section now separates buffer
+ from layout and warns about the frame-rate cost.
+- **3.5.0** — Surface/Motion/Event-FX correction release from a truck-diorama
+ postmortem: finish heightfield/slab edges flush (no lip or portal), keep every
+ exiting mover visible until its world bounds clear the slab, never fade a solid
+ hero with material opacity, gate exhaust/steam/dust by authored event windows
+ with the emitter at the physical nozzle, and replace flat untextured halo
+ quads with radial-alpha sprites. New `qa/audit.mjs` checks flat glows,
+ whole-group fades, early hides, teleports, idle/orphan emitters and paper-margin
+ leaks; `shoot`, `portrait`, `sweep` and `strip` now fail with a nonzero exit
+ code; QA README documents the optional audit contract. New DESIGN audit sheet;
+ `detail.js` gains `haloPlane`/`softDiscTexture` so a soft light card is the
+ default.
+- **3.4.0** — The fragile code is now shipped, not described: `poses.js`,
+ `transfer.js` (climb, stand spots, facing), `track.js` and a `stage.js`
+ skeleton with a worked actor chain; `qa/` as runnable scripts (shoot, portrait,
+ strip, probe, sweep) instead of a checklist; Numbers split into invariants and
+ calibrated values. Water, wake and splash re-verified in `verify/water/`, which
+ found two real defects: the splash used `Math.random` (now seeded) and neither
+ effect could be frozen (both now expose `reset()`; the harness re-simulates from
+ zero and a two-frame diff fell from 334 to 18 pixels). `build.mjs` writes a
+ favicon stub so the 404 stops polluting the console gate.
+- **3.3.0** — Social/life-scene release from the Night Market build: clothed-cast
+ craft (skull/jaw head, hairline, layered garments, hands), carry/handoff and
+ crate-loading rules, scooter/cargo-bike anatomy, two-wheeler mount with hip-Z
+ abduction, service/queue state machine with `moving` gates, Night Market worked
+ example and fix table, 2x backing/scale-by-camera guidance, empty-paper rule,
+ social verification logs, night/practical/headlight guidance, cutaway and
+ glazing rules, bus/van anatomy, cat/dog quadruped rig and gait, generalised
+ `DESIGN.md` with Life/Service and Contact/Choreography sheets, new
+ `peopleModel-street.js` template, scene fast path, and a laundromat/workshop
+ router row.
+- **3.2.3** — Hollow-object rule: cannon bores, pipe mouths, chimney flues, lamp
+ chimneys and tunnels need open collars, a recessed dark bore, a back disc and
+ a lip ring. Added 1:1 bore audit and the brass-end-cap pitfall; the Bombard
+ cannon now has an open muzzle instead of a cap.
+- **3.2.2** — Fixed cannon ammo station rebuilt as a wall-mounted locker below
+ the deck: shelf, brackets, powder chest, shot tray and hung rammer, outside
+ both yaw sweep and barrel arc. Added bounding-box overlap check to the pivot
+ audit and recorded the wall-locker pattern.
+- **3.2.1** — Rotating-assembly parentage rule: only the gun may live under yaw;
+ fixed deck stores go on a static group. Added pivot-parentage strip and
+ acceptance check; cannon keg, shot and rammer moved off the yaw group.
+- **3.2.0** — One-prompt commission mode: default commission table, assumption
+ line, ten-scene router, universal four-question generator, bakery worked
+ example, autonomous eight-pass build, cut-count-not-detail rule and
+ one-prompt acceptance; reading order trimmed to the sections needed.
+- **3.1.0** — Canonical numbers/camera/light/post/palette contract; field and
+ machine grammar; goal-response vocabulary; FX edge, snap and contact-context
+ rules; crew/defender rule; human death grammar; climb and rotating-emitter
+ rules; expanded `DESIGN.md`; new `detail.js` rope, trophy-board and
+ contact-shadow helpers.
+- **3.0.0** — Detail Bar, Animation Bar, new-subject intake, reference density,
+ detail recipes, system/combat animation, attack/death audits, beam/artifact
+ triage, detail-and-animation QA, `templates/DESIGN.md`, `templates/detail.js`,
+ `templates/combat.js`.
+- **2.1.0** — Combat Readability section; threshold clearing, tower grammar,
+ boss goal contact, death species, standalone `String.replace` guard.
+- **2.0.0** — Palette/post contract, camera solve, cast rig, vehicle/seat
+ transfers, clipping, verification.
diff --git a/references/combat-readability-towers-bosses-deaths.md b/references/combat-readability-towers-bosses-deaths.md
new file mode 100644
index 0000000..4978144
--- /dev/null
+++ b/references/combat-readability-towers-bosses-deaths.md
@@ -0,0 +1,147 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Combat Readability (towers, bosses, deaths)
+
+A diorama is judged on whether the **cause and the consequence are both
+visible at the reset hero camera**. Geometry that is correct in world space can
+still read as a bug on screen. Run these gates before calling a combat beat
+finished.
+
+- **Clear the threshold.** Keep at least 2 m of empty ground in front of a
+ portal mouth, gate, or spawn arch. No crates, barrels, boulders, bones, or
+ hanging vines in that pocket. Remove fireflies over the mouth, and never put
+ rising smoke there: a grey billboard above an arch reads as a rock flying out
+ of the entrance, even when it is soft and transparent.
+- **Give every tower a legible grammar.** Origin flare, a readable travel or
+ channel, and an impact that lands on the target. A beam needs contrast against
+ both the tower body and the page (there is no sky), plus motion along its
+ length; a plain white
+ cylinder over a white tower reads as a waterfall or a static icicle. Use a
+ scrolling band texture, a darker halo, and a target flash. If the line of
+ sight is blocked by the keep, a foreground tower, or a ruin, pick another
+ target instead of drawing through the wall.
+- **A beam that fires at a dead target is a bug.** Store the target id on every
+ beam event and hide the beam on the frame its target dies.
+- **A boss with a goal must act on the goal.** Stop it outside the threshold by
+ at least its body depth plus weapon reach, face the door, and make the weapon
+ visibly contact the door. Position alone is not enough: sync the contact pose
+ to the door-hit timestamp (a decaying pulse from the simulation), so the
+ club/ram/fist is low on the same frame the door flashes, shakes, and cracks.
+ If the weapon is off-screen, through the wall, or on the ground at the hit
+ frame, the beat is not finished.
+- **Do not let an attack hide the story.** A boss at the gate and a tower beam
+ arriving at the same spot fight for the same pixels. Let the tower lose line
+ of sight to the gate pocket, or dim/shorten the beam there; the door beat
+ wins. The player can see the beam elsewhere in the loop.
+- **Deaths need a species, not an explosion.** No generic sphere, boulder, or
+ rock burst on death. Use a body-specific collapse plus two or three
+ type-coloured shards or cloth/armour/goo/feather pieces, a dropped weapon
+ where the species carries one, a ground stain or splat, and a brief soul
+ flicker. Cannon and mortar impacts land in dust and smoke with a ring, never
+ in stone chunks. If a death reads as "grey puff", it is not done.
+- **A stone weapon is not a floating rock.** A club, maul, or ram needs a
+ visible haft connecting it to the hand, iron bands, studs, or spikes, and a
+ colour that separates it from the wall it hits. Check the impact crop: if the
+ head looks detached, add the haft/band contrast, not more debris.
+- **Prove the beat with time, not a still.** Shoot the impact frame and the
+ frame 0.2 s later. The first must show contact and the flash; the second must
+ show recoil or follow-through. If the club is hidden at impact and only
+ appears on the recoil, the pose is late.
+- **Sync effects by timestamp.** Gate hits, door cracks, beam impacts, and
+ death pulses must derive from the same simulated event time. Two independent
+ cycles will drift apart on a long loop even if they match on the frame you
+ happened to inspect.
+
+### Attack Audit
+
+Run one row per tower, at the timestamp it fires. A tower that never fires in
+the loop is scenery, not a defence.
+
+| Check | Pass condition |
+| --- | --- |
+| origin | muzzle, rail, crystal or hand is visible and offset from the body |
+| wind-up | at least 0.1 s of visible anticipation |
+| travel | projectile or beam is traceable across at least 4 frames |
+| impact | lands on the target with a species-specific effect |
+| recovery | weapon returns; crew resets; no snap to rest |
+| count | `shots > 0` in the sim stats for this tower |
+| no stale | no projectile or beam outlives its target |
+
+If a tower fails "origin", move the spawn point; adding more impact particles
+will not fix it. If it fails "travel", slow the projectile or widen the trail;
+a 1-frame hit is a hitscan, which is fine only for a beam.
+
+### Field Audit
+
+A **support, aura or ground field** has no projectile and must not be failed for
+that. Audit it on five field stages instead:
+
+| Check | Pass condition |
+| --- | --- |
+| source | emitter, valve, horn mouth or caster hand is visible |
+| area | radius/cone is readable on the deck; no floating ring |
+| ramp | effect grows over at least 0.15 s; not an instant decal |
+| affect | affected units visibly change (speed, colour, stagger, burn) |
+| decay | effect fades/expires on the loop, leaving residue |
+| count | `events > 0` for this field in the sim stats |
+
+A field that never expires is a lighting change, not an attack.
+
+### Death Grammar
+
+| Species | Body collapse | Debris | Dropped | Residue |
+| --- | --- | --- | --- | --- |
+| goblin | fold forward, knees first | cloth scraps, 2 bone chips | knife or spear | dark stain |
+| orc | drop to one knee, then side | 3 iron plates, 2 tusk chips | cleaver or sword | dust + blood |
+| slime | flatten, then pop | 6 goo blobs, 1 core | none | glossy splat |
+| flyer | spiral, wings fold | 5 feathers, 1 bone | none | feather on ground |
+| human / crew | knees, then hat/coat fold | 3 cloth scraps, 1 tool | hat, keys or hook | oil or blood stain |
+| boss | knee dip, torso fall, weapon drop | 6 armour plates, 2 horns | club | scorch + rubble |
+
+Every death also gets a 0.2 to 0.4 s additive soul flicker. It is the punctuation
+that says "this was a creature", not "this was a particle system".
+
+### Beam And Impact Artifacts
+
+- **A black band along a beam is a texture backing, not a shadow.** A canvas
+ filled with black and then painted with white stripes still carries black RGB
+ with alpha 1; under a render target it can survive as a dark segment. Clear the
+ canvas and paint pale stripes with transparent gaps. Never use a black
+ background for an additive beam texture.
+- **A beam that looks like a waterfall** is a white cylinder against a white
+ tower. Add a darker halo, a scrolling band texture, an origin flare and a
+ target flash. The eye needs motion along the length and contrast at both ends.
+- **A beam through a wall** is a line-of-sight bug. Sample the keep/foreground
+ silhouette and drop the target if the segment crosses it; do not shorten the
+ beam after it has already drawn through the wall.
+- **A beam on a corpse** is a stale target. Store `targetId` on the beam event
+ and hide the beam on the frame that id dies.
+- **Dark smoke over a bright beam** reads as a black bite. Smoke is normal-alpha
+ grey; if it crosses a beam, lighten it, move it out of the beam corridor, or
+ draw the beam after the smoke. Do not assume additive blending saves it.
+- **A projectile that looks like a floating rock** has no trail and no muzzle.
+ Spawn it at the weapon, add a tumble or trail, and remove it on impact.
+- **A muzzle flash with no recoil** reads as a sticker. Move the weapon back
+ 0.1 to 0.25 m and return it over 0.2 to 0.5 s.
+
+### Prop And Landmark Failures
+
+- **Two landmarks with one silhouette.** A skull tree behind a skull totem
+ becomes one antlered monster; a cart beside a crate becomes a pile. Remove or
+ move one. Project both to screen and check the union.
+- **A trophy that floats.** Mount it on a board, plaque or branch with a visible
+ rope, strap or nails. A skull in mid-air is a rock with eye sockets.
+- **Loose skulls at the base read as white pebbles.** At diorama scale, a 0.1 m
+ sphere with two dots is not a skull. Remove it or make it a clear bone pile
+ with a jaw and horns.
+- **A cart load made of pale spheres reads as a blob.** Use tied rectangular
+ bales, straw tufts, a pitchfork and a sack. The load must have a construction
+ logic, not just a colour.
+- **Rising smoke over a threshold reads as rocks flying out.** Remove it from
+ the pocket. Fire can glow without a smoke column.
+- **A prop at the slab edge with its wheel or shaft over the void** breaks the
+ cut-out. Move it in until the lowest contact and the full silhouette are on
+ the deck.
+
diff --git a/references/construction-regression-gates.md b/references/construction-regression-gates.md
new file mode 100644
index 0000000..09bcdda
--- /dev/null
+++ b/references/construction-regression-gates.md
@@ -0,0 +1,37 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Construction regression gates
+
+These construction rules apply across subjects and all render presets; they supplement, not replace, the style gate and profile-aware verification above. They make known failures testable, not impossible.
+
+1. **Specify the mating interface before decorating the part.** Extend the component manifest with units, parent-local frame, shaft/bore/slide axes, shared joint/port anchor IDs, mating surfaces, nominal dimensions and radial/axial tolerances. Derive both mating meshes and their motion from those anchors, not repeated guessed offsets. A bearing eye needs a real through-bore; its beam, cap, bolt and bevel must stop outside that bore. Budget bevel/fillet intrusion in the actual construction method (inward bevels reduce usable bore), axial lane widths, spacers, end float and end stops. Check coaxial alignment and anchor residual after parent transforms. Model the load path through real bearings, brackets, fasteners and a base; route each functional port through an actual connected opening to its destination, not a hose ending inside a solid. Document symbolic/omitted internals. **Evidence:** V8 running-gear repair found a centred rod beam cutting its crankpin despite an annular eye, bank stagger applied to only one mating member, and fillets facing the wrong local axis. **Test:** local-axis/anchor tests, measured bore plus bevel allowance and axial stack tests, section crops from two orbit directions, and traced port/support connections. Record geometry revision and proof frames in the manifest. Copy `templates/mechanism-contract.mjs` and fill the interface and connection sheets in `templates/DESIGN.md`; the helper validates scalar budgets, not arbitrary mesh bores or load strength.
+
+2. **Audit the complete swept assembly, with narrowly scoped intended contact.** Derive every driven pose from one driver and test the actual transformed meshes or documented conservative collision proxies, including beams, caps, fasteners, webs, fillets and supports. Broad-phase boxes alone neither detect holes correctly nor prove clearance. Enumerate potentially interacting pairs and coverage; whitelist only a named pair of mating surfaces with phase window, normal-gap/penetration tolerance and rationale (bearing/journal, meshing teeth, valve/seat), never an entire assembly or all pairs of a part type. All other pairs need the declared positive clearance. Check full travel, extrema, cycle seam, contact transitions and close-approach intervals with refinement; include ports/FX containment. Report method, sample spacing, tolerance, worst phase/pair, exclusions and unresolved regions. Dense sampled vertex/triangle tests are bounded evidence, not continuous exact collision proof: use analytic bounds or conservative continuous checks where available, otherwise retain that limitation explicitly and block unsupported clearance claims. **Evidence:** the V8 12/12 invariant report omitted rod/crank interference; the later rod probe added bore triangle samples, axial lanes, journal vertices, anchor residual and fillet axes. **Test:** intentionally inject a beam-through-bore, wrong-axis fillet, too-wide lane, out-of-window contact and a non-whitelisted overlap; each must fail. Run full-cycle probes plus before/contact/after crops from two angles. `templates/qa/mechanism-contract.test.mjs` tests budget/contact-policy failure detection only; per-scene geometry/sweep checks remain mandatory and UNVERIFIED until run.
+
+3. **Repeated interfaces share anchors and axes (3.18 evidence + test).**
+ Generate ALL repeated mating members from one anchor/axis table, not just the
+ first working example. Quartz-watch pads at radius 12.6 missed posts at 13;
+ rotating a native CylinderGeometry about Y did not redirect its native Y axis.
+ The seconds shaft opposed its hand and the model lacked a physical 60:1 stage.
+ Coplanar shaft-cap fans z-fought. Use transformed local axes (quaternion maps
+ native Y to the declared axis), common anchors, real through-bores and a single
+ end surface or measured axial separation; never hide coplanar caps with depth
+ overrides. Derive ratio/direction from the actual connected transmission, not
+ only a display hand formula. **Test:** with `templates/mechanism-contract.mjs`
+ shared anchors/checkRepeatedInterfaces/checkEndPlanes, enumerate every pad,
+ post, bore, cap and shaft; assert count, transformed axis/anchor residual,
+ radial/axial clearance and physical ratio/direction across the full cycle.
+ The repaired watch measured zero residual at all four pad anchors and 0.08
+ board-bore radial clearance; those are historical measurements, not defaults.
+ Inject one displaced repeat, wrong native axis, sealed bore, reversed shaft,
+ missing reduction and coplanar cap; each relevant check must fail. Review
+ section/end-on and oblique crops; scalars cannot prove real mesh openings.
+ Evidence: the historical construction report and highlight shots above.
+
+Lesson/UI behavior and its tests are defined once in `Canonical educational UI
+and inspection contract`. `templates/education-dock.mjs` remains a dependency-free
+state helper with `templates/qa/education-dock.test.mjs`; its older CSS is not the
+V8 visual authority.
+
diff --git a/references/design-extended.md b/references/design-extended.md
new file mode 100644
index 0000000..0308321
--- /dev/null
+++ b/references/design-extended.md
@@ -0,0 +1,366 @@
+# <TITLE> — design sheet
+
+> Fill this before modelling. Keep it in sync with `README.md` and the code.
+> Narrative scenes need a verb/conflict; educational scenes need one causal mechanism, not cast/ritual quotas.
+> Delete rows that do not apply, but replace them with the equivalent
+> (a machine's goal, a field's area, an ambient loop's period).
+
+## Profile and hard acceptance
+
+- `sceneProfile`: narrative OR educational:
+- Educational: one mechanism causal sequence and short input → change → output explanation:
+- Educational UI: canonical V8 `templates/education-v8.css` + skill DOM contract; ONE reserved 360px right card / bottom dock at <=880px (explicit placement request may override); neutral tokens independent of subject/render preset:
+- Manifest artifact: essential part IDs, parent/support/joint, function/connections, mesh mapping, selection anchor, source, tolerance, proof frame:
+- Declared omissions/symbolic simplifications (unexplained essential omissions fail):
+- Actual drive ratios / phase / units / kinematic equations / contact and clearance invariants:
+- Numeric test command, dense samples + boundaries, results and tolerances:
+- Frozen repeatability / hero desktop + phone / back + high orbit / motion-strip proof:
+- Live local-geometry label anchor → world projection and opaque occlusion checks / nearest visible ray hit / one label at a time:
+- Hidden-part picker: stable assembly ID versus mesh-piece ID/mapping, keyboard access to each intended target, useful revealed view or explicit authored cutaway; no see-through click or disabled depth test:
+- Selection: selected part soft glow + OTHER parts darken, per-mesh shared/multi-material isolation; restore exact material identities/array slots, visibility and cast/receive shadows, dispose owned clones; MeshBasicMaterial receives no added emissive properties:
+- Inspection effect: highlight/dim/ghost settings, declared internal/shell IDs; see skill “Soft glow and holographic inspection — implementation recipe”:
+- Hologram feature-edge threshold/scale filters and decal-edge exclusions, live rigid/deformed/instance transform strategy; authored blocker/reveal plan per hidden target, preserved depth/opaque occlusion, picker exclusion and owned resource cleanup:
+- Glow/hologram proof: per-part desktop/phone before/selected/restored screenshots with measured contrast and occlusion verdicts (emissive > 0 alone never passes an invisible highlight); shared/multi-material exact restore, moving source agreement, Inside-state preservation and rapid reselection without edge/resource growth:
+- Short selection-triggered camera+target focus / fit bounds and panel clearance / previous-view Back + hero Reset:
+- Cancel focus tween on user orbit/pointer/keyboard / no clock-driven chase / reduced-motion immediate view:
+- Acceptance captures: before, selected, restored; rapid reselection; hidden menu selection at multiple frozen phases; Back/Reset and interruption mid-transition:
+- Keyboard focus, dock picker, drag vs click, multitouch cancel, reset proof:
+- Profile/preset checks applied or replaced, reason; UNVERIFIED checks cannot pass:
+- For educational mode delete inapplicable cast, service, multiple-system and ritual sheets below; do not fabricate roles to fill them.
+
+## Premise
+
+`[place]` + `[a repeated verb/ritual]` + `[who or what interrupts it]` + `[payoff]`.
+
+One sentence:
+
+- Archetype (router row):
+- Assumption line (scale, loop, systems, cast):
+
+## Render Preset and Style Confirmation
+
+- Existing repair: original recorded preset/provenance (retain without re-asking), or explicitly requested style change:
+- Gate asked at project start, before the first mesh (SKILL.md `Render Preset Gate`)?:
+- Preset: `pixel` (default) | `stroked-toon` | `pixel-stroke`:
+- User's answer for this build (quote it; never inferred from a reference or from the word "toon"):
+- Explicit style in the request / delegated default ("you pick") / no answer -> pixel:
+- If delegated or unanswered: why pixel was kept, and that no later switch may happen without a new answer:
+- Colour family / accent (subject-specific, cream is not mandatory):
+- Paper/background / grain / optional figure frame and accessible UI:
+- Contour width at desktop and phone / no-outline materials and cavities:
+- Camera: mandatory free user orbit + hero reset for EVERY preset, no auto-spin:
+- Render path: PixelPost OR native toon OutlineEffect OR low-res hybrid toon OutlineEffect + nearest upscale; never double edges:
+- Shared QA / preset-specific checks / intentionally replaced pixel assertions:
+- Hero construction, attachments, functional connections and related prop clusters:
+
+## Educational UI fidelity (3.16)
+
+- Copied canonical CSS; exact neutral token/computed-style measurements and any user-authorized deviations:
+- One in-card title, Explore default, About closed, no beige/glass/detached masthead/full-height panel:
+- Stage measured separately from card/dock; desktop 1280×800, phone 390×844 and 320×640, 200% zoom proof:
+- Style regression command/results; injected beige/title/full-height failures; missing checks UNVERIFIED:
+- Keyboard tabs/steps/picker, synchronous freeze/text agreement and selected/restored captures:
+
+## Camera Side
+
+- Pixel reset hero angle: azimuth 45, elevation 33, fov 20.5; fillX/fillY 0.84–0.94
+ (fit margin only). Approved toon starting point: azimuth 38, elevation 27.5,
+ fov 26; record final fit/angle and mandatory orbit bounds and reset controls:
+- Subject scale: 1.0; 0.70 = 30% smaller linearly, more paper (camera only;
+ frame, slab, clip and shadows unchanged):
+- Closed exterior cold-load/Reset; explicit Inside control and lesson-exit restoration (or commissioned permanent-section exception):
+- Complete swept fit bounds / measured canvas-safe rectangle / protrusion test / desktop-phone-200% zoom proof:
+- Page, renderer, scene and ground/post white-background consistency / empty-corner pixel proof:
+- Exterior or interior cutaway:
+- Street lane (in front +Z / behind -Z; passing vehicle timing):
+- Night palette mix (moon/key / practical / pool):
+- Pixel render buffer: 1× CSS default; 1.2–1.5× renderScale for a small subject;
+ 2× only for face close-ups; maxDim / CSS image-rendering. Approved toon:
+ antialias + native DPR capped at 2, no pixelated CSS; measured fps:
+- Slab size / deck height:
+- +Z face / hero face (exterior); for an interior cutaway, camera-side wall
+ omitted and street behind at -Z:
+- Threshold / entrance (keep 2 m clear):
+- Tall landmark (back, offset in screen x; top height):
+- Foreground prop (near corner):
+- Mid-ground prop (leads the eye):
+- What must never be occluded:
+- Grey blockout frame (time):
+
+## Cast Sheet
+
+Three to eight rows; the default is four to six including any disruption. Every
+row needs an exit (or death) and a signature prop.
+
+| Role | Silhouette feature | Locomotion | Action | Reaction | Exit / death | Signature prop |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+
+## Life / Service Sheet
+
+Fill this for a market, hatch, ticket window, bakery, hotel desk or any social
+scene. A combat play can delete it.
+
+- Service point (counter / hatch / window):
+- Queue slots (positions, spacing, heading):
+- Staff positions (cook / cashier / runner):
+- Arrival order and serve order:
+- Machine slots (washer/dryer/table), cycle end and release beat:
+- When the queue is full / empty:
+- Late customer or disruption:
+
+| Role | Entry | Slot | Order | Pay | Receive | Exit |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+
+## System Sheet
+
+- Loop length / DT:
+- Three or four systems (defence / machine / service station / loop; name,
+ origin, output, contact, events):
+- Crew / staff (who operates, exit, machine behaviour when gone):
+- Three or four visitor / enemy / animal roles:
+- One goal or disruption, optional for a life scene (what place does it act on?
+ contact point + response):
+- Economy / score / progression (optional for a life scene):
+- What changes between first and last beat:
+
+### Shot / Event Count
+
+| System | Shots / events | First at | Last at | Proof frame |
+| --- | --- | --- | --- | --- |
+| | | | | |
+| | | | | |
+| | | | | |
+
+## Beat Sheet
+
+| Time | Beat | Camera proof |
+| --- | --- | --- |
+| 0.0 | establish | |
+| | first system output | |
+| | first consequence | |
+| | machine / field / service output | |
+| | disruption arrives | |
+| | goal / service contact | |
+| | finale / residue | |
+| | relight / recovery | |
+| | loop seam | |
+
+A social play may collapse this to five rows: establish, first ritual, disruption,
+handoff, residue. A combat play uses all nine.
+
+## Hero Objects
+
+Name every object that gets the Detail Bar. Type is tower / machine / service
+station / vehicle / creature / prop / landmark. "Parts" is the visible mesh count target.
+
+| Name | Type | Parts | Construction layers | Story detail | Contact |
+| --- | --- | --- | --- | --- | --- |
+| | | | | | |
+| | | | | | |
+| | | | | | |
+| | | | | | |
+| | | | | | |
+| | | | | | |
+
+## Whole-object completeness matrix (3.17)
+
+Apply the skill's three Whole-object completeness gates to every hero, including
+educational scenes. Keep this sheet even when deleting narrative-only sheets.
+
+- Commissioned scope: complete named object (default) / detached mechanism / explicit permanent section; user wording and section boundaries:
+- Whole-object front/side/rear references, proportions and explicit assumptions:
+- Grey silhouette comparison + uncropped desktop/phone proof paths and reviewed result:
+- Exterior/rear/side/high crops, attachment-seat close-ups and Inside/Reset restoration result (or not applicable with reason):
+
+One row per expected assembly, not merely per mesh already built. Cover silhouette,
+exterior/rear, attachments and functional internals; cross-reference the existing
+component manifest rather than duplicate it. For a strapped quartz wristwatch,
+consider case, dial/crystal, crown, caseback, lugs/spring bars, both strap halves,
+reference-appropriate buckle/keeper or clasp, and the functional movement. Adapt
+to the actual reference; these are not universal fittings or verified watch specs.
+
+| Hero / stable assembly ID | Coverage category | Reference / assumption | Required / simplified / omitted + scope rationale | Live mesh/group mapping | Seat/joint/connection | Proof view/path | Actual check/result |
+| --- | --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | | |
+
+- Reference-to-inventory review (including assemblies absent from the built scene):
+- Required rows reconciled with nonempty live geometry, connection checks and reviewed proof:
+- Negative checks: hidden silhouette assembly, missing rear closure/disconnected attachment, removed required mesh, blank proof and unexplained omission; commands and observed failures:
+- Explicit user-approved scope changes (an omission note alone cannot waive an essential assembly):
+- `qa/report.json` command/results/proof paths; unresolved FAIL / UNVERIFIED items (either blocks completeness pass):
+- Evidence limits: visual/presence checks do not certify mechanics; retain the existing clearance/motion gates:
+
+## Contact / Choreography Sheet
+
+Every carry, handoff, load, mount and seat needs a contact timestamp.
+
+| Beat | Hands on | Prop / seat anchor | Start | Contact | Release | Proof |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+| | | | | | | |
+
+## Ambient Loops
+
+| Loop | Period | Motion | Phase offset | What it touches |
+| --- | --- | --- | --- | --- |
+| | | | | |
+| | | | | |
+| | | | | |
+
+## Surface / Motion / FX Audit
+
+- Slab edges finished (right / lower / all visible): heightfield or road
+ feathers to slab over:
+- Exit rule for every mover: visible until world bounds clear slab + margin:
+- Event FX windows (start / rev / launch / hit / landing), source object, tail:
+- Idle effects that are deliberately allowed (otherwise "none"):
+- Large translucent planes and why each is not a flat halo:
+- Whole-object fades: none / exempted with reason:
+- `qa/audit.mjs` contract exposed (`slab`, `movers`, `emitters`):
+- Edge crop pair, burst frame, burst + 1.5 s, margin scan:
+
+## Detail Budget
+
+| Element | Count | Parts each | Story detail |
+| --- | --- | --- | --- |
+| Towers / machines / service stations | | 25–45 | |
+| Vehicles | | 20–45 | |
+| Species / people | | 12–20 (hero 40–60) | |
+| Props | | 8–15 | |
+| Landmark | | 30–60 | |
+| Deaths / exits | | 5–8 pieces + residue, or exit-only with no debris | |
+| Ambient loops | | 2+ | |
+| Triangles / draw calls | | | |
+
+## Palette / Authored Colour Family
+
+Pixel only:
+- Length (must equal `uPalette[N]` and the JS array):
+- Base entries:
+- Accent entries:
+- Forbidden: pure black, gradients, unlisted colours.
+
+Approved stroked-toon only (replace the pixel block above):
+- Named material colours / local contrast / restrained accent:
+- Four shade-ramp bytes / charcoal contour / stroke hierarchy:
+- Lighting and background gradients may survive; no final-pixel palette snap:
+- No-outline materials: cavities, glass, liquid films, decals, vapour:
+- Major/medium/microdetail budget and actual draw-call/fps measurement:
+
+## Animated Effects (arrows, flames, flow)
+
+- Local forward axis and unit test (tip at +Z, base behind, transform dot >.999):
+- Placement: genuinely open volume or a real cut window; never depthTest:false:
+- Depth test/write kept on for effect materials; outline disabled for small FX:
+- Minimum legible scale and exact hide threshold; fade-boundary tested:
+- Measured free band per frame (moving crown/valve faces), positive-gap assert:
+- No port-centreline spline; effect derived from the live free volume:
+- Fit direction-dependent full extent (|dy|*half + flat*head), not the centre:
+- Anchors: tail/tip 0.008 under the valve underside, <=92% of the band:
+- Authored length = max length, so scale <= 1 and the legibility gate is real:
+- One arrow per stroke; never two stacked rows at the same x/z:
+- Effect fades with its source (flame kernel); no orphan arrow:
+- One declared space for every Y constant (scene root lift subtracted):
+- Ignition flash caps: halo opacity <=0.55, halo scale <=0.62, light <=2.2:
+- Full tip/tail/width containment across the complete event, sample interval:
+- Adjacent-degree delta bound on position and scale (no pop/teleport):
+- 15-degree contact sheet per stroke read frame by frame, not four hero stills:
+- Flame kernel: anchor, max height/radius, clearance to crown and head:
+- One idea per primitive; fan separation >= one head-width if used:
+- Phase window per group; mid-stroke counts and zero-leak outside phases:
+- Hollow outlet: connected sleeve+lip, centre-ray open / annulus-ray hit:
+- Real bore/slot at every crossed fixed wall; crossing-plane swept test:
+- Screenshot strip: all strokes from two orbit angles (paths):
+
+## Non-Penetration Gate (all profiles and presets)
+
+- Intended contact/joint pairs, explicitly listed:
+- Non-contact pairs and required positive clearances / units:
+- Full-cycle sweep sample interval, contact-boundary samples and tolerance:
+- Actual complete surface checks (tips, tails, bevels), not centres only:
+- REAL bores/slots through every crossed fixed wall/flange; crossing-plane mesh test:
+- Piston/rod/base flange, cam/follower, head/plug or subject-equivalent checks:
+- Effect free-volume constraints relative to moving solids; depth testing on:
+- Before/contact/after proof frames from two orbit angles:
+- Exact test command, worst measured clearance and report path:
+- Failed or unrun non-penetration check = NOT ACCEPTED:
+
+## QA Frames
+
+| Frame | Time | What it proves |
+| --- | --- | --- |
+| Grey blockout | | staging before palette |
+| Hero | | staging + palette |
+| First system | | origin / travel / contact |
+| Queue approach | | slots, feet, serve order |
+| Carry / load | | palms on prop, over-rim, release |
+| Mount / seat | | boot, leg clearance, hands on grips |
+| Night / glass | | darks, practical, no tint, no occlusion |
+| Quadruped | | ears, pupils, hocks, tail |
+| Exit (social) | | turn, walk, prop, no debris |
+| Machine / field / service | | area, ramp, output |
+| Surface edge | | no lip, gap or portal; flush at 1:1 |
+| Event FX start | | burst at the source, not idle haze |
+| Event FX tail | | plume gone within the authored tail |
+| Mover clear | | whole bounds outside slab before hide |
+| Exit / death | | species or role grammar |
+| Goal contact | | contact + response |
+| Follow-through | | recoil / release |
+| Beam / field off | | no stale effect |
+| Threshold | | clear pocket |
+| Relight / aftermath | | residue and recovery |
+| Standalone | | `file://`, no errors |
+
+## Risks
+
+- What is most likely to read as a blob at 1:1?
+- Which object has the weakest silhouette?
+- Which beat has the least visible cause?
+- Which FX crosses the slab edge, and does it fade or cut?
+- Does any standing gesture overlap a walking root? (queue slide)
+- Are the palms on the carried prop at the contact frame?
+- Does a boot pass through the bars, seat or body during the mount?
+- At night, are there three dark values and a visible practical?
+- Does a passing vehicle cover the hero at the contact frame?
+
+
+## Mating interfaces, swept coverage and lesson regression (3.14)
+
+Use project units, explicit local frames and stable surface IDs; do not copy engine dimensions into another subject.
+
+| Interface ID | Parts/surfaces | Source-frame IDs / shaft and bore axes / shared repeated-mount anchor IDs (derive all instances; no separately guessed offsets) | Full shaft/bore or slide geometry + tolerances | Inward bevel/fillet allowance | Radial gap / axial lane/end float + cap endplanes/separation to prevent z-fighting | Source / proof |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+
+| Functional connection | Source port / opening | Destination port / opening | Continuous route and actual bore proof | Support / bearing / bracket / fastener / base load path | Declared simplification |
+| --- | --- | --- | --- | --- | --- |
+| | | | | | |
+
+| Tested surface pair | Full mesh or conservative proxy / exclusions | Full driver range + spacing + extrema/transitions/refinement | Required clearance / worst gap and phase | Intended contact: exact surfaces, window, tolerance, reason | Method limitation / unresolved interval | Command/result/proof crops |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+
+- Pair coverage inventory and potential-pair omissions (why safe):
+- Nonempty fixture/pair coverage and asserted expected sample counts; actual runtime geometry type (include RoundedBox-labelled geometry reporting Box as a counterexample); injected beam-through-bore, bevel overrun, wrong-axis fillet, lane overflow and non-whitelisted overlap failures:
+- Analytic/continuous bounds versus sampled evidence, explicitly distinguished:
+- Neutral sans single dock/right-panel layout, progressive disclosure and phone/zoom containment:
+
+| Causal step | Driver phase/time + units | Actual manifest part ID | Input → change → observable result | Frozen evaluator state/readout agreement | Proof |
+| --- | --- | --- | --- | --- | --- |
+| | | | | | |
+
+- Keyboard, focus visibility, touch targets, contrast, reduced motion, no focus trap and no canvas event leakage:
+- QA manifest: final build hash matched to tested geometry/artifacts, exact commands + exit outcomes, expected/actual sample counts, nonempty fixtures, negative-injection failures and proof paths; UI desktop/phone + 200% zoom, step/scrub agreement, rapid changes, pause/orbit, picker/reset and scene selection/camera/material results:
+- Unrun or failing checks (UNVERIFIED/FAIL, never implied pass):
diff --git a/references/detail-recipes.md b/references/detail-recipes.md
new file mode 100644
index 0000000..eb8daaf
--- /dev/null
+++ b/references/detail-recipes.md
@@ -0,0 +1,174 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Detail Recipes
+
+Detail is a hierarchy, not a texture. Build in this order and stop adding when
+the silhouette is explained.
+
+### The Five-Part Prop
+
+Every readable prop answers five questions with geometry:
+
+1. **What touches the ground?** Feet, skids, wheels, a stone base, roots. Add a
+ contact shadow at 0.018 above the deck.
+2. **What holds it up?** Posts, frame, legs, axle, brace. This is the
+ construction layer and it must be visible from the camera.
+3. **What is its working surface?** Planks, slats, a lid, a blade, a trough, a
+ table. Divide it into pieces; a single slab reads as a box.
+4. **What attaches the parts?** Rope, iron straps, nails, hinges, lashings,
+ rivets. Two or three are enough; a row of identical studs is noise.
+5. **What is the story?** Contents, a tool, a repair, a trophy, a rag, wear on
+ the edge that is used. One or two, placed where the camera sees them.
+
+A hay cart from the reference build: bed, six side slats, two spoked wheels with
+iron tyres, four corner straps, three tied bales, loose straw, pitchfork, sack,
+red rag, two draft shafts. That is ten assemblies for a prop the user sees for
+two seconds. A crate with a pale sphere inside is none of them.
+
+### Tower Anatomy
+
+A defence tower is a small building, a machine and a crew in one silhouette.
+
+| Layer | What it adds | Failure if missing |
+| --- | --- | --- |
+| 1 foundation | plinth, steps, rubble, contact | tower floats or looks pasted on |
+| 2 shaft | taper, buttresses, bands, ladder | reads as a cylinder |
+| 3 platform | deck, rail, hatch, brackets | machine has nowhere to stand |
+| 4 machine | weapon, pivot, rail, recoil travel | attack has no origin |
+| 5 crew | gunner, cranks, spotter, ammo | tower feels automated/empty |
+| 6 livery | banner, number, pennant, paint | tower has no owner |
+| 7 wear | scorch, chips, rope, spent cases | tower looks unplaced |
+
+The animation pivot belongs to layer 4. The muzzle or launch point belongs to
+the weapon, never the tower centre. Recoil travel is 0.1 to 0.25 m for a ballista
+or cannon, 0.02 to 0.06 for a beam crystal. A tower with no recoil, no crew and
+no ammo is a monument.
+
+**A hollow object must show its opening.** A cannon with a solid brass cap is a
+baton, not a gun; the same failure turns a pipe into a rod, a chimney into a
+post, a lamp into a mushroom and a tunnel into a painted arch. Build the opening
+as geometry, not a dark decal:
+
+- replace the end cap with one or two **open-ended collars** (no front face);
+- add a recessed **dark bore tube**, open at the mouth, with its inner wall
+ visible (`DoubleSide` on a cloned material, never on the shared palette
+ material);
+- close the back with a **dark disc** so the barrel interior is not see-through;
+- add an **iron inner lip ring** and a **brass outer lip ring** so the edge
+ catches the light at 1:1;
+- put the muzzle/effect origin at the lip, not inside the bore.
+
+At 1:1 the opening needs a dark centre at least 5 to 6 px across and a lit lip.
+If the centre is brass, the hole failed.
+
+**A rotating assembly owns only its moving parts.** The yaw/turret group may
+contain the carriage, barrel, recoil slide and muzzle. Fixed stores — powder
+keg, shot pile, rammer, tools, ready rack, crew — belong to a static group on the
+tower root, never the yaw group. If they are children of the yaw group they sweep
+around the tower when it tracks a target, which reads as the whole gun deck
+rotating.
+
+Do not simply reparent the props at deck height: the barrel and carriage sweep
+through that volume at some yaw. Put them outside both the yaw sweep and the
+barrel's vertical arc. If the deck has no clear sector, bolt a ready locker to
+the outer wall below the deck: shelf, two iron brackets, powder chest with corner
+straps, shot tray, and a rammer hung on two hooks. It reads as part of the tower
+and never collides.
+
+Test two ways at minimum and maximum yaw: each fixed child's world position
+delta must be 0, and each fixed mesh's world bounding box must not intersect any
+mesh under the yaw group. Both checks pass, or the station is still in the arc.
+
+Worked example, Bombard Bastion: 17 fixed parts — shelf, two iron brackets,
+powder chest, lid, two corner straps, rope handle, shot tray, tray lip, three
+iron shot, rammer shaft, iron cap and two wall hooks. It sits at y 1.1 to 1.6 on
+the outer shaft, below the deck and outside the barrel arc. At both yaw extremes
+all 17 world positions are identical and the station has zero bounding-box hits
+against the yaw group.
+
+### Creature Anatomy
+
+A creature needs a silhouette feature before it needs a face.
+
+1. **Core mass.** One dominant volume: hunched torso, round slime, long bat.
+2. **Silhouette feature.** Horns, ears, hump, wings, tail, crest, antlers. This
+ is what the user recognises at 30 px.
+3. **Face.** Two eyes, brow, jaw or beak. Eye sockets must be dark and set in,
+ not painted on the surface.
+4. **Limbs.** Joint groups with fillers; hands and feet larger than anatomy
+ suggests, or they disappear at this scale.
+5. **Gear.** One weapon, one strap, one trophy. Not a full armour set.
+6. **Colour break.** One hue for skin, one for cloth, one metal accent.
+7. **Asymmetry.** A chipped horn, a single pauldron, a dragging club. Perfect
+ symmetry reads as a toy soldier.
+
+The boss gets 40 to 60 parts and one signature weapon. Build the weapon as a
+separate group with a haft, head, bands, studs or spikes, and a hand attachment.
+A stone head with no haft reads as a rock floating at the door.
+
+### Small Quadrupeds (Cats, Dogs)
+
+A cat is not a small human on all fours. Build a horizontal spine and four
+contact legs; the silhouette is the back line, ears and tail.
+
+- **Body:** chest sphere r 0.085 at y 0.24, belly capsule 0.24 long, hip sphere
+ r 0.080. Shoulder height 0.26, nose-to-tail base 0.46. A cat at human scale is
+ about 0.25 m at the shoulder; measure, do not scale a person by 0.2.
+- **Head:** skull r 0.075, muzzle 0.045 forward, jaw, nose, two triangular ears
+ (cones or three-vertex prisms) at the top corners. Eyes face forward with a
+ dark socket and a vertical pupil; at 30 px the ears and pupils carry the read.
+- **Legs:** four chains (upper 0.10, lower 0.11, paw 0.05). Front legs are
+ straighter; rear legs have a hock that bends backward. Paws land flat, toes
+ forward. Do not use the human knee sign for a hock.
+- **Tail:** four to six segments with a slow S-curve, root at the sacrum. It
+ counter-sways against the walk and curls when sitting; a rigid stick tail is
+ the fastest way to lose the animal.
+- **Walk:** lateral-sequence four-beat, phase offsets roughly LF 0, RH 0.25,
+ RF 0.5, LH 0.75. The spine dips and rises twice per cycle; the head stays
+ level. Drive phase from distance travelled, like the bipeds.
+- **Sit:** haunches down, rear hocks folded, front legs straight, chest up, tail
+ curled around the paws. A sitting cat is a triangle, not a crouched person.
+- **Jump:** crouch (hips down, spine compressed), extend (all four legs push),
+ airborne (legs tucked, tail up), land (front paws first, then rear). Two
+ seconds of anticipation and recovery, not a linear hop.
+- **Fur:** one base colour, a lighter chest/muzzle, darker ears/tail tip and two
+ or three stripe bands. Do not model individual hairs; the palette snap eats
+ them. Contact shadow is one stretched ellipse under the body, not four paw
+ blobs.
+
+Shoot the cat at 1:1 in profile, three-quarter and sitting. If it reads as a
+rabbit, the ears are too long; if it reads as a dog, the muzzle is too broad and
+the back line too straight. No gear, no trophy, no human jacket.
+
+### Environment Anatomy
+
+- **Three scale cues.** One small (grass, bones, cobbles), one human (cart,
+ barrel, spear), one tall (tower, tree, gate). Without all three the slab has
+ no scale.
+- **Three story props.** A camp, a repair, a warning, a toll, a shrine. Place
+ them off the main path but inside the camera cone.
+- **Two ambient loops.** Fire, flag, smoke, fireflies, grass, water, hanging
+ bones. Phase them differently; synchronized loops read as a screensaver.
+- **A path with a memory.** Ruts, footprints, dropped goods, a worn threshold.
+ A clean path is a diagram.
+- **A boundary treatment.** Trees, rocks, posts or a wall that explains why the
+ slab ends. Do not let props clutter the threshold.
+
+### Detail Audit At 1:1
+
+Before the animation pass, inspect each hero object at 1:1 and answer:
+
+- Can I name its three construction layers without guessing?
+- Does it cast a contact shadow and touch the ground?
+- Is there one asymmetry or story detail I can point to?
+- Does it overlap another object of the same silhouette?
+- Is any detail under 1.5 px, and therefore speckle?
+- Does every hollow object — cannon, pipe, chimney, lamp, tunnel — show a real
+ opening, or does it end in a cap?
+- Does it read in grey, without colour?
+
+If any answer is no, fix the object before animating it. Animation multiplies
+detail; it does not create it.
+
diff --git a/references/education-ui.md b/references/education-ui.md
new file mode 100644
index 0000000..8a6a5e2
--- /dev/null
+++ b/references/education-ui.md
@@ -0,0 +1,122 @@
+# Educational UI
+
+## Canonical educational UI and inspection contract
+
+This is the single authority for educational UI, selection and lesson behavior.
+The exact V8 tokens/hierarchy below remain the 3.16 visual contract.
+
+**Use code, not an interpretation of “shadcn-style”.** For every new educational
+scene, copy `templates/education-v8.css` and build the DOM hierarchy below.
+This is the canonical visual contract extracted from the V8 explorer, independent
+of the chosen 3D render preset. Default to its ONE right card / mobile bottom dock;
+do not substitute the older bottom/center examples as new-build defaults.
+An explicitly requested bottom/center dock may change placement only, retaining
+these tokens, controls and hierarchy. Existing repairs preserve requested placement.
+The older `education-dock.css` is a minimal helper, NOT the V8 visual reference;
+do not use it as the visual starting point for new educational builds.
+
+Evidence: the grandfather-clock drift used beige/brass UI, a separate top-left
+title, translucent blurred panel and fixed top-to-bottom height. None follows
+from a clock subject. Brass belongs on the clock, not on its application chrome.
+
+### Exact visual values (copy the CSS; do not restyle per subject)
+
+- Page `#f7f7f5`, opaque card `#fff`, ink `#18181b`, muted `#71717a`,
+ border `#e4e4e7`, secondary `#f4f4f5`, focus/accent `#2563eb`.
+- System sans, base 14px/1.5. Desktop heading 21px/1.35, weight 650,
+ letter spacing -0.6px; mobile 19px. Supporting copy and buttons 12px.
+- Desktop `.viewer`: grid `minmax(0,1fr) 360px`, right padding 24px,
+ height 100dvh, vertically centered card. Stage is the first grid cell, NOT
+ a fullscreen canvas underneath an overlay. Card is content-height, max
+ `calc(100dvh - 48px)`, 22px padding, 18px gap, 14px radius, 1px border,
+ shadow `0 1px 3px #18181b08, 0 8px 32px #18181b03`.
+- Below/equal 880px: one column, rows `minmax(0,1fr) auto`; dock max-height
+ 48dvh, full width, top corners 14px, padding 16px 18px plus safe-area bottom.
+ Measure the actual remaining stage for camera fit and renderer sizing.
+- Two segmented tabs: secondary background, 4px inset, 9px outer radius;
+ selected tab white with subtle shadow. Primary playback is dark ink/white,
+ not subject-coloured. Controls 36px desktop / 40px mobile; maintain adequate
+ touch targets (44px hit regions where needed without crowding the row).
+- No beige/brown UI substitutions, serif/display fonts, uppercase eyebrow,
+ translucent glass, backdrop blur, heavy shadow, detached title, always-open
+ technical sections, extra dashboards or full-height panel. Do not grow a short
+ card to fill its max-height. Subject geometry/materials remain subject-specific.
+
+### DOM skeleton and state adapter
+
+```html
+<main class="viewer">
+ <div class="stage-wrap">
+ <canvas id="stage" tabindex="0" aria-label="Interactive mechanism; drag to orbit"></canvas>
+ <p class="gesture">Drag to orbit · scroll to zoom · click a part</p>
+ </div>
+ <aside class="panel" aria-label="Mechanism controls and explanation">
+ <div class="panel-top">
+ <header class="panel-head">
+ <div class="title-row"><h1>Subject name</h1><span class="badge">Interactive</span></div>
+ <p class="lede">Short input → change → output summary.</p>
+ </header>
+ <div class="tabs" role="tablist" aria-label="Mode">
+ <button id="tab-explore" role="tab" aria-selected="true" aria-controls="explore-panel">Explore</button>
+ <button id="tab-learn" role="tab" aria-selected="false" aria-controls="learn-panel" tabindex="-1">How it works</button>
+ </div>
+ <div class="controls" role="group" aria-label="Playback">
+ <button class="btn primary" id="play">Pause</button>
+ <button class="btn icon" id="prev" aria-label="Previous step">‹</button>
+ <button class="btn icon" id="next" aria-label="Next step">›</button>
+ <button class="btn icon" id="home" aria-label="Reset view">↺</button>
+ <button class="btn toggle" id="xray" aria-pressed="false">Inside</button>
+ </div>
+ </div>
+ <section id="learn-panel" role="tabpanel" aria-labelledby="tab-learn" hidden>
+ <p class="section-note">One short instruction.</p>
+ <div class="lesson-steps" role="group" aria-label="Causal steps"><!-- subject steps --></div>
+ </section>
+ <div class="readout">
+ <p class="phase-title" id="phaseTitle"></p>
+ <p class="phase-meta" id="phaseMeta"></p>
+ <p class="explain" id="explainText"></p>
+ </div>
+ <button class="link" id="clearPart" hidden>← Back to cycle</button>
+ <section id="explore-panel" role="tabpanel" aria-labelledby="tab-explore">
+ <label class="label" for="parts">Inspect a part</label>
+ <select id="parts"><option value="">Choose a part…</option></select>
+ </section>
+ <details class="disclosure help"><summary>About this model</summary>
+ <p class="section-note">Simplifications and keyboard help.</p>
+ </details>
+ <p class="sr-only" role="status" aria-live="polite" id="announcer"></p>
+ </aside>
+</main>
+```
+
+Adapt subject names, number of lesson steps, part IDs, explanatory text and
+physical units only. Omit Inside for a mechanism with no enclosing shell; never
+add a fake x-ray toggle. Optional scrubber/Back lives in this same surface, not a
+second toolbar. Use line SVG icons matching the supplied CSS in production.
+Implement tab click plus ArrowLeft/Right/Home/End roving tabindex, hidden panel
+state, and semantic buttons/select/range. Bind controls to the actual evaluator:
+`play/pause`, `freeze(step.phase)`, `orbit.reset`, reversible `inside`,
+`selectPart(id)` and `clearSelection`. A lesson change freezes synchronously and
+updates explanation from that state; it must not trigger automatic camera motion.
+The skeleton/CSS is not a functioning controller; do not ship inert controls.
+
+### Three regression gates
+
+1. **Computed-style/structure:** at 1280×800 assert one card, one h1 INSIDE it,
+ 360px card column, opaque white card, exact neutral tokens, no backdrop filter,
+ content-height card, closed About and Explore selected initially. At 390×844
+ and 320×640 assert one bottom dock, no horizontal overflow and an uncovered
+ nonzero stage. Inject beige tokens, detached title and full-height panel; each
+ must fail the check. Record measured values, not just “V8-like”.
+2. **Rendered evidence:** review desktop, phone and 200% zoom screenshots plus
+ selected/restored states. Check actual background pixels against the authored
+ paper (not merely body CSS), tiny-part readability, stage/card separation and
+ front/back/high camera fits. For V8 matching use `#f7f7f5` consistently in CSS,
+ renderer clear/scene and ground composition; user-requested white overrides all
+ those together. A screenshot is not mechanical clearance proof.
+3. **Interaction:** keyboard-only tabs/steps/picker/reset, paused orbit, drag vs
+ selection, Inside lifecycle and shared-material restoration must pass existing
+ per-scene gates. Store commands, values and proof paths in `qa/report.json`;
+ missing browser/computed-style/visual checks remain UNVERIFIED.
+
diff --git a/references/educational-mechanism-profile-first-class-exception.md b/references/educational-mechanism-profile-first-class-exception.md
new file mode 100644
index 0000000..4534c9a
--- /dev/null
+++ b/references/educational-mechanism-profile-first-class-exception.md
@@ -0,0 +1,21 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Educational Mechanism Profile (first-class exception)
+
+**UI and inspection authority:** `Canonical educational UI and inspection contract`
+below owns placement, controls, lessons, selection, focus and restoration. Follow
+it rather than inferring defaults from older screenshots. The render preset gate
+and free orbit apply unchanged.
+
+Choose `sceneProfile: educational` for explanations, technical cutaways and how-it-works scenes. This profile takes precedence over ALL narrative quotas below: no mandatory cast, disruption, ritual, landmark, three systems, ambient loops, five actor layers or decorative story props. One accurately constructed mechanism and one clear causal sequence is sufficient. Do not invent a crowd or combat to satisfy the router. Research and construction accuracy remain mandatory; simple UI never means missing mechanical parts.
+
+- **UI, selection and lessons:** use the canonical contract below; no second
+ toolbar, competing material cache or explanatory clock.
+- **Component manifest is a hard delivery artifact:** record each essential part's ID, assembly/parent, function, supporting joint/bearing/fastener, input/output connection, motion law, units, source and tolerance, mesh/group mapping, selectable anchor and proof frame. Include otherwise obscured shafts, cams, rods, links, valve gear, ports, supports and housings when functionally relevant. Explicitly state omissions and symbolic simplifications before acceptance; never substitute a label for missing construction.
+- **Mechanics are coupled, not independently looped:** derive all driven transforms from a shared phase/driver. Write and test actual ratios, directions, phase offsets, link lengths, kinematic equations, contact/clearance and event timing. For an engine, for example, verify crank:cam 2:1 over a 720° four-stroke cycle, connecting-rod length and piston stroke, valve lift/seat contact and opening order; do not copy these ratios into unrelated mechanisms. Check contacts across motion, not only at the hero frame.
+- **Nothing passes through another solid:** this is a hard acceptance rule for EVERY profile and preset, including educational scenes. Test non-contact pairs over the complete motion range and at contact transitions, not just one still. Declare intended joints/contact surfaces and numeric tolerances; all other swept bodies must keep positive clearance. Include complete geometry (tips, tails, bevels, fasteners and attachment arms), not only centres/anchors. In an engine, test actual piston-crown/valve-head/spark-plug bounds and actual cam/follower surfaces at dense phase samples. Do not move independent parts with unrelated sine waves, hide a collision with a cutaway, turn off depth testing, or use transparency/labels to pretend it is fixed. First solve the constraint or alter the geometry. Every shaft, piston, rod or sliding member that crosses a fixed wall/flange needs a REAL bored hole, slot or cutaway opening with measured swept clearance; a solid shelf with a dark circle painted on it is a failure. Test the moving body against the actual structural mesh at the crossing plane, including the lowest/full-travel pose. Ignition flames, gas arrows and pressure indicators must also stay in the moving free volume: their full tips/tails/width must not cross the piston, liner, valves or plug. Keep depth testing on; an explicit x-ray teaching mode must be separately selected and clearly identified, never the default. Capture before/contact/after frames from at least two useful orbit angles. A failed or unrun penetration check blocks acceptance.
+- **Hard acceptance, not promises about agents:** reject delivery until the manifest has no unexplained missing essentials; numeric invariant tests pass at boundaries and dense cycle samples; repeated `freeze(t)` yields identical state; desktop/phone hero frames and front/back/high orbit crops are reviewed; a motion strip proves causal order, contact and no interpenetration; controls, pointer-drag vs click, keyboard selection/focus and reset are tested. Store actual commands/results and tolerances in `qa/report.json`. An unrun check is UNVERIFIED, never a pass. These gates make omissions detectable; no skill can guarantee every future agent complies.
+- **Profile-aware QA:** retain finite geometry, console, deterministic time, contact and motion checks for every preset. Pixel uses palette/dither checks; toon uses native contour/material checks; hybrid checks low-res target + nearest upscale + only one outline pipeline. Educational off-white and the canonical single UI surface replace white-empty-paper/cast/ritual quotas explicitly; do not silence unrelated failures. Fixed-camera assertions apply only after `orbit.reset()`, never during user inspection.
+
diff --git a/references/educational-models.md b/references/educational-models.md
new file mode 100644
index 0000000..ad90c83
--- /dev/null
+++ b/references/educational-models.md
@@ -0,0 +1,60 @@
+# Educational assets: commercial, modifiable, lesson-accurate
+
+Verified external geometry may be the named teaching object, a subsystem or context. Authorship is required for missing explanation/identities/interfaces, not necessarily every vertex. A detailed exterior, CAD badge or institutional source does not establish correct internals or operating motion.
+
+## Small search, not another catalogue crawl
+
+1. Read the whole-object brief and identify exact subject/variant/part number, needed internal parts, motion and available reference dimensions.
+2. Search official/institutional or original-author sources first. Inspect up to **three promising candidates**, one targeted refinement if necessary, then decide. Do not enumerate an entire repository for an educational build. Keep licensing evidence and short metadata on disk, not huge pages/model blobs in context.
+3. Prefer an appropriately licensed, documented model over guessed hand geometry. If none passes, author only the missing/suitable representation from trusted references. Never substitute an unrelated “close-looking” object or invent hidden construction without marking it reconstructed.
+
+### Discovery sources (not blanket approval)
+
+- [Smithsonian 3D](https://3d.si.edu/): object scans and documented artefacts; verify the actual model bears **CC0**. Exterior scans are not internal assembly diagrams. Its [Open Access FAQ](https://www.si.edu/openaccess/faq) lists GLB/glTF/OBJ and distinguishes restricted items.
+- [NASA 3D Resources](https://science.nasa.gov/3d-resources/): free mission assets; inspect each asset's provenance, credits, scale and [media usage rules](https://www.nasa.gov/nasa-brand-center/images-and-media/). Free access is not an automatic license for every third-party element; NASA/public-domain/custom terms require explicit review, not relabelling as CC0.
+- Original manufacturer/university/open-hardware CAD and drawings: useful for exact dimensions and separable assemblies. Free CAD download alone does NOT permit commercial adaptation or redistribution. No acceptable explicit rights means reference-only or reject as a scene asset.
+- Clearly licensed original-author repositories/marketplaces: inspect the original landing page and the actual model/texture licenses. A search engine, preview, “royalty-free” label or third-party mirror is not a rights grant. Polyfork may provide context or actual matching parts if the same rights/readiness conditions are met; decorative low-poly assets do not prove mechanical accuracy.
+
+## Non-negotiable rights gate
+
+Require zero acquisition cost AND documented permission for **commercial use, modification/adaptation, and redistribution as part of the delivered scene**. Offline delivery also requires local bundling/embedding and included dependencies. Do not silently settle for personal/educational-only, editorial, NC, ND, evaluation-only or unknown terms. No login/paywall/terms bypass and no inferred permissions from a provider's reputation.
+
+Default automatic policy acceptance:
+- **CC0-1.0**: copy/modify/distribute commercially; retain provenance even when attribution is optional. [Official deed](https://creativecommons.org/publicdomain/zero/1.0/).
+- **CC-BY-4.0**: commercial adaptation/redistribution with appropriate credit, license link, retained notices and change indication; do not impose extra restrictions on the licensed asset. Keep its license separate from your code license. [Official deed](https://creativecommons.org/licenses/by/4.0/).
+
+Other licenses (including CC-BY-SA, MIT/Apache CAD, custom manufacturer or public-domain declarations) need a documented manual compatibility review before use; they are not automatically prohibited or falsely renamed CC0. ShareAlike may allow commercial derivatives but introduces obligations, so do not silently accept it for a proprietary deliverable. Prefer another CC0/CC-BY candidate if review would expand the task. Unknown rights are not permission. Check textures, clips, fonts, decals, embedded scans and other separately licensed works too. Patent/trademark/privacy/publicity issues are not cleared by a copyright label; don't imply endorsement.
+
+## Accuracy and functional acceptance — separate from rights
+
+Assign one role to each accepted candidate:
+- **Teaching**: exact identity/variant, documented dimensions/scale and critical geometry match the lesson. Map actual parts to semantic IDs, validate required pivots/travel/ports/openings and real interfaces. For static subjects, explicitly record which motion/interface checks are inapplicable and why. A flattened mesh can serve only if the lesson genuinely needs no separable internals; don't invent a fake part map.
+- **Exterior**: documented identity/proportions suitable for exterior explanation/reference, without internal/mechanical claims.
+- **Context**: appropriate scenery with verified scale/import, not evidence for how the teaching object works.
+- **Rejected / needs review**: wrong variant, missing rights, missing critical components or untested import. A legitimate license can pass while teaching readiness remains false.
+
+Compare against an independent drawing, source description or reliable measurements. Measure imported geometry, not just metadata. Check units, up/front axes, origin, bounding dimensions, finite/nonempty geometry, actual holes and fit. Validate motion with the existing driver/interface tests. Preserve needed clearances/part boundaries during decimation and palette conversion; no default material replacement that erases labels or important colour coding.
+
+## Import wrapper and delivery
+
+Prefer GLB/glTF for the web; convert CAD/OBJ offline only when the tools and rights permit it. Download only the chosen assets and their required dependencies. Store source bytes/hash and a permitted working conversion separately. Remote modules are executable third-party code: prefer inspected data assets/local vetted conversion, not blind execution of arbitrary source.
+
+Return a wrapper with `{group, physicalLeaves, selectableScopes, localAnchors, ports, motionHandles}`. The wrapper supplies explicit ownership, shared interfaces and evaluator adapters. Do not merge selectable/moving parts or replace real model pivots with guessed world coordinates. Validate the imported object using the same construction, coverage, highlight/restoration, live callout and camera-fit checks as authored geometry.
+
+Default delivery remains genuinely self-contained/offline. Embed/local-package ALL dependencies when permitted; no hidden CDN texture, remote module or lazy model fetch. Test with network disabled, not just a warm cache. If an asset permits only online use/hotlinking, reject it for this delivery; an online-dependent variant needs explicit user agreement and truthful labelling. Do not call an externally fetched model “inlined” because the loader code is inlined.
+
+## Recorded evidence + executable gate
+
+Start from `templates/educational-asset-record.json` (blank fields deliberately fail). Save one compact `assets/manifest.json` record per copyright work (group same-license model/buffer/texture files under one work; separate differently licensed works in `dependencies`). Use `templates/educational-asset-gate.mjs`:
+
+```js
+import { evaluateEducationalAsset } from './educational-asset-gate.mjs';
+const result = evaluateEducationalAsset(record, {delivery: 'offline'});
+if (result.status !== 'accepted') throw new Error(JSON.stringify(result.reasons));
+```
+
+The helper header specifies the record fields: source/download URLs, creator/date, canonical license and asset-page evidence, explicitly reviewed rights/zero cost, credit/license/change notices, delivered file hashes, dependency rights, accuracy/structure/import results and role. `restrictions: []` means no additional incompatible terms beyond the standard license—not that CC-BY has no conditions. Never set a checkbox merely to make this pass. Attach actual proof links/measurement notes in the manifest or DESIGN.
+
+`rightsAllowed` and `ready` are separate. Only recorded CC0/CC-BY evidence auto-passes; missing/custom/SA holds, explicit incompatible rights reject. Offline recursively checks bundling/dependencies. This is a **policy/completeness validator of supplied records**, not a crawler, license authenticator, file-hash recomputation tool, legal opinion or scientific-accuracy detector. The agent must read real terms, hash actual downloaded bytes and run actual import/geometry tests. Its synthetic regressions do not certify a real downloaded asset.
+
+No new full-scene audit bureaucracy: reuse the existing single QA runner and credit file. Search once, keep the chosen record, and rerun import/readiness only when that asset or its use changes.
diff --git a/references/effects.md b/references/effects.md
new file mode 100644
index 0000000..93b037a
--- /dev/null
+++ b/references/effects.md
@@ -0,0 +1,77 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Effects
+
+- **Water**: `MeshPhysicalMaterial` with vertex colours, not a custom shader, so
+ it receives shadows. Ramp shallow to deep teal, never to navy: a near-black end
+ quantises into a hard band the user reads as a hole.
+- **Wake**: unlit additive foam streak plus 8 to 12 expanding ripple rings spawned
+ behind a moving body every 0.4 s, fading as `(1-k)^2`.
+- **Splash**: 60ish unlit additive droplets with gravity plus four rings and a
+ foam disc; normal-blended white over teal reads as a grey blob. Seed the burst
+ (`trigger(x, z, power, burstSeed)`), never `Math.random`: a frozen frame must
+ reproduce the same burst, and the same frame must reproduce it again after the
+ clock jumps.
+- **Effects that integrate dt need a `reset()`.** Wake and splash advance by
+ `dt`, so jumping the clock to freeze a frame does not jump their state, and the
+ frozen splash shows whatever the last played frame left behind. Both templates
+ expose `reset()`; the harness calls it and re-simulates in fixed steps from
+ zero, which took a two-frame diff from 334 differing pixels to 18.
+- **Smoke**: camera-derived billboards. The camera can orbit, so update from its current
+ quaternion once and every puff is a plane facing the lens.
+- **Debris with history**: loose notes or paper use a solved arc, a drag term, a
+ spin about a random-but-deterministic axis, then slerp to flat and lie there for
+ the rest of the loop. Deterministic hashing (`sin(n*127.1)*43758.5` fractional)
+ keeps every replay identical.
+
+### FX And The Edge
+
+The slab is a window, but not every effect is a solid. Split them:
+
+- **Cut FX** — debris, props, vehicles, bodies. Let the world clip plane cut
+ them; model the interior so the cut reads as a cutaway, and route them so they
+ enter and leave rather than parking across the edge.
+- **Read-through FX** — light beams, glow, wake, spray, horizon haze. Do **not**
+ let a hard clip plane slice them. End the effect at its target, fade intensity
+ to zero before the slab boundary, or mask it with a soft edge. A lighthouse
+ beam that stops in a straight vertical cut reads as a broken cone.
+- **Additive over white.** Additive white on a white page is invisible. Give a
+ beam a saturated core from the palette plus a darker under-edge or halo, and
+ test it at 1:1 against the page, not against a dark viewport. If the beam must
+ cross the whole frame, let it dim toward the edge; a bright hard-ended beam is
+ worse than a soft falloff.
+- **Clipped water.** A hull cut at the slab edge needs its interior and a foam
+ plane at the cut, or it reads as a hollow shell. A moored boat should sit fully
+ inside the frame for the beat where it unloads.
+
+### FX Under The Snap
+
+Every scene effect goes through the palette snap. That is the look, but it
+punishes sub-pixel tricks:
+
+- Author FX at **2 px or wider** at the target buffer. A 1 px additive wisp
+ disappears or becomes a single palette dot; enlarge it or delete it.
+- Use a **palette-legal saturated colour** and a dark contour, not pure white.
+ White clips to the page and the snap has nothing to quantise.
+- Do not rely on a smooth gradient to carry an effect. Build it from 2 to 4
+ palette steps, a scrolling band, or a shape with a hard edge.
+- Test with `?dither=0` and at 1:1. If the effect only reads in a downscaled
+ preview, it is not in the render.
+
+### Contact Contexts
+
+"Touching the ground" is not one rule:
+
+- **Ground prop:** contact shadow plane 0.018 above the slab; lowest vertex on
+ the deck, not floating.
+- **Deck / gallery / table:** the shadow belongs on that surface at its Y, not on
+ the slab below. Parent the figure and shadow to the deck, or project onto the
+ deck plane; a gallery figure with a slab shadow reads as a ghost.
+- **Water:** the hull sits below the waterline; use a foam ring at the waterline
+ and a wake, not a contact shadow. A floating boat with a hard shadow on the
+ water reads as a toy on a table.
+- **Vertical / wall:** a ladder, hook or rope needs a contact mark at the rung,
+ grille or rail it bites, plus a small recoil; a hook in mid-air is a prop.
+
diff --git a/references/external-models.md b/references/external-models.md
new file mode 100644
index 0000000..670c575
--- /dev/null
+++ b/references/external-models.md
@@ -0,0 +1,96 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Borrowed models: the Polyfork CDN
+
+A free catalogue of ~2,800 low-poly models, every one hotlinkable with no account, commercial use, no attribution. It is worth knowing for one reason: the models are metres, Y up, origin on the ground, front facing +Z, flat-shaded vertex colours on a single material. No textures to relight, no import pipeline, no scale guessing.
+
+### Default sourcing compliance
+
+Search AND use suitable licensed assets by default, for major roles rather than a token background prop. The 5.1 internet-first rule in SKILL.md governs: Polyfork is first for narrative kits, not the only source; a miss continues to relevant model libraries. A licensed candidate must also pass actual import, palette/scale/detail, performance and requested motion/selection checks. Do not reject a useful model merely because it needs a pivot/identity wrapper. Prefer free commercially adaptable, scene-redistributable assets; paid downloads need approval. Record real downloaded files/hashes, license evidence and final-scene use, or the specific reason no fitting model could be used. Never force an unsuitable model to meet an asset quota.
+
+### When it earns a place
+
+**Narrative scenes: the catalogue is the primary source.** Ground, buildings, vehicles, vegetation, furniture, signage, animals, cast, clutter — sweep it before modelling, and hand-model only what the sweep proves absent or what the scene must select, move or explain. A street assembled from eight hand-rolled primitives when a matching kit shipped 60 coherent parts is a failed scene, not a disciplined one.
+
+**Educational scenes: verified teaching geometry is allowed.** Follow `educational-models.md`: shortlist at most three relevant assets; require documented free commercial use, modification and scene redistribution, then check identity, dimensions, critical geometry and usable components. Import the named object/parts when they pass; author semantic identities, interfaces, missing internals and evaluator behavior. A pretty exterior alone cannot establish working mechanics. This bounded educational search does not require the narrative full-catalogue sweep below.
+
+In a narrative scene a borrowed asset may carry the hero prop if the sweep found the actual object and it survives palette/scale checks. Selection is not a reason to reject imported geometry: attach explicit ownership and local anchors. Explaining a mechanism additionally requires the educational accuracy/structure gate; author any missing teaching interfaces instead of claiming unverified internals are accurate.
+
+### Sweep the catalogue before you model
+
+One pass, every noun, recorded. Run it after the DESIGN sheet and before the layout milestone. It is cheaper than modelling, and it is the difference between a scene standing in a real world and one assembled from guesses.
+
+1. **List the nouns.** Ground/terrain, each building type, vehicles, vegetation, furniture, signs, tools, animals, people, and the clutter that sells scale. One row per noun in `sweep.md`.
+2. **Enumerate the catalogue once.** `GET /api/assets?per_page=100&page=N&fields=compact` until `total` is consumed — 28 pages for the current 2,766 rows. Write `id`, `class`, `triangles`, `kit` to `sweep.csv` with a local script: a page is ~42 KB of JSON and the full set is ~1.1 MB, so it is never pasted into context. No detail calls yet.
+3. **Query each noun four ways:** the word, a synonym or US/UK variant, an era or material qualifier, and by class (`class=prop|building|vehicle|character|animal|attachment|terrain|ultra|hand`). Read `coverage` on every answer and `unmatched_terms` after a miss.
+4. **Sweep kits for places.** `GET /api/kits`, then `/api/kits/{id}`. Adopting a kit beats assembling singles that then need a coherence pass: one palette, one scale, one grid, and a `layout` of real placements you can rebuild exactly.
+5. **Fan out from the best hit.** `/api/assets/{id}/matching` walks same kit → shared palette → compatible scale. One call turns a prop into a coherent group.
+6. **Decide per noun, then stop.** `sweep.md` rows: noun | queries | candidates seen | chosen id and why | rejected. "Absent" is a legitimate recorded answer that sends you back to hand-modelling, or changes the scene. A second pass only when a hit's kit suggests a better family — never the same query again at a later milestone.
+
+The coverage words mean different things and the wrong reading produces a worse scene. `none`/`poor`: the catalogue does not have it — say so, model it, or `POST /api/demand`. `filtered_out`: it exists and your filters removed it (`matches_before_filters` says how many) — relax a filter, never report a gap.
+
+Metadata sweeping is free and unrestricted; what is rationed is remix *baking* (~40/hour anonymous). Download nothing in bulk — hotlink `/cdn/` at runtime.
+
+### Find one asset
+
+1. `GET https://polyfork.dev/api/assets?q=<plain+words>&per_page=24&fields=compact` — rows already carry `size_m`, `origin_y`, `triangles`, `has_rig`, `has_ik`, `has_skeleton`, `kit`.
+2. `GET /api/assets/{id}` — detail: palette, clips, license, exact download URLs, `physics`, decals.
+3. `GET /api/assets/{id}/matching` — same kit, then shared palette, then compatible scale.
+4. `GET /api/kits/{id}` — a kit is a *place*: shared palette, shared scale, shared grid module.
+
+Agent docs: [`/llms.txt`](https://polyfork.dev/llms.txt) is the reference, [`/prompt.txt`](https://polyfork.dev/prompt.txt) is the same catalogue written as working instructions. MCP endpoint `https://polyfork.dev/mcp` exposes `search_assets`, `get_asset`, `find_matching`, `get_kit`. Browsing needs no key.
+
+Enumerating metadata is browsing. Bulk-downloading or mirroring the GLBs is redistribution and breaks their terms; one model loaded from the CDN per placement is not.
+
+### Load it
+
+- **ES module (preferred inside a scene module).** The page's import map needs *both* entries — the modules import bare `three` and `three/addons/`:
+
+ ```html
+ <script type="importmap">
+ { "imports": {
+ "three": "https://unpkg.com/[email protected]/build/three.module.js",
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/" } }
+ </script>
+ ```
+
+ ```js
+ import createAsset from 'https://polyfork.dev/cdn/barrel-aadc94.mjs';
+ scene.add(createAsset());
+ ```
+
+ Import the **default**, never a named export. An export the module does not have is a link-time `SyntaxError` and nothing draws (about one module in nine omits `params`, `presets`, `rig`, `detach` or `night`).
+
+- **GLB.** `https://polyfork.dev/cdn/{id}.glb` through `GLTFLoader`, or any glTF pipeline. Use this when you need the file rather than the factory.
+- `/cdn/` is the anonymous path; `/dl/{id}.mjs` and zips want an account, and `-hd` editions want Pro. Never build an `-hd` URL you have not been given.
+- Bundlers (Vite, Next) do not resolve remote `https://` imports: download the `.mjs` and import it as a local file.
+- Serve over `http://`. Browsers refuse ES modules over `file://`.
+- Screenshot or canvas readback: construct the renderer with `preserveDrawingBuffer: true`, or the readback is one flat colour while the page looks fine.
+
+### Make it obey the look contract
+
+Their colour is `COLOR_0` vertex colour on one material. Decide *before* placing, because the palette snap will flatten whatever arrives:
+
+- **Accept** — only if the model's palette already sits in the diorama family. Check the hero frame, not the swatch list.
+- **Retint** — map their vertex colours to your palette entries and write them back, keeping one material. Where the module exports `params`/`presets`, prefer `createAsset({ colorway: '…' })` and let the model do it.
+- **Recut** — reassign per colour zone when one zone must read differently (a hull dark, a deck light).
+
+Then per preset:
+
+- **Pixel:** `flatShading: true`, no maps, no environment map. The post pass owns banding and ink contour; a texture or a PBR material fights both and reads as a photo glued into a drawing.
+- **Toon:** swap the borrowed material for the shared stroked-toon material and carry the vertex colours as the multiply, or replace per zone. Keep the outline width matching the hand-built cast or it reads as a different scale.
+- **Scale:** their metres are real and one figure is 1.69 m. This skill's cast reads at 30–45 px. If the diorama is not 1:1, apply **one** uniform factor recorded in the DESIGN sheet — never a per-model fudge factor.
+- **Origin:** place at the ground point with `y = 0`. No bounding-box maths. Two flagged exceptions: wall/ceiling fixtures are built at installed height, ground tiles and terrain hang below their own top surface. `origin_y` on the row tells you which you have.
+- **Merging:** `mergeAssets` from `/cdn/merge.mjs` collapses static dressing to one draw call. Merge only background that never gets selected, moved or evaluated — merging destroys per-part identity and picking.
+
+Motion, only if you need it: `rig` gives named pivots (a door, a boom), `clips` lists clips inside the GLB (animals carry Idle/Walk/Run), characters carry a skeleton and no clip and play free Mixamo clips via `/cdn/clips.mjs`. `night` maps colour zones to what lights up after dark, for windows and lamps. All three are cheaper than animating a borrowed prop by hand.
+
+### Honesty
+
+Commercial use and modification must be permitted by the actual asset terms, not inferred from “free” or this guide. A runtime CDN scene is online-dependent, not offline/standalone. Before local bundling, conversion or embedding, verify redistribution/embedding rights for every asset and dependency. If terms allow only hosting/hotlinking or prohibit redistribution, use another asset for offline delivery; do not bypass restrictions by converting it. The educational default acceptance gate is documented in `educational-models.md`.
+
+- Record in `sources/`: asset id, URL, "Polyfork free tier — commercial use, no attribution required".
+- Anonymous remix baking is rationed per IP (about 40/hour). Bake nothing you can do at runtime with knobs.
+- If the catalogue has nothing that answers, say so and model it. `POST /api/demand {"need": "…"}` records the gap. Substituting an unrelated asset because it was close is worse than an honest no — their own rule, and the right call visually.
diff --git a/references/field-notes-two-creature-combat.md b/references/field-notes-two-creature-combat.md
new file mode 100644
index 0000000..4c54c14
--- /dev/null
+++ b/references/field-notes-two-creature-combat.md
@@ -0,0 +1,102 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Field Notes: Two-Creature Combat
+
+From a Pikachu vs Charizard battle diorama built against Sword/Shield and anime
+footage. The rig, the effects and the send-out all broke in the same three ways,
+and the fixes generalise to any fight between two rigged actors.
+
+### Aiming is a local-space problem
+
+Both rigs look down their own `+Z`, and both sit under a stage root that is
+rotated (here 90°). Reading a world-space bearing to the opponent and writing it
+to a local `rotation.y` aims the two *past* each other, toward the lens. Compute
+the yaw inside the stage's own frame:
+
+```js
+const camLocal = cameraDirection.clone().applyAxisAngle(UP, -STAGE_ROT);
+const aimYaw = (a, b, cheat) => {
+ const dx = b.x - a.x, dz = b.z - a.z;
+ return Math.atan2(dx, dz) + camLocal.x * cheat; // local, not world
+};
+```
+
+Then prove it numerically, every half second, through the whole loop: forward
+vector versus vector-to-opponent should sit at 0.97+, and it may only dip during
+a deliberate spin. Eyeballing this at 300 px hides a 20° miss.
+
+### Effects belong in bone space, not world space
+
+Flames leaving a mouth must be anchored to the head joint, or they slide off the
+jaw whenever the head turns. Convert the parent's forward and up into the target
+bone's local space once at build time and keep the emitted point there:
+
+```js
+const localFwd = bone.worldToLocal(pivotPoint.clone().add(forward)).normalize();
+```
+
+Same idea for the aim of a projectile: take the muzzle from the bone matrix, not
+from a hardcoded offset.
+
+### Flat effects need an upright basis
+
+`quaternion.setFromUnitVectors(+Z, viewDir)` picks an arbitrary roll, which is
+why a kanji-shaped blast can arrive upside down or rotated 40°. Build the basis
+from the lens explicitly:
+
+```js
+const right = new THREE.Vector3().crossVectors(worldUp, viewDir).normalize();
+const up = new THREE.Vector3().crossVectors(viewDir, right).normalize();
+mesh.quaternion.setFromRotationMatrix(new THREE.Matrix4().makeBasis(right, up, viewDir));
+```
+
+### Explosion vocabulary
+
+A hit burst is a hot core with ten short sparks radiating out of it, plus a ring
+on the ground. That is the whole recipe; it reads at any size.
+
+- No cone petals, no triangle fans, no straight bars, no scaffolding around the
+ blast. Every one of those reads as geometry, not energy.
+- Layered silhouettes beat layered spheres: a body colour, a hot mid, a core,
+ each scaled *individually* (`m.scale.set(k,1,1)` per layer) — sharing one
+ geometry between layers makes the layers invisible.
+- A continuous stream is **one** mesh with overlapping segments. Separate quads
+ with per-segment jitter make a ladder with seams.
+- Nested cones hide their own core: nudge the inner layers toward the lens and
+ lift them so the hot tip clears the outer silhouette.
+
+### Pin the effect to where the hit landed
+
+An eruption anchored to `actor.position` every frame crawls across the slab while
+the actor slides out of it, which is exactly the "something feels off, it moves a
+bit" report. Latch the anchor once, at the moment of impact, and animate from
+that fixed point. Same for the projectile's target: aim at the latched point, not
+at the live chest position.
+
+### Send-out and recall are different verbs
+
+- Send-out: the trainer throws. The ball leaves the hand on an arc, spins, lands
+ on the mark, the lid opens with a white burst — flash, smoke puff, sparks, a
+ ground ring — and the creature springs out *at full size*, covered by the flash.
+ The ball then snaps shut and returns to the trainer's hand.
+- Do **not** replace that with a slow orb the creature materialises inside; that
+ is the legendary-encounter variant, and it reads as a bubble.
+- The red beam belongs to a recall or a knockout, never a send-out. If the ball
+ glows red before release, it reads as a second, wrong beam — keep the release
+ white.
+- If the trainer holds a second ball while the thrown one is in the air, hide the
+ held prop for the duration or the throw doubles.
+
+`templates/creature.js` ships these five as runnable functions: `aimYaw`,
+`headAnchor`, `uprightQuat`, `makeHurtModel`, `sendOut`.
+
+### Hit reactions scale with the attack
+
+One hit model, four severities: a light flinch (0.9 s, a tip back), a knocked-back
+stagger (1.7 s, air time), a spin-out (1.3 s), and a full collapse (3.5 s, falls,
+lies down, gets up). Rotate about the axis of the blow (`[dz, 0, -dx]`), pivot at
+mid-body so the actor rocks rather than hinging at the feet, and add a small
+vertical arc so the feet leave the ground.
+
diff --git a/references/inspection.md b/references/inspection.md
new file mode 100644
index 0000000..200c7ba
--- /dev/null
+++ b/references/inspection.md
@@ -0,0 +1,95 @@
+# Selection and inspection
+
+### Selection, focus and lesson adapter
+
+Raycast actual visible geometry: nearest eligible hit wins, respecting nearer
+opaque occluders. Map the hit mesh to both its assembly ID and its actual piece
+ID; assembly selection and clicked-mesh selection are distinct scopes. The
+single labelled keyboard piece picker must expose the same pieces/actions,
+including hidden pieces; never silently broaden a click to an entire assembly.
+Show one short explanation in the card. An optional single label uses a live
+geometry-local anchor and hides behind camera, offscreen or when occluded.
+
+A deliberate canvas/picker Inspect selection may make one short useful camera
+AND OrbitControls-target transition to live selected bounds. Avoid end-on shafts
+and blocking housings; use an authored reveal/cutaway for hidden pieces and
+report remaining occlusion honestly. Save the prior view for Back; Reset restores
+the hero. User orbit/pointer/keyboard navigation cancels the tween immediately.
+Reduced motion uses an immediate useful view. Never auto-spin, chase moving parts
+or restart focus per frame. Lesson step selection instead pauses and synchronously
+freezes the real evaluator, highlights its part and updates phase/text/readout
+without moving the camera; only an explicit Inspect action focuses. Scrubbing
+updates the lesson from evaluated state, not an independent clock. Announce
+intentional changes politely, not each frame.
+
+Use semantic buttons/select/range, visible focus and non-colour part-name cues;
+canvas arrows orbit and R resets. Tabs implement roving focus and keyboard
+navigation; no focus trap. Drag/multitouch is orbit, not click (use the movement
+threshold/cancel handling in `templates/orbit.js`); UI gestures never bubble into
+the stage. Paused and reduced-motion modes retain inspection.
+
+### Soft glow and holographic inspection — implementation recipe
+
+This is an **inspection overlay**, not a new render preset, bloom pass or a way to hide modelling errors. Use the same mechanism for a selected gear, valve, pump impeller, drawer slide or anatomical structure. The V8 selection implementation is the calibration evidence: restrained warm material lift, dimmed context, transparent outer castings and selective gold feature edges. Do not interpret “glow” as a white emissive blob.
+
+**1. Preserve and derive, never mutate the shared originals.** Build a registry once from the actual selectable meshes, BEFORE adding overlays. Store each exact original material reference, including arrays of material slots; a mesh's slot array itself must also be restored by identity. Derive cached variants from each source UUID plus mode. Clone `userData` and `outlineParameters` before changing outline alpha, since nested objects may otherwise be shared. Keep toon ramps, texture maps, roughness and existing supported preset properties. Restore the originals before applying each new selection/X-ray state, not by attempting to reverse colour arithmetic.
+
+Use `templates/inspection.js` rather than duplicating a second material controller.
+Its API is `createInspection(THREE, {parts, contextMeshes, resolveVisibility,
+onChange, style})`, with `select({partId, mesh})`, `clear()`, `refresh()`,
+`dispose()` and `piecePickerEntries(partId, {visibleOnly:false})` (includes hidden
+pieces for keyboard inspection). Validate actual mesh membership before selection.
+The helper supports rigid meshes only; reject skinned/instanced/morph assumptions.
+`resolveVisibility` returns named `hiddenPartIds`/`hiddenMeshes` plus `description`
+for an authored cover removal. Hiding requires `shell:true`, or an explicit
+`inspectionOccluder:true` part plus an active selection and nonempty cutaway
+description; that latter exception may remove an upper gear/bridge to expose a
+lower part, never hide construction failures. Optional `ghostPartIds`/`ghostMeshes`
+are accepted only for `shell:true`. Selected assemblies/pieces remain visible;
+context meshes (floor/stand/UI) cannot hide, ghost or dim.
+Unknown parts, duplicate ownership, empty geometry and unsupported material or
+deformation paths fail explicitly. Never request a whole-mechanism ghost. The host owns
+camera focus, picking and V8 DOM; the helper owns emphasis/restoration, not UI or
+mechanical certification. Cached variants derive per original material and mode; never
+from the currently displayed variant. Lift colour gently; write emissive values
+only where the original material supports them. Dim context as opaque solids.
+Only the explicit housing reveal below may change transparency/depth-write.
+
+**2. Reveal only manifest-authorized occluders; ghosting is shell-only. Never defeat depth on the selected part.** Declare `internalPartIds` and `occludingShellIds` per subject in the component manifest. For an internal selection, remove authored covers or optionally ghost only declared outer housings that obscure it; keep the selected part solid, retain non-selected internals as dim solids, and leave floor/stand/UI alone. A global Inside toggle applies that same named reveal plan without dimming all internals. A selected housing stays highlighted rather than ghosting itself. Unlisted opaque solids must still occlude correctly: `renderOrder` does not override the depth buffer. For an internal blocker, author an explained selection-only `inspectionOccluder:true` removal plan; the independent Inside toggle still affects shells only. Hidden siblings need a piece-level plan and cannot remove the selected scope. Do not set `depthTest=false`, use additive whole-body overlays, or fade all solids to pretend a mechanism is correctly constructed. Picker rays ignore generated edges and ghost-shell hits, but respect remaining opaque foreground objects; click and picker share the same selection action.
+
+**3. Make the hologram from feature edges, attached to the live part.** Do not use `wireframe:true`: that exposes triangle diagonals. Use `EdgesGeometry(source.geometry, 32)` and a restrained `LineBasicMaterial` (`color:0xffc35c`, `opacity:0.5`, `transparent:true`, `depthTest:true`, `depthWrite:false`, `toneMapped:false`). Normal blending, no bloom. Exclude slivers, ring grooves, gaskets and tiny bolts when edges become noise; the V8 thresholds were minimum dimension 0.018 units and, for cast housings, volume 0.006 units³. Those are **model-scale-dependent starting values**, not universal dimensions. Use one physical edge overlay on the selected component only, not a second full-scene OutlineEffect/Sobel pipeline. Its surface outline may need suppression to avoid doubled contours. WebGL line width is generally one device pixel: do not promise a controllable CSS-pixel width through `linewidth`.
+
+Attach each owned edge overlay as an identity-transform child of its live source
+mesh; mark it as an inspection overlay and exclude it from raycasting. On change,
+remove and dispose owned overlays, never source geometry or shared maps.
+
+This child pattern follows moving rigid geometry without copying a stale pose. If an overlay must be a sibling/world-space object, synchronise its transform from the source every evaluation; copying position/quaternion once is insufficient when the source mesh moves. `EdgesGeometry` does **not** automatically follow vertex deformation or per-instance transforms: skinned/morphed/instanced subjects need a deformation-aware shader/overlay or a clearly declared unsupported path. Never claim those supported because a rigid V8 example works. Do not dispose the source geometry, shared source maps, shared toon ramps or original materials; dispose only owned variants/edge geometries and owned overlay materials. Keep overlay generation bounded to selection changes, never create/dispose hundreds of edge objects every frame.
+
+**State and restoration contract.** One selection controller owns this effect. Resolve in order: restore exact originals → remove previous edges → compute selected/internal/Inside state → ghost selected occluding housings → highlight selected meshes → dim remaining mechanism meshes → attach selected edges. Re-apply from originals when Inside changes. Leaving How it works restores its earlier Inside state and removes its tutorial tint; clearing selection retains an independently enabled Inside toggle. Picker, canvas, keyboard and lesson adapters must not compete by writing materials from separate uncoordinated caches. Clear/reset/teardown restores material references, opacity/depth/blending/outline state, selection/readout and authored camera state; only teardown disposes long-lived caches. Respect reduced motion; avoid automatic pulsing, scanlines or flashing. Keep the part name and keyboard focus as non-colour cues.
+
+**Historical evidence (not project dependencies):** `quartz-watch/shots/highlights/dialPost1.png`,
+`quartz-watch/shots/highlights/dialPost2.png`, `quartz-watch/shots/highlights/dialPost3.png`,
+`quartz-watch/shots/highlights/dialPost4.png`, `quartz-watch/shots/highlights/individual-piece.png`,
+`quartz-watch/shots/highlights/rotor.png`, `quartz-watch/shots/highlights/reduction.png`,
+`quartz-watch/qa/highlights-report.json` and `quartz-watch/qa/construction-report.json`.
+These record this repair, not files future users must have. Twenty-six assembly
+glow states had numerical tests/captures; only a subset received visual review.
+Do not present that as universal contrast certification.
+
+**Evidence and test — selection contract (3.18).** Quartz-watch selection was
+almost invisible, posts were end-on/occluded, and adding emitter properties to
+MeshBasicMaterial caused a `shader.value` error. Use `templates/inspection.js`,
+with `templates/qa/inspection.test.mjs` and
+`templates/qa/inspection-browser.mjs`; use the API above. Assert assembly versus actual clicked-piece identity,
+keyboard equivalence, nearest opaque occlusion, and obvious visible glow with
+retained shape/colour (never a white blob) in desktop/phone crops. Test shared
+and array materials, Basic/toon, two frozen phases, moving/orbiting, rapid changes,
+Inside/clear/Back/Reset/lesson exit, interrupted focus and reduced motion. Restore
+exact original material AND slot-array identities, shadow flags and `visible`
+state, plus original material properties; test source immutability and owned-only
+disposal with stable overlay/material counts. Basic materials must never gain
+`emissive` or `emissiveIntensity`, even temporarily; feature-test capability before
+writing, and assert absent properties remain absent. Verify shader compilation
+and no console errors in the fresh browser build. Scalar/material tests alone do
+not establish visible contrast, depth correctness or useful focus.
+
diff --git a/references/interfaces.md b/references/interfaces.md
new file mode 100644
index 0000000..83179bb
--- /dev/null
+++ b/references/interfaces.md
@@ -0,0 +1,43 @@
+# Small interface checks — apply at the risky joint
+
+Copy `templates/interface-checks.js`, inject the scene's existing THREE, and reuse these predicates in the same QA runner. They do not build a global physics/collision system. Geometry bounds use active transformed triangles; hidden and transparent physical meshes stay included. Unsupported deformation/empty data fail rather than disappearing from coverage.
+
+## Model the working region before the support
+
+For a fixture, gate, machine, drawer or character/vehicle transfer, reserve a local volume for the payload/tool/travel. Put supports below/around that volume; a shortened support must still join real load-bearing geometry. A continuous carrier plate can support the fixture while a short spider connects that plate to a hub; a long arm through the pocket is not extra useful detail.
+
+Derive the stack once: bearing face → collar bottom/top → hub → carrier bottom/top → fixture seat. Mounting bolts attach to real surfaces and clear walls and payload; labels do not hang into neighbouring moving geometry. Generate all instances from the same frame table, then run the same predicates on EVERY instance.
+
+## API and limits
+
+```js
+const q = createInterfaceChecks(THREE);
+// Both are complete axis-aligned boxes in the supplied local frame.
+const contact = q.seated(plate, support, {
+ frame: assembly, tolerance: 1e-4, minOverlap: .1,
+});
+const clearance = q.outsideBox(arm, {
+ frame: assembly, box: workingPocket, clearance: .1,
+});
+const scope = q.scopedMeshes({required: specifiedMembers, registered: selectable.meshes});
+const anchor = q.worldAnchor({mesh, root: physicalRoot,
+ local: geometry => { geometry.computeBoundingBox();
+ const b = geometry.boundingBox;
+ return [(b.min.x+b.max.x)/2, b.max.y, (b.min.z+b.max.z)/2]; }});
+const fit = q.projectPoints(actualWorldPoints, camera, {margin: .08});
+```
+
+- `bounds(mesh,{frame})`: actual active geometry envelope in world or named local axes. Ignores rendering visibility, not physical membership.
+- `seated`: validates complete axis-aligned box surfaces, then signed face gap and positive transverse overlap. Curved/bevelled/annular/partial surfaces need the appropriate real-face predicate; a bounding-box face is NOT their seating surface. Explicitly reject unsupported cases instead of relaxing this helper until they pass.
+- `outsideBox`: conservative AABB separation. `clear` proves separation from this declared box at this pose; `candidate` does NOT prove penetration. Use real geometry/proxy checks for close candidates and full moving-path samples where applicable.
+- `scopedMeshes`: exact nonempty membership against an independently specified mesh list, including glazed parts; don't create both lists from the same filtered survivors. It doesn't prove shader appearance or exact material restoration—exercise the existing inspection controller and reviewed pixels too.
+- `worldAnchor`: derives a fresh point from the live mesh/local frame; callback can recompute geometry-dependent anchors. Rejects detached sources. Validate geometry once during build/QA; this is not an occlusion, screen-label or displayed-text test.
+- `projectPoints`: reports full projected point coverage and clipping; it doesn't prove another solid isn't occluding them. Retain the selected/restored screenshot check.
+
+All example values are illustrative model units, not universal tolerances. For an annular carrier, a short-spoke outer-radius bound strictly inside the nearest fixture radius can prove their separation only when the actual geometry lies in the measured radial bands. Use transformed geometry, not an assumed radius or outer-minus-outer clearance.
+
+## A few real regressions, not more ceremony
+
+Pass baseline → lift a real mounting plate → SAME seating predicate fails → restore → pass. Extend/move the real support into the working pocket → SAME clearance predicate flags a candidate → use the relevant narrow check → restore. Omit the actual glazed member from selection → SAME scope predicate fails. Translate/rotate parent and revise source geometry → live anchor follows; remove it from root → reject. Move camera too close → SAME projection predicate fails; use the solved fitter → pass.
+
+Evidence: the 1 November carousel repair shortened eight spokes from the bottle-pocket region to the inner carrier lip, seated the rotating stack on its actual bearing and moved bolt heads/labels clear of occupied regions. The focused project runner passed 44 bounded checks and two real mutations, with reviewed empty-pocket/top/low captures. That repaired assembly is evidence for these patterns—not proof that the whole machine, gear design or a future model is mechanically certified. No required per-mesh screenshot collection or extra all-pairs audit is added.
diff --git a/references/motion-graphics-primitives-arrows-flames-flow.md b/references/motion-graphics-primitives-arrows-flames-flow.md
new file mode 100644
index 0000000..0e34056
--- /dev/null
+++ b/references/motion-graphics-primitives-arrows-flames-flow.md
@@ -0,0 +1,158 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Motion Graphics Primitives (arrows, flames, flow)
+
+Animated arrows and flames are how a mechanism explains cause. They fail
+silently: the build passes, one still looks plausible, and the graphic points
+backwards or sits inside a solid. Treat every primitive as a tiny part with its
+own convention test, in every preset.
+
+- **Declare and test the local forward axis.** A cone built with
+ `CylinderGeometry(radiusTop, radiusBottom, ...)` points along the *top* end.
+ Swapping those two numbers makes every arrow flow backwards while still
+ looking like an arrow. Build the tip at local `+Z`, store `tipLocal` and
+ `tailLocal` in `userData`, and assert: cone base wide and behind, tip a point
+ ahead, and the placement transform maps `+Z` onto the requested tangent.
+- **Never place an arrow on the centreline of an opaque body.** An arrow inside
+ a cast runner is invisible with honest depth testing; the usual "fix" is
+ `depthTest:false`, which turns the scene into x-ray. Two honest options only:
+ cut a real window/section that exposes the gas volume, or place arrows solely
+ in the genuinely open region (port mouth, chamber, outlet). Keep depth test and
+ depth write on; assert `depthTest === true` for effect materials.
+- **A spline through an open cutaway is not a flow route.** An intake path that
+ looked correct in the port still speared the valve disc, because the gas turns
+ around the open valve, not through it. Derive each effect from the *current
+ free volume* (crown to the live valve underside) instead of a fixed centreline,
+ and use one bold arrow per stroke rather than a stream spawned along a curve.
+- **Fit the whole cone, not its centre.** The vertical extent of a
+ cylinder-capped cone depends on its direction: `|dy|·half + flat·head`. For a
+ vertical arrow that is its half length, so clamping only the centre lets the
+ head pierce the crown or the valve. Compute the extent, reduce the scale until
+ the band and the bore both fit, then clamp the centre. Judge "bold" by rendered
+ length (`length × scale`), not by the scale ratio: a long authored arrow in a
+ short band is legitimately scaled down and still reads.
+- **Anchor to a real surface, and normalize the authored length.** Put the intake
+ tail and the exhaust tip `0.008` under the valve head underside
+ (`seat − 0.061 − lift`), span at most `92%` of the band, give a compression
+ chevron its tail on the rising crown (`crown + 0.02`) so it touches the charge
+ it describes, and start a force arrow `0.015` *inside* the flame tip. Author the arrow at its maximum length so `scale ≤ 1`; otherwise a
+ non-normalized `1.14` arrow makes the minimum-scale gate and every sizing test
+ meaningless.
+- **Never stack two rows of the same arrow.** Two overlapping compression rows
+ read as double-headed spikes. Two side-by-side chevrons, or one arrow, not two
+ rows at the same x/z.
+- **Couple the effect to its source.** A pressure arrow that outlives the flame
+ becomes an orphan arrow pointing at nothing. Fade the arrow with the flame
+ kernel and hide both on the same frame.
+- **Every Y constant shares one space.** A group lifted off the plate (here
+ `+0.024`) silently shifts every "absolute" ceiling. Measure the *scene* in the
+ same local space the constants were written in; mixing world and local turned a
+ correct flame into a phantom 24 mm head violation.
+- **A flash must not saturate the frame.** Halo opacity `0.40`, halo scale `0.42`
+ and point-light intensity `2.2` are already generous at diorama scale; the
+ earlier `0.95 / 1.14 / 9.0` blew the whole head to white, and `0.55 / 0.62`
+ still washed the crown orange for two frames. Judge the ignition frame itself,
+ not the frame after it.
+- **A flame may not die as a bead.** The kernel must span the fixed clearance
+ recess at TDC (`0.125` here) and be hidden below `0.12` height. A flame that
+ fades to a two-pixel dot on the valve seat is the flame equivalent of an arrow
+ speck, and a mid-stroke still will not show it.
+- **Audit every 15°, not four hero stills.** Render the full 720° at a tight
+ chamber camera, build one contact sheet per stroke, and read every cell. The
+ spear-through-valve, the double-headed chevrons and the ignition white-out were
+ all invisible in the four "representative" screenshots.
+- **Bound the change between adjacent degrees.** A per-degree delta test on
+ position and scale catches pops that a mid-stroke still hides. Scale a fade so
+ it cannot drop by more than about `0.06` per degree, and hide only when the
+ final scaled size is below the legible threshold.
+- **No effect speck.** A primitive that fades by scale must become invisible
+ before it becomes a 2 px nub. Drive `visible` from the *final scaled size*, not
+ from the envelope alone, and hide below a legible threshold (about 0.3 of the
+ authored arrow length at a normal educational-camera distance; 0.22 is only for
+ very large arrows). Test the fade boundary as well as mid-stroke; a nub reads
+ as a rendering bug.
+- **Size against the real free volume, and check the sign.** Measure the moving
+ ceiling (valve faces, piston crown, lid) each frame, not the closed deck or a
+ cached constant. An inverted subtraction (`floor - tip` instead of
+ `tip - floor`) silently hides every arrow while all numbers stay finite. Assert
+ the available band is positive wherever a primitive is visible, and fit the
+ full tip/tail/width inside it.
+- **A flame is a kernel, not a balloon.** Anchor it at the igniter/plug and let it
+ grow only into the volume the mover releases, except that the kernel always
+ spans the fixed clearance recess at TDC where the released gap is almost zero.
+ A chamber-sized flame hides the pressure graphic, touches the piston and reads
+ as a balloon. Keep it compact, put the force arrow in the free band *below* the
+ flame, and prove the flame bounds against the crown and the head across the
+ whole event.
+- **One idea per primitive.** Three short arrows sharing an origin merge into an
+ unreadable trident; one bold arrow reads instantly. If a fan is genuinely
+ needed, separate tails and heads by at least one head-width and verify it in a
+ 1:1 crop.
+- **No ink outline on tiny FX.** An outline sized for castings swallows a thin
+ shaft and turns coloured arrows into black sticks. Effect materials stay flat
+ and un-outlined; check `outlineParameters.visible === false` and the rendered
+ colour in a crop.
+- **Lifetime is phase-bound and deterministic.** Each group has an explicit
+ window and no history dependence: visible mid-stroke, zero in every other
+ stroke, identical for the same phase in any order. Test mid-stroke counts and
+ a sweep of outside phases.
+- **A hollow outlet is one connected solid.** No floating torus as a rim and no
+ flat cap closing the bore. Lathe one continuous sleeve + rolled lip, overlap
+ the pipe, and prove with a centre-ray (passes through the opening) and an
+ annulus-ray (hits material).
+- **Every crossed fixed wall needs a real opening.** A piston, rod or shaft that
+ passes a flange needs a bored hole/slot with measured swept clearance, not a
+ shelf with a dark circle painted on it. Test the actual structural mesh against
+ every moving surface vertex at the crossing plane, at the lowest/full-travel
+ pose.
+- **Selection:** follow `Canonical educational UI and inspection contract`;
+ an explicit Inspect focus is distinct from a camera-stationary lesson step.
+- **Use the copy-in helper, not a fresh guess:** `templates/flow-primitives.js`
+ carries the +Z convention, the band fitter and the legibility gate.
+- **Regression checks for this section:** forward-axis unit test, tangent
+ alignment, per-stroke visible counts plus zero leakage, minimum legible scale,
+ a 720° vertex sweep against crown/bore/head/valve-disc/stem/plug with the live
+ lift, an adjacent-degree no-teleport bound, flame-kernel and crown bounds,
+ open-outlet and flange rays, a 48-frame contact sheet per stroke, and a
+ screenshot strip of all four strokes from two orbit angles. A missing check is
+ not a pass.
+
+### Recorded failure modes (four-stroke engine, v3.12.0)
+
+These were all present in one finished-looking scene; check for each by name:
+
+1. Reversed cone (`radiusTop`/`radiusBottom`) — arrows flowed backwards.
+2. Arrows on the centreline of solid intake/exhaust runners — invisible, then
+ faked with `depthTest:false`.
+3. Fade boundary left coloured specks (scale 0.016) visible.
+4. Arrow ceiling taken from the deck instead of the valve faces, and inverted
+ downward-room sign — pressure arrows vanished entirely.
+5. Chamber-sized ignition flame hid the pressure arrows and touched the crown.
+6. Three short pressure arrows merged into one trident.
+7. Ink outlines turned small flow arrows into black sticks.
+8. Detached torus "rim" floating off the exhaust pipe; solid cap in the bore.
+9. Solid cylinder-base flange slicing the piston and rod at the bottom of the
+ stroke — the exact "it passes through" report.
+10. Part selection changed colour but did not dim the rest or move the camera.
+11. Intake/exhaust arrows followed a spline through the valve disc — a visible
+ spear through the head. Fix: free-volume arrows, never a port centreline.
+12. Only the arrow *centre* was clamped, so heads poked through the crown and the
+ valve underside. Fix: fit the direction-dependent full extent.
+13. Two stacked compression rows overlapped into double-headed spikes. Fix: one
+ chevron per side.
+14. Arrow scales ran past `1.14` because the authored length was shorter than
+ the desired length, defeating the legibility gate. Fix: normalize length.
+15. The pressure arrow outlived the flame and pointed at nothing. Fix: shared
+ fade with the flame kernel.
+16. World-space tests applied to engine-local constants reported a phantom
+ flame-above-head violation (`+0.024` root lift). Fix: one declared space.
+17. Ignition flash at `opacity 0.95`, `scale 1.14`, `intensity 9.0` blew the
+ whole head to white for the ignition frame. Fix: capped flash.
+18. The flame faded to a two-pixel bead on the valve seat for 20° of crank
+ rotation. Fix: span the clearance recess and hide below a legible height.
+19. Four hero stills missed all of the above; the 15°-step contact sheet and a
+ 6°-step video found them. Fix: the frame-by-frame audit is the acceptance
+ gate.
+
diff --git a/references/new-subject-intake.md b/references/new-subject-intake.md
new file mode 100644
index 0000000..9475598
--- /dev/null
+++ b/references/new-subject-intake.md
@@ -0,0 +1,176 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## New Subject Intake
+
+A new subject is not a new pile of props. Before modelling, fill this sheet.
+Copy `templates/DESIGN.md` into the project and keep it in sync with the code.
+
+```
+PREMISE
+ [place] + [a repeated verb/ritual] + [who or what interrupts it] + [payoff].
+ One sentence. If it has no verb, it is a shelf model, not a diorama.
+
+CAMERA SIDE
+ Which face is +Z? Where is the threshold, the hero tower, the foreground prop?
+ Which silhouette must never be occluded from this angle?
+
+CAST SHEET
+ role | silhouette feature | locomotion | action | reaction | exit/death | signature
+ ...
+
+SYSTEM SHEET
+ loop length | three or four systems | crew | three or four visitor roles |
+ goal/disruption (optional) | economy/score (optional) | what changes
+
+BEAT SHEET (absolute seconds)
+ 0.0 establish / portal / doors
+ ... first signal, first system output, first consequence
+ ... disruption reaches the goal (or the last customer arrives)
+ ... contact / handoff / finale, residue, loop seam
+
+DETAIL BUDGET
+ systems n x parts | vehicles n | creatures/people n | props n | landmark n |
+ exits/deaths n | ambient loops n | triangle / draw-call ceiling
+```
+
+Rules that keep a new subject from becoming a blockout:
+
+- **Invent the conflict.** If the user says "a diorama of a lighthouse", decide
+ what the lighthouse does, who arrives, what goes wrong, and what the keeper
+ does about it. A subject plus a verb is a diorama.
+- **Give every machine an operator.** If a tower, loom or pump needs a crew,
+ model the crew and decide what happens when they die: the machine slows, stops,
+ or runs unmanned with a visible consequence. A gun that fires itself while its
+ crew lies dead is a ghost. If the machine is autonomous, say so in the sheet.
+- **Choose five signature moments before modelling.** Establish, first system
+ output, first consequence, goal/handoff contact, final residue. A social diorama
+ may use establish, ritual, disruption, handoff, residue. Every object earns its
+ place by serving one of those five.
+- **Stage for the hero camera.** Put the threshold and the hero action on the
+ +Z face; put tall landmarks at the back but offset in screen x so they do not
+ stack. Put one foreground prop at the near corner for depth and one mid-ground
+ prop to lead the eye.
+- **Blockout in grey first.** Boxes, cylinders and the camera, no palette, no
+ post. Shoot 1:1. If the five moments do not read in grey, detail will not save
+ them. Redesign the staging, not the textures.
+- **Name every hero object.** `totem`, `hayCart`, `gatehouse`, `troll`, not
+ `prop12`. Unnamed objects become clutter because nobody owns their silhouette.
+- **One boss goal, one tower verb.** The boss must visibly act on a place
+ (door, bridge, pump, nest); the tower must visibly act on a target (pierce,
+ blast, freeze, chain). Repeat the verbs with variation, not new nouns.
+- **Write the QA timestamps now.** Pick the five frames you will inspect before
+ you build them. If you cannot name a timestamp for a beat, it is not staged.
+
+### Reference Density
+
+The Hollow Toll shipped at this density. Use it to calibrate a new subject; a
+smaller subject should have fewer objects at the same detail per object, not
+fewer details per object.
+
+| Measure | Value |
+| --- | --- |
+| Slab | 21 x 14 x 0.42 m, 64-colour palette |
+| Towers | 4 + 2 gate cannons |
+| Species | 5 (goblin, orc, slime + split, bat/imp, troll) |
+| Units | 42, one boss |
+| Combat events | 527 |
+| Tower shots | 183 |
+| Scene meshes | ~3,100 |
+| Triangles | ~164,000 |
+| Scene draw calls | ~1,700 at 1440 x 900 |
+| Textures | 5 |
+| Loop / sim | 46.0 s at 40 Hz pre-sim |
+| Standalone | ~783 kB with three.js inlined |
+
+A 12 x 9 m scene with two towers and three species should land around
+1,000 to 1,600 meshes and 60 to 100k triangles. Raw count is not the goal;
+the detail per hero object and the number of readable beats are.
+
+### Worked Example: The Hollow Toll
+
+This is the reference build the numbers above come from. Read it as a calibration
+of **what "finished" looks like**, not as a scene to copy.
+
+- **Set.** A 21 x 14 m slab, purple portal at the back-left, winding road, goblin
+ camp, moat and drawbridge, gatehouse at the near-right. Four towers and two
+ gate swivels; keep gate faces +Z.
+- **Cast.** 14 goblins, 4 orcs, 7 slimes plus 10 split slimelets, 6 imps and one
+ Toll-Troll: 42 units, 5 death grammars, one boss goal.
+- **System.** 46 s loop at 40 Hz, 527 events, 183 shots. Ballista single target,
+ bombard splash, frost lance channel, tesla chain, gate swivels on the last
+ stretch. The troll reaches the gate at 38.6 s and hits it eight times.
+- **Detail.** The gatehouse has a plinth, two towers, crenellations, a gate arch,
+ door leaves with cracks, two swivel cannons, banners and torches. The skull
+ warning tree has a trunk, fork, trophy board, horned skull, rope collar, bone
+ chimes, rags, tally marks and roots. The hay cart has a bed, slats, two spoked
+ wheels with iron tyres, corner straps, three tied bales, loose straw, a
+ pitchfork, a sack, a rag and two shafts.
+- **Animation.** The frost spire pulses, flares at the crystal, holds a scrolling
+ band lance, ramps heat, and shuts off on the target's death. The troll stops
+ outside the threshold, turns three-quarter, swings an iron-banded maul, and
+ drives the door flash, shake and cracks from the same gate-hit timestamp.
+ Every species has its own collapse and debris.
+
+Fixes that became rules in this file:
+
+| Report | Root cause | Rule |
+| --- | --- | --- |
+| "rocks flying out of the entrance" | camp smoke billboards above the portal | clear the threshold of smoke, props and fireflies |
+| troll inside the gatehouse | stop at `length - 1.05`, body through wall | stop at body depth + weapon reach; keep the door visible |
+| club looked like a rock | end-on pose, haft hidden, no bands | yaw 0.35 rad, build haft + bands + studs, sync contact |
+| beam had a black segment | black backing plate in the additive beam texture | clear the canvas; transparent gaps, never black |
+| deaths were spheres/rocks | generic burst | species collapse + debris + dropped gear + residue |
+| skull tree looked like a monster | a second totem overlapped the tree | one landmark per silhouette; mount the skull on a board |
+| cart looked like a blob | pale spheres in an open box | five-part prop: bed, slats, wheels, load, tools, story |
+| standalone broke over `file://` | `String.replace` expanded `$&` in the bundle | function replacer; test the standalone |
+
+A new subject should copy the **density and audit discipline**, not these nouns.
+A lighthouse, market or launch pad needs the same number of readable systems,
+the same five animation layers and the same proof frames.
+
+### Worked Example: Night Market
+
+The social-scene calibration: no combat, no boss, no deaths. A food truck, a
+queue, a courier, one scooter and a cat. It proves the same discipline applies to
+a life scene.
+
+- **Set.** 21 x 14 x 0.42 slab; truck at (0.15, -3.35) with the hatch facing +Z;
+ counter at z 1.10; parked scooter at (5.55, -0.72) facing +Z; bench, rail,
+ lamps, bins, service block behind. Camera azimuth 45, elevation 33, fov 20.5,
+ fill 0.93.
+- **Cast.** Cook, cashier, customers A/B/C, courier, late customer D, cat. The cat
+ is an actor with its own idle, walk, sit and tail loop, not set dressing.
+- **Systems.** Grill flare, order rail, bag pass, scooter dispatch. Four readable
+ systems, no towers.
+- **Loop.** 46 s at 40 Hz. Queue forms 0–16 s; four paper bags + one insulated
+ bag; courier loads 21.2–22.5, mounts 22.7–23.5, departs 23.5–27.3; D arrives
+ 26.0–33.4, last bag 34.0, exits 34.8; quiet seam 40–46.
+- **Scale.** The user asked for 30% smaller. The fix was `subjectScale: 0.70`
+ after the fit (`distance = fit / 0.70`), not scaling the slab, cast or canvas;
+ geometry scaling breaks the world clip and shadow maps, and shrinking the
+ canvas breaks the 1:1 crops. Backing buffer 2x CSS for the faces, CSS
+ downscale.
+- **Proof.** Nine 1280x800 frames plus two close strips: courier mount, D walk.
+ The strip camera was a fixed side view, not the hero camera.
+
+Fixes that became rules in this file:
+
+| Report | Root cause | Rule |
+| --- | --- | --- |
+| "the building bottom/right is cut" | slab edge/backdrop closed too tight | close side walls and undersides; camera fit includes the slab corners |
+| "bike lights look unnatural" | large additive disc | emissive lens + small halo; cone only at night |
+| "doesn't put the box on the bike" | prop teleported from hands to crate | carry in world space from wrists; lower over the rim; release with a beat |
+| "doesn't sit on the bike naturally" | car seat/root constants reused | measure scooter seat; board for the left boot; abduction swing; bars to hands |
+| "the human/cat doesn't look human" | sphere head, cap at theta 1.85 | skull+jaw head, hair cap 1.22, ears/brow/lids, tapered limbs |
+| "carry the bags more human-like" | prop at root, hands nearby | two-hand hold at the prop's top, object origin at its bottom |
+| "no text outside the diorama" | DOM overlay on the paper | empty-paper rule; copy on modelled signs only |
+| "30% smaller" | scaling the scene | move the camera; keep world clipping and shadow scale |
+| "leg swings over the handlebar" | hip X flexion for a side mount | abduct with hip Z; knee tucked; root arc 0.1–0.2 m |
+| "single human slides near the shop" | standing gesture blended during walk | gate gestures on `!state.moving`; serve after arrival |
+
+A new subject should copy the **timing discipline and contact logs**, not the
+food truck. A pool, a station or a bakery needs the same queue/service,
+carry/load and close-up proof.
+
diff --git a/references/numbers-that-make-it-read.md b/references/numbers-that-make-it-read.md
new file mode 100644
index 0000000..73f2eab
--- /dev/null
+++ b/references/numbers-that-make-it-read.md
@@ -0,0 +1,48 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Numbers That Make It Read
+
+| Knob | Value | Why |
+| --- | --- | --- |
+| Camera | fov 20.5, az 45, elev 33 | long lens, near-ortho miniature |
+| Framing | `fillX 0.84–0.94`, `fillY 0.86–0.94` | fit margin only: slab plus landmark tops |
+| Subject scale | `1.0`, or `0.70` for 30% smaller | post-fit camera multiplier; never geometry |
+| Camera distance | solved, 5 to 300 | bisection; actual distance = fit / subjectScale |
+| Post buffer | 1× CSS; 1.2–1.5× for a small subject; 2× faces | extra detail without resizing the diorama |
+| Palette | 64 entries (any N, but the shader array and loop must match) | skin, stone, asphalt, glass, livery, props |
+| Dither | `d*(0.0012 + 0.019*gate) + sparkle*0.0012` | stipple in ramps only; gate = edge |
+| Ink | `smoothstep(0.13,0.34,edge)`, mix 0.62 | outline without scribble |
+| Palette tie-break | `secondD-bestD < 0.0005` → lighter | flat surfaces come out flat |
+| Sun | `0xfff8ee` at 3.3, hemi 0.24, fill 0.46, env 0.18 | hard shadows, cool fill |
+| Shadow cam | ±13, near 4, far 70, 2048 map, bias -0.00022 | tight around the whole slab, no acne |
+| Figure | 1.69 m, hip 0.86, head 0.584 | toy proportions that read |
+| Car | L 4.4, W 1.86, belt 0.90, roof 1.44 | door 1.30, leaf sits between 0.34 and 0.90 |
+| Scooter | wheel r 0.26, board 0.30, seat 0.83, bars 1.06 | boots and hands land on built surfaces |
+| Loop | 41 to 47 s | one robbery beat plus police, and a quiet seam |
+
+The table mixes two different kinds of number, and treating them alike is how a
+new subject comes out wrong.
+
+**Pixel-preset invariants.** The camera/palette/post values here belong to the
+pixel look, not approved stroked-toon builds. They hold on every pixel subject: azimuth 45,
+elevation 33, fov 20.5; one deterministic reset hero pose for QA plus user orbit; palette discipline
+(every material samples a palette entry, the shader array length equals the
+palette length); gated dither, ink at 0.13/0.34 mixed 0.62, the palette tie-break;
+the rig's proportions and joint signs; 2048 shadow map with a frustum tight to
+the slab; everything a pure function of `t`.
+
+**Calibrated.** Measured against one subject and only evidence for it: palette
+count (64 for the bank job, 66 here), buffer size and renderScale (1×/1.25×/2×),
+`fillX`/`fillY`, `subjectScale` and the camera `size` divisor, slab dimensions
+and deck height,
+loop length, sun and hemisphere intensities, and every prop dimension in the
+vehicle and scooter rows. Re-derive these per build: start from the value, then
+look at a screenshot and change it.
+
+A scene may change any calibrated number if the subject needs it; change the
+template and `DESIGN.md` in the same edit and record the reason. A template that
+silently uses a 2x different sun is worse than no template, because the next
+reader trusts it.
+
diff --git a/references/one-prompt-one-build.md b/references/one-prompt-one-build.md
new file mode 100644
index 0000000..f003f08
--- /dev/null
+++ b/references/one-prompt-one-build.md
@@ -0,0 +1,207 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## One Prompt, One Build
+
+When the user gives a subject in one line, treat it as a **commission**, not a
+questionnaire. Make the creative decisions, state them in one short assumption
+line, and build the whole diorama. Do not stop at a plan, a blockout or a design
+sheet and wait for approval.
+
+The only reasons to ask are credentials, a destructive action, a path that
+would overwrite the user's work, **or the `Render Preset Gate`**. That gate is a
+deliberate exception to autonomous assumptions: one question, once per project,
+before the first mesh. Everything else is a default.
+
+### Step 0, before the assumption line
+
+Ask the `Render Preset Gate` question first, then run the three lookups in
+`Research Before You Model`:
+
+1. Step the real subject into frames and write down its motion grammar.
+2. Walk the sourcing ladder for every hero asset (disk, CC0, CC-BY, hand-build),
+ with a `CREDITS.md` line per import and the search in `refs/SOURCES.md`.
+3. Stand up the capture loop (`qa/shoot.mjs`, a frozen `?t=` frame, a contact
+ sheet) so every beat can be reviewed as a picture.
+
+For an invented subject, spend the same time on reference density instead: find
+three images that agree on what the place looks like, list the props they share,
+and build those before any invented detail.
+
+### The default commission
+
+Use these unless the prompt explicitly says otherwise:
+
+| Knob | Default |
+| --- | --- |
+| Slab | 21 x 14 x 0.42 m; 16 x 12 for one room, 24 x 16 for a street, port or launch pad |
+| Loop | 46 s at 40 Hz; one readable cycle plus a quiet seam |
+| Palette | 64 entries |
+| Systems | 4 defences/machines/service stations/attractions; 3 is acceptable, 6 is the ceiling |
+| Cast | 4 to 6 roles total, including one disruption; 2 ambient loops |
+| Props / landmarks | 2 hero props, 1 landmark, 3 to 6 supporting props |
+| Hero detail | every hero object meets the Detail Bar |
+| Animation | every hero actor has all five layers |
+| Output | `index.html`, `<slug>.html`, `README.md`, `DESIGN.md`, `src/`, `dist/` |
+| Path | `<cwd>/<slug>/` unless the user named a folder |
+| Minimum viable | 3 systems, 3 roles + 1 disruption, 1 hero prop + 1 landmark, 30 s loop; still passes the bars |
+
+State the assumption in one line before coding:
+
+> Assumption: market archetype, 46 s loop, 4 service systems, 6 roles plus a
+> late customer, 21 x 14 slab, 64 colours. Say if you want a different scale or
+> genre.
+
+That line is the contract. State it, then continue in the same turn; do not wait
+for approval. It gives the user a chance to redirect after seeing the assumption,
+without blocking the build.
+
+### Long builds and context
+
+A scene like this runs for hours of agent time and thousands of messages: render
+loops, one screenshot per beat, one probe per bug. The session will need to
+compress its context, more than once, and compaction is lossy. Build so that a
+compact does not cost you the work:
+
+- **State lives in files, not in the chat.** `DESIGN.md`, `refs/SOURCES.md`,
+ `CREDITS.md`, `qa/report.json` and the beat table in `stage.js` must carry every
+ decision. If a fact only exists in a message, it is already gone.
+- **Write the rule down when you learn it.** A fix found at 3 a.m. is worthless if
+ it only exists in the transcript; put it in the skill or a comment next to the
+ code, with the reason.
+- **Name the shots.** `qa/frames/<entity>/sheet.png` and `shots/t-12.40.png` are
+ stable handles a post-compact agent can re-read without rerunning anything.
+- **Re-derive, do not remember.** After a compact, re-run `frames.mjs` and
+ `shoot.mjs` rather than trusting your summary of what the last frame looked
+ like: the numbers are cheap, and a confident memory of an old build is the
+ most expensive thing in the session.
+- **Keep one open task list** in the repo (a `TODO.md` or an issue) so the thread
+ that survives compaction is the plan, not the chat.
+
+### Reading the prompt
+
+| Prompt shape | What to do |
+| --- | --- |
+| one noun ("a bakery") | pick the closest router row; invent the verb, disruption and goal |
+| one sentence ("a lighthouse under siege") | take its nouns and verbs literally; fill the missing cast/systems from the router |
+| a reference image | match its composition, camera side and palette first; keep this skill's detail/animation bars |
+| "like X but Y" | reuse X's structure, replace the subject and the detail anchors; do not copy X's nouns |
+| "make it detailed" | use the full Detail Bar and five animation layers; do not add more systems |
+| "keep it simple" | cut systems and cast, not detail per hero; two rich objects beat six blockouts |
+
+A prompt that names only a place is still a commission. Decide what the place
+does, who arrives, and what goes wrong. State the assumption and build.
+
+### The scene router
+
+Pick the closest row. Do not invent a new genre from scratch unless none fit.
+
+| If the prompt is... | Systems (3–5) | Cast | Goal / disruption | Detail anchor |
+| --- | --- | --- | --- | --- |
+| defence, siege, castle, base, zombies | 4 towers + gate guns | defenders, 4 species, boss | boss reaches the gate | gatehouse |
+| heist, bank, museum, casino | drill, lasers, cameras, getaway | 3 crew, guards, manager | vault opens / escape | vault door |
+| market, kitchen, bakery, cafe, food truck, night market | stalls, ovens, prep, pass, dispatch | vendors, cooks, cashier, courier, customers, inspector | closing time / service rush / last bag | counter, hatch or oven |
+| laundromat, workshop, gym, repair shop, arcade | washers, dryers, benches, tools, machine slots, ticket rail | folder, attendant, customer, courier, cat | last load / closing / power cut | machine bank or workbench |
+| launch, factory, port, mine | gantry, press, crane, conveyor | crew, inspector, cargo | launch / ship / lift | gantry |
+| aquarium, pool, harbour, reef | filters, pumps, slides, lights | fish, swimmers, diver, lifeguard | feeding / party / storm | reef or tank |
+| station, airport, bus, hotel | signal, platform, desk, luggage | commuters, guard, porter | last departure | clock |
+| festival, temple, carnival, funeral | stage, rides, altar, procession | performers, crowd, official | climax / storm | big top or altar |
+| farm, garden, safari, nature | irrigation, harvester, weather vane | animals, farmer, crows | harvest / storm | barn |
+| home, shop, library, workshop | rooms, counter, shelves, tools | family, clerk, customer, pet | opening / closing | window |
+| arena, battle, mech, gladiator | traps, weapons, doors, lifts | fighters, champion, beast | champion enters | gate |
+
+If none fit, use the universal shape: **place + repeated ritual + interruption
++ consequence**. Give it 3 to 5 systems, 4 roles and one goal. A quiet subject
+still needs a verb: a library needs a closing, a bakery needs a service, a
+lighthouse needs a sweep that fails.
+
+### If the router misses
+
+Do not freeze. Answer four questions about the noun:
+
+1. **What does this place produce or repeat?** Bread, light, trains, fish, money,
+ quiet, laundry, coffees.
+2. **Who operates it?** Baker, keeper, guard, diver, clerk, mechanic.
+3. **What interrupts the output?** A critic, a storm, a thief, a shutdown, a
+ delivery, a leak, a closing-time crowd.
+4. **What is the visible consequence?** Burnt batch, dark lens, missed train,
+ flooded tank, empty till, closed sign.
+
+Those four answers give you the system, cast, goal and residue. Then use the
+five beats: **normal output → first interruption → escalation → goal contact →
+residue and seam**. No combat required. A deadline, an inspection, a storm or a
+closing bell is a valid boss.
+
+Worked one-prompt example:
+
+> "a tiny bakery at closing time"
+
+- Archetype: market/kitchen. Slab 16 x 12. Loop 42 s.
+- Systems: oven, proofing rack, counter, till. Cast: baker, apprentice, last
+ customer, food inspector (the disruption).
+- Goal: the inspector reaches the counter before the last loaf is sold.
+- Beats: 0 s oven glow and bread out; 8 s first customer; 16 s inspector at the
+ door; 26 s last loaf contested; 34 s sign turns, flour settles, cat sleeps.
+- Detail anchors: oven door (hinges, soot, peel), bread rack (trays, crumbs,
+ cloth), counter (ledger, bell, worn edge), inspector's clipboard.
+- No towers: use machine grammar for the oven and till; field audit for the
+ oven's heat; death/exit for the inspector's departure.
+
+### The autonomous pass
+
+1. **Interpret.** Pick the archetype; write the assumption line; fill
+ `DESIGN.md` yourself. Do not ask the user to fill it.
+2. **Blockout.** Grey slab, camera, five beats at 1:1. No palette, no post, no
+ materials. If the beats do not read, restage before adding detail.
+3. **Presentation.** Palette, light, post, ink, dither, camera solve.
+4. **Set and props.** Landmark, two hero props, supporting dressing. Clear the
+ 2 m threshold. No duplicate silhouettes.
+5. **Cast and detail.** Rig the cast; apply the Detail Bar to every hero object.
+ Cut a role before cutting detail per role.
+6. **Animation and systems.** Five layers per hero; tower acquire/fire/impact/
+ recovery; field ramp/area/affect/decay; machine input/motion/output/residue.
+7. **Effects and residue.** Contact shadows, species deaths, dropped gear,
+ stains, ambient loops, loop seam.
+8. **QA and package.** Detail/animation audit, numbers, 1:1 crops, standalone
+ `file://`, README and `DESIGN.md` agreeing.
+
+If time is tight, **cut the number of systems or actors, never the detail per
+hero or the animation layers**. Two detailed towers with five layers beat six
+blockout towers with one fire animation.
+
+### Efficiency rules
+
+- **One project, one build loop.** Scaffold once, then build, shoot and fix in
+ place. Do not rewrite the entry file for a detail that lives in a prop module.
+- **Build for orbit inspection.** Prioritise the hero view, but construct every exposed back, support, cavity and joint coherently.
+- **Cut systems before detail.** A tight build with two rich towers and five
+ animation layers reads better than six thin towers with one recoil.
+- **Use the templates.** Camera, post, palette, lighting, the cast rig and the
+ detail helpers are already solved; do not re-derive them from prose.
+- **Shoot known timestamps.** Freeze at the five beat times and the five QA
+ frames; do not scrub for a good frame.
+- **Package last, once.** Build the standalone only after the QA frames pass;
+ rebuilding it after every tweak wastes the pass.
+
+### One-prompt acceptance
+
+Do not report "done" until all of these are true:
+
+- `DESIGN.md` exists and matches the build.
+- Five beats have timestamps and proof frames.
+- Every system has events; every actor has a death, exit or residue.
+- Each hero has three detail passes and at least one story detail.
+- Each hero actor has idle, locomotion, action, reaction and death/exit.
+- Every carry, handoff, load and mount has a contact timestamp and a nine-frame
+ strip; palms are on the prop and boots are on the vehicle.
+- A queue serves after arrival, never before; no standing gesture is blended
+ into a walking root.
+- No generic sphere burst, floating prop, clipped landmark or beam on a target
+ that has already expired.
+- No fixed deck prop, ammo store, tool or crew member moves with a turret,
+ flywheel or machine pivot.
+- Standalone opens over `file://` with zero console errors.
+- The final message gives the path, loop length, system/shot counts and the QA
+ frames, not a request for feedback.
+
diff --git a/references/optional-pixel-stroke-hybrid.md b/references/optional-pixel-stroke-hybrid.md
new file mode 100644
index 0000000..cc5b65d
--- /dev/null
+++ b/references/optional-pixel-stroke-hybrid.md
@@ -0,0 +1,12 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Optional Pixel + Stroke Hybrid
+
+`pixel-stroke` is a third style, not the pixel default, and it is selected through the single `Render Preset Gate` question — never inferred, never switched to later without a new answer. Record the answer and do not offer it again during the build. Rotation is mandatory regardless of the answer.
+
+Copy `templates/pixel-stroke.js` plus `templates/stroked-toon.js`. Create WebGLRenderer with antialias false, alpha true. Use `createPixelStroke(renderer, {width:320,height:200})`, its `toon`/`flat` material factories and `render(scene,camera)`. Resize the low-resolution target explicitly with `look.setSize(bufferW,bufferH)` while sizing the renderer to the display aspect; keep target aspect aligned to viewport/camera. Toon lighting/materials plus selective geometry OutlineEffect render into that target, then ONE nearest-neighbour fullscreen upscale. Do not run PixelPost, Sobel ink, a second outline pass or CSS blur over it. Native-resolution DOM UI is outside the target and must remain crisp.
+
+OutlineEffect thickness is a projected effect parameter, NOT a CSS-pixel width. Rasterisation happens at the low-resolution target: a one-target-pixel contour becomes approximately `displayWidth / targetWidth` CSS pixels after upscale (analogous vertically). A thinner subpixel outline can disappear or flicker; measure target and screen crops at desktop/phone, adjust target resolution and selective material stroke together. Disable outlines for inward cavity surfaces, liquids, films, transparent glass, vapour and contact patches; do not double edges. For native toon, measure the native-DPR render instead. Free orbit, construction, manifest and QA requirements are unchanged.
+
diff --git a/references/optional-stroked-toon-preset.md b/references/optional-stroked-toon-preset.md
new file mode 100644
index 0000000..3ea9eca
--- /dev/null
+++ b/references/optional-stroked-toon-preset.md
@@ -0,0 +1,121 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Optional Stroked-Toon Preset
+
+### 1. Chosen through the gate; preserve the default
+
+Use **stroked toon / illustrated miniature** (`stroked-toon`) only as resolved by
+`Render Preset Gate`; retain its recorded answer during repairs. The gate owns
+consent/default/recording rules—do not ask a second style question here. This
+preset changes presentation, not the subject or choreography; never import
+coffee props or workshop colours into an unrelated scene. Record paper/frame
+and camera choices alongside the preset in `DESIGN.md`.
+
+**Precedence when approved:** the recipe below replaces the pixel-only camera,
+white/no-plinth, palette-snap, edge-shader, Bayer, empty-paper and buffer rules
+where they conflict. Do not combine both post pipelines by default. A thin
+bevelled slab edge and a restrained optional figure frame/title/hint/readout are
+allowed. Locked animation framing, deterministic time, clipping/containment,
+contacts, silhouette readability, detail and animation QA still apply. Orbit is mandatory for all presets; it needs no separate approval. Character
+proportions remain subject-appropriate; don't force toy people into every scene.
+
+### 2. Render solid illustrated parts, not a pixel filter
+
+Copy `templates/stroked-toon.js` into the project. It exports an opt-in Three.js
+helper; it has no dependency on Anatomy CSS, SVG, fonts or the coffee rig.
+
+- **Native crisp rendering:** antialias on; device pixel ratio capped at 2;
+ sRGB output, `NoToneMapping`. Disable PixelPost, palette quantisation, dither,
+ Sobel ink and CSS `image-rendering: pixelated`. Keep a small authored colour
+ family, not a requirement that every final shaded pixel equal a palette entry.
+- **Four-step surface shading:** `MeshToonMaterial` with a 4×1 RedFormat ramp,
+ bytes `[68, 122, 184, 246]`, nearest filters, no mipmaps. These are starting
+ values, not physical light calibration. Give materials distinct local colours:
+ warm/cool off-white, desaturated object hues, dark structure, metal or timber,
+ one restrained accent. Adapt to the setting; warm cream is optional.
+- **Selective fine contours:** Three.js `OutlineEffect`, warm charcoal rather
+ than pure black. Start thickness 0.0024–0.0038 (effect units, not world units
+ or pixels). At the final viewport, aim for a roughly 1–2 CSS-pixel hero contour
+ with finer subordinate edges; tune by screenshots at desktop and phone sizes.
+ Broad silhouettes can be heavier, tiny fasteners lighter. Do not add wireframe
+ or stroke every triangulation. Flat decals, liquid films, transparent glass,
+ steam, contact patches and inward cavity surfaces normally have no outline.
+- **Light for volume:** one warm upper-side key with shadows, a broad hemisphere
+ and weaker cool fill. The helper starts key 2.55, hemi 1.55, fill 0.72; measure
+ and tune for the scene, especially night/water. Tight shadow bounds, 2048 map,
+ PCFSoft shadows, low bias, no acne. Combine cast shadows with small radial-alpha
+ contact patches only where needed; no overlapping dark discs or false rings.
+- **Model the edge:** modest bevels on casing, slab, rails and props; profile
+ lathes for vessels; cylinders with enough segments to read round. Avoid a
+ melted soft-plastic scene or polygonal mugs. Separate outer silhouette from
+ cavity shading: real wall thickness and a bottom, one-sided inward surface,
+ no expanded backface stroke through the interior. Glass must reveal contents;
+ liquid stays inside the wall through the whole fill range. Paper/grain and
+ lighting gradients are allowed; they must not obscure part boundaries.
+- **Compose and inspect:** a long-lens three-quarter view (start fov 26,
+ azimuth 38°, elevation 27.5°), fit to full animated bounds, room for the tallest
+ object and controls. These are a starting point, not a mandatory angle for all
+ subjects. Free user orbit is mandatory in every preset: use OrbitControls,
+ bounded zoom/polar angles, reset view and no pan; detail all exposed sides. No auto-spin.
+ Keep UI outside the subject, subtle, readable and keyboard-accessible. A title,
+ hint and actual live state are optional figure furniture, not part of the 3D
+ material system and not an excuse to import unrelated Anatomy CSS.
+
+Minimal integration after user confirmation:
+
+```js
+import * as THREE from 'three';
+import { createStrokedToon } from './core/stroked-toon.js';
+
+const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
+const look = createStrokedToon(renderer);
+renderer.setSize(width, height, false);
+const shell = look.toon(0xc4cbb4);
+const inner = look.toon(0xb8bfaa, { outline: false });
+// Add subject-specific lighting and objects; do not also call PixelPost.render.
+look.render(scene, camera);
+// On resize: renderer.setSize(width, height, false); update camera projection.
+```
+
+### 3. Match the craft and detail, not just the shader
+
+Use the Detail Bar's silhouette → construction → story passes, plus this close-up
+acceptance bar. Detail is structural, not a quota of randomly scattered meshes.
+Visual calibration references are `media/stroked-toon-reference.jpg` (overall
+framing/material hierarchy) and `media/stroked-toon-service-reference.jpg`
+(assembly detail). Read them when reproducing this look, but translate their
+craft to the requested subject rather than copying their props or palette.
+The coffee-rig repair is the evidence: a floating lever needed a pedestal;
+interior parts needed supports and connected runs; a ring under the scale read
+as a detached base; outlined cavities and oversized liquid surfaces looked broken.
+
+| Pass | Requirement (life/story rows are narrative-only) | Translate to the subject |
+| --- | --- | --- |
+| Structure | Primary mass, supporting assembly, secondary panels/members | trunk/roots/branches; hull/ribs/deck; torso/joints/gear; wall/roof/trim |
+| Attachments | Every small part has a visible or explainable seat, joint or support | leaf stem, rope knot, hinge pin, bracket, cuff, axle, strap, fastener |
+| Functional detail | Inputs, outputs and working parts connect; contents fit containers | rooted irrigation, connected hoses, docked lines, harness to buckle, wheels to hubs |
+| Surface hierarchy | Large readable forms, medium assemblies, sparse microdetails | seams, fittings, latches, bark scars, stitches, labels, scales; not uniform noise |
+| Nearby life | 3–6 supporting props in purposeful clusters when space/brief permits | campsite kit; cargo/lifebuoys; books/blanket; tools/materials; tracks/nests |
+| Story | At least one specific used/changed detail per hero | wear at contact, repair, folded cloth, spilled contents, missing tile, footprint |
+
+Start with 8–15 meaningful pieces for a small supporting prop and 30–60 for a
+hero; a complex cutaway may need 100–250+ small pieces across its subsystems.
+These are planning ranges, not mesh-count acceptance tests. Reuse geometry and
+materials, merge static siblings only after visibility/animation ownership is
+settled, measure draw calls/fps and reduce invisible detail before construction.
+Preserve clear working paths and negative space. "Feels empty" calls for a few
+related clusters at varied heights, not filling every inch of deck.
+
+**Proof before delivery:** one whole-scene desktop and phone frame; a 1:1 hero
+crop; a cavity/contact crop if relevant; an action strip at known times. Always inspect front, service/back and high angles. Check outline
+width and tiny-part legibility; no floating supports, disconnected endpoints,
+false residue hoops, filled-in hollows, liquid clipping, or outlines on vapour.
+Scan finite vertices, contacts/clearances and moving bounds; check the actual
+readout against the frozen time. Keep `freeze(t)` and reduced-motion support.
+Do not call a symbolic cutaway a verified engineering design. Use the existing
+QA harness for shared checks, but disable or replace its pixel-palette/dither,
+empty-white-paper and fixed-angle assertions for this preset explicitly; do not
+silence unrelated failures. Record the preset and which checks apply.
+
diff --git a/references/palette-and-the-post-pass.md b/references/palette-and-the-post-pass.md
new file mode 100644
index 0000000..3a6f8ad
--- /dev/null
+++ b/references/palette-and-the-post-pass.md
@@ -0,0 +1,82 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Palette And The Post Pass
+
+`templates/post.js` renders the scene to an offscreen target, then a full-screen
+shader turns it into pixel art. Order matters; each stage assumes the last.
+
+1. **Coverage gather.** ~12 taps in a small disc read alpha, so the silhouette can
+ be softened and stippled without blurring the interior. The target is
+ transparent outside the slab.
+2. **Composite onto paper.** `mix(vec3(1.0), c, smoothstep(0.26, 0.72, cov))`.
+3. **Gamma.** `c = pow(c, 1/2.2)`. The target is linear; skip this and the frame is
+ dark and muddy, which reads as a lighting bug.
+4. **Grade.** Saturation 1.07 and contrast 1.028 *before* quantising, or the snap
+ flattens everything to mid tones.
+5. **Ink.** Neighbour luma differences, `edge = max(abs(d))`, brought to display
+ scale with `pow(edge, 0.4545)`, then
+ `ink = smoothstep(0.13,0.34,edge) * smoothstep(0.20,0.55,cov) * (1 - smoothstep(0.86,0.985,cov))`
+ mixed 0.62 toward `vec3(0.085,0.082,0.076)`.
+6. **Dither, gated.** `d = bayer8(gl_FragCoord.xy) - 0.5`,
+ `gate = smoothstep(0.004,0.055,edge)`,
+ `c += (d*(0.0012 + 0.019*gate) + sparkle*0.0012) * uDither`. Keep `uDither` as a
+ uniform: it is the fastest way to prove whether a speckle is the dither.
+7. **Palette snap.** Nearest entry with channel weighting `(1.0, 1.12, 0.93)` so
+ greens do not beat skin. Keep the runner-up and break near-ties toward the
+ lighter entry, or a surface halfway between two entries flips entry per pixel
+ on the dither noise and stipples a whole pavement.
+8. **Rim dither.** Where coverage is 0.78 to 0.995, threshold against Bayer so the
+ cut-out edge is stippled, not anti-aliased.
+
+The palette length is a shader constant: `uniform vec3 uPalette[N]` in the
+fragment source and the JS array must be the same length. A mismatch loses the
+last colours or reads out of bounds, and the symptom is a colour that "does not
+exist in the palette" appearing on screen.
+
+### Tuning Table
+
+| Symptom | Cause | Fix |
+| --- | --- | --- |
+| Water looks like TV static | dither ungated | add the edge gate |
+| Frame dark and muddy | missing gamma | `pow(c, 1/2.2)` before grade |
+| Everything mid-grey | no grade before snap | saturate 1.07, contrast 1.028 |
+| Scribble outlines | ink threshold too low | 0.13 / 0.34 |
+| Missing outline on figures | rim suppression too wide | narrow to 0.86 / 0.985 |
+| White speckle on flat deck | material grain aliasing | cut grain, not resolution |
+| Bands with hard edges | palette hole | add 4 to 6 intermediate entries |
+| Speckle only where a tone sits between entries | palette tie | break near-ties toward lighter |
+| Speckle at zero dither | sub-pixel geometry | widen detail to ~1.5 px or delete it |
+| Beam goes flat or vanishes on paper | additive white over white | saturated palette core + dark halo; fade before the edge |
+| Glow disappears after the snap | sub-pixel or pure-white FX | widen to 2 px+, use a palette entry, add a contour |
+| Beam ends in a hard vertical cut | world clip plane on a read-through FX | taper intensity to zero before the slab edge |
+| Flame reads as a grey smudge | normal-alpha smoke over a bright source | lighten/remove smoke in the flame corridor, draw flame last |
+
+Isolate noise in this order and stop at the first that removes it: dither
+uniform to 0 → widen or delete sub-pixel geometry → disable `shadowMap`. Judge on
+a 1:1 crop; a downscaled preview softens all three into "texture".
+
+### Resolution
+
+Default: `setSize` renders one target pixel per CSS pixel, capped by `maxDim`
+(1600), and CSS `image-rendering: pixelated` handles the upscale. The chunky
+look comes from the palette snap and the ink, not from a low buffer.
+
+When the diorama is deliberately small on the page (`subjectScale` under ~0.8),
+raise the buffer **a little** instead of enlarging the subject:
+`new PixelPost(renderer, 2000, 1.25)` renders 1.25 target pixels per CSS pixel;
+at a 1312 × 760 CSS canvas that is a 1640 × 950 buffer, CSS still 1312 × 760.
+The post pass quantises at the finer grid and the browser downsamples; the page
+size, camera solve, slab and clip do not move. 1.2–1.5× is the useful range; 2×
+on a full arena is usually a frame-rate tax, not more art. Log `post.size` and
+`canvas.getBoundingClientRect()` and check a 1:1 crop for shimmer.
+
+For faces and close-up contact beats, use `renderScale: 2` and
+`image-rendering: auto` (not pixelated), with `maxDim` high enough (2400) to
+avoid the cap. The post pass still quantises at 2×; the CSS downscale is a clean
+box filter, not a change to the art. Keep the CSS size as the layout size so the
+camera solve and the 1:1 QA crops stay comparable. Re-run the portraits after
+any resolution change: raising the buffer exposes hats, stripes and noses that
+hid at the old grid.
+
diff --git a/references/pipeline.md b/references/pipeline.md
new file mode 100644
index 0000000..3b3cb2d
--- /dev/null
+++ b/references/pipeline.md
@@ -0,0 +1,16 @@
+# Construction-first pipeline
+
+This is the operational order for all profiles/presets. The former palette-first sequence is retained only in the 3.18 backup, not as an alternate workflow.
+
+1. Resolve scope, profile and render preset. Read only routed recipes. Fill the compact DESIGN inventory from whole-object references.
+2. Dimension the site/object: units, top-surface datums, hierarchy, lots and full envelopes, access paths and interfaces.
+3. Build a neutral representative complete assembly with native-axis-safe helpers. Inspect grey front/side/rear views and measure contacts, openings and neighbour clearance.
+4. Replicate from shared data/frame tables. Validate every instance and required member, including rear/exterior/attachments.
+5. Evaluate mechanism or narrative motion from one driver. Test extrema, contacts, transitions, seam and closest-approach intervals; constrain full geometry, not centres.
+6. Add meaningful structural/functional detail, then signature narrative/educational detail. Recompute envelopes and contacts after canopies, trim, fittings and moving pieces are added.
+7. Apply one selected presentation recipe. Pixel uses palette/post; toon uses native smooth contours and four-tone materials; hybrid composes toon with one nearest-upscale low-res pass. Fit the real complete/swept subject to the measured UI-safe stage.
+8. Bind semantic selection ownership, live local callouts, constrained FX and profile UI. Materials must restore exactly; labels/ports/emitters follow their source transforms.
+9. Run geometry tests with required negative injections; render hero/reverse/high/critical-interface and selected/restored phone views; test pointer/keyboard/control lifecycles, deterministic freeze and standalone loading.
+10. Build the final artifact, identify its loaded hash, rerun affected checks and reconcile DESIGN/readme/evidence. FAIL/UNVERIFIED never becomes PASS through a screenshot or a confidence statement.
+
+Narrative cast, locomotion, queues, combat, exits and five-layer acting apply only to implemented narrative features. Educational scenes require complete causal construction and lessons, not fictional actors or attack quotas. Presentation recipes cannot waive physical checks.
diff --git a/references/pitfalls.md b/references/pitfalls.md
new file mode 100644
index 0000000..dc810b1
--- /dev/null
+++ b/references/pitfalls.md
@@ -0,0 +1,53 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Pitfalls
+
+- **A building's roof is a large visible surface at 33 degrees.** Look down onto
+ it and dress it, or keep buildings lower than they are deep.
+- **A merge pass eats anything whose visibility is animated.** Batching
+ same-material siblings keeps one `visible` flag, so hidden cargo comes back as a
+ single invisible mesh that never appears, and the survivor's `getWorldPosition`
+ reports local coordinates. Tag runtime-toggled meshes `userData.noMerge = true`.
+- **Canvas size is presentation, resolution is the buffer.** Shrinking the display
+ keeps the buffer; moving the buffer changes the art. `renderScale` 1.2–1.5×
+ on a small subject sharpens it without making it larger; measure fps and inspect
+ a 1:1 crop before keeping it.
+- **Raising the buffer exposes geometry that hid at the old grid.** Re-run the
+ portraits after any resolution change: floating hats, detached stripes and
+ oversized noses show up there first.
+- **A prop swallows a figure placed inside it.** Sit the figure on the near rim
+ with the limbs outside; more detail inside will not read anyway.
+- **Lying bodies convert joint Z rotations into vertical lifts.** Flatten
+ shoulders to about ±0.15 and keep elbows near zero.
+- **A springboard must move and the rider must follow it**: pivot at the root,
+ integrate a spring on `rotation.z`, and put the feet on
+ `pivotY + h*cos(flex) - arm*sin(flex)`.
+- **A standing gesture blended into a walk straightens the legs and slides.**
+ Gate `PAY`, `ORDER` and `POINT` on `!state.moving`; a still at one timestamp
+ will not catch it, a 0.15 s strip will.
+- **A carried prop parented to the root leaves the hands at the first turn.**
+ Keep it in world space, solve from the wrists each frame, and log palm-to-prop
+ distance.
+- **A leg swung with hip X goes through the handlebars.** A side mount needs hip
+ Z abduction, knee flex and a small root arc; hip X is for walking and sitting.
+- **Shrinking the geometry or the canvas frame to satisfy "smaller"** shrinks
+ the world clip, contact shadows and slab, or changes the 1:1 crop. Move the
+ camera with `subjectScale` instead; the frame and backing buffer stay fixed.
+- **A DOM caption on the white paper** is outside the diorama. Model the sign or
+ use the browser title.
+- **A hat hovering above the skull** is a brim at 0.225 instead of 0.192.
+- **Oversized nose**: 0.044 at this camera is a snout, 0.038 is a nose.
+- **Two figures at 0.8 m read as one silhouette.** Judge spacing from numbers.
+- **A shared window synchronises a group.** Stagger every actor's window.
+- **A door left open beside idle actors reads as stuck in the doorway.**
+- **A pose switch is not a transition.** Cutting from a run into a transfer pops
+ the whole body: blend out over the last 10 to 15 percent and hold a beat.
+- **A cannon with a brass end cap is a baton.** Hollow collars, a recessed dark
+ bore, a back disc and a lip ring; the hole must survive the 1:1 crop.
+- **Fixed deck props parented to a yaw group sweep with the gun.** A powder keg,
+ shot pile, rammer or crew member under the turret turns with every aim. Put
+ them on a static wall locker outside the barrel arc, not just on the root at
+ deck height; test world positions and bounding-box overlap at both yaw extremes.
+
diff --git a/references/project-layout.md b/references/project-layout.md
new file mode 100644
index 0000000..88c0651
--- /dev/null
+++ b/references/project-layout.md
@@ -0,0 +1,112 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Project Layout
+
+```
+DESIGN.md filled design sheet: premise, cast, systems, beats, budget
+CREDITS.md every imported model: URL, author, licence (CC0/CC-BY/owned)
+refs/ reference frames: contact sheets stepped from the source clip
+refs/SOURCES.md research log: query -> found -> decision, per question
+src/
+ config.js scene constants + clamp/lerp/smooth/pulse/hash
+ main.js renderer, scene, clip planes, resize, rAF, ?t= freeze
+ core/
+ palette.js N entries + named C map
+ post.js PixelPost: gamma, grade, ink, dither, snap, rim (pixel only)
+ stroked-toon.js optional approved OutlineEffect + four-step toon materials
+ materials.js every material, palette-validated
+ geometry.js roundedBox, addBox, lathe helpers
+ mechanism-contract.mjs shared anchors, coverage/end-plane budgets + scoped contact policy
+ inspection.js rigid assembly/piece emphasis, reveal authorization, exact restoration
+ ui/
+ education-dock.mjs education-dock.css dependency-free single lesson surface
+ merge.js mergeSiblingMeshes: one draw per material per group
+ scene/
+ camera.js lighting.js street.js bank.js props.js
+ car.js shell, doors, boot, seats, cargo
+ peopleModel.js base rig (swimwear/aquatic)
+ peopleModel-street.js clothed rig: heads, layers, hats, hands
+ people.js the cast: poses, walk/run, tracks, buildCast
+ stage.js the beat sheet + every actor as a function of t
+ effects.js contact shadows, smoke, spill, siren
+build.mjs esbuild bundle, index.html, standalone HTML
+qa/
+ shoot.mjs viewports + console errors + named timestamps
+ inspection.test.mjs helper state/identity/ownership and injected failure regressions
+ inspection-browser.mjs synthetic contrast/depth/restoration fixture, three presets
+ probe-*.mjs one-off numeric probes (facing, anchors, NaN, spawn pose)
+ audit.mjs scene lint: halos, fades, camera/render scale, exits, FX
+ portrait.mjs isolated figure/framing shots through a debug camera
+ strip.mjs N-frame motion strips (fails on a frozen loop)
+ probe.py colour runs across an edge
+ sweep.mjs pairwise distances + jam/teleport verdict
+ tile.py tile a motion strip
+ README.md audit contract, commands, failure table
+```
+
+Wire order in `main.js`: renderer → scene → camera → post → clip planes → lights →
+materials → street/bank/props → cars → cast → effects → merge → stage. Merge once,
+before the stage is created, so the timeline binds to the surviving meshes.
+
+A defence or arena subject replaces `street/bank/car` with `path/towers/keep`:
+
+```
+src/scene/
+ path.js route samples, arc length, at(d), ground height
+ towers.js foundations, machines, crew, recoil pivots
+ monsters.js rig, poses, walk/fly/hop, boss club
+ keep.js gate, walls, door leaves, cracks, goal response
+ roster.js species stats and wave table
+ battle.js deterministic 40 Hz sim, shots, impacts, deaths, gate hits
+ props.js camp, skull tree, cart, torches, trees, portal dressing
+ effects.js beams, projectiles, dust, smoke, shards, rings, souls
+```
+
+The same wire order applies: build the set, then the cast, then effects, then
+merge once before the battle timeline reads the survivors.
+
+When the beat sheet moves into its own module, delete the superseded director and
+update the README's beat table in the same pass. An unreferenced six-hundred-line
+timeline and a table that disagrees with the code are exactly what the next reader
+trusts.
+
+`templates/` carries runnable copies, not excerpts. Foundations: `post.js`,
+`palette.js`, `camera.js`, `lighting.js`, `geometry.js`, `build.mjs`. Cast and
+motion: `peopleModel.js`, `peopleModel-street.js`, `poses.js` (the pose library,
+including the four climb poses and the walk/run cycles), `transfer.js` (seating,
+the climb, stand spots, facing), `track.js` (arc-length paths with lane offsets
+and smoothed ground height), `stage.js` (beat table, `keysAt`, `place`, the
+actor loop, a car state machine). Props and systems: `detail.js` for prop
+assemblies (including `haloPlane`/`softDiscTexture` for soft light cards),
+`combat.js` for deterministic timing and death grammar, `creature.js` for a
+fight between two rigged actors (stage-local `aimYaw`, bone-space `headAnchor`,
+`uprightQuat`, the `makeHurtModel` severity table and `sendOut` throw-and-return
+geometry). Effects: `water.js`, `wake.js`, `splash.js`. Sheets: `DESIGN.md`,
+`CREDITS.md`, `SOURCES.md` (the research log, filled before the first mesh).
+
+`stage.js` ships as a **skeleton with one worked actor chain**: a figure leaves a
+car, walks a route, comes back and climbs in. It is deliberately not a story. The
+structure it does ship is the part that is tedious and easy to get wrong: beats
+ordered monotonically in `t`, one branch per actor per frame, the contact shadow
+following `place()`, and the door as a timeline rather than a state. Replace the
+cast, the routes and the beat table; keep the skeleton.
+
+`car.js` is still not in the kit. A vehicle is the most subject-specific prop in
+the scene, and the recipe (dimensions, door pivots, windscreen versus seat, boot
+well, livery split) is written above at the length it needs. Everything else you
+need is a file.
+
+`qa/` is the harness: `shoot.mjs` (viewports, named timestamps, console errors,
+the buffer/camera/draw-call line), `audit.mjs` (flat-glow, whole-object fade,
+camera/render-scale, early-hide, teleport, idle/orphan emitter and margin checks
+against the optional scene contract), `portrait.mjs` (isolated figures through the debug
+camera), `strip.mjs` plus `tile.py` (motion strips, which fail on a frozen
+loop), `probe.py` (colour runs across an edge, the tool for "why is there a band
+here"), and `sweep.mjs` (pairwise distances across a beat, with a two-sample jam
+verdict and a teleport limit). They need `playwright-core` and a page that
+exposes `window.__diorama` with `freeze(t)`; `verify/water/` is a worked example
+that exercises the three water modules and shows what the acceptance output
+looks like.
+
diff --git a/references/realism.md b/references/realism.md
new file mode 100644
index 0000000..8512265
--- /dev/null
+++ b/references/realism.md
@@ -0,0 +1,42 @@
+# Realism without photorealism or extra clutter
+
+Realism means plausible construction, proportions, material roles, spatial hierarchy and operation. It applies equally to pixel, toon and hybrid; do not change the user's style to PBR/photorealism. A high mesh count and zero obvious intersections do not make a believable object.
+
+## Before expensive geometry: choose a coherent reference family
+
+For real subjects, use one whole-object reference plus the necessary side/rear/interface views from a compatible design family; a real photograph/dimension drawing is preferable to several AI guesses. Record the specific proportions and construction choices you adopt. Research only unresolved anatomy/motion, not four unrelated asset searches per tiny object. Invented subjects still borrow one coherent construction vocabulary. Do not merge incompatible mechanisms because their silhouettes look useful.
+
+Make a short proportion table: overall width/depth/height; work/deck/ground elevations; main opening; largest moving envelope; support spacing; material thickness; two human/object scale cues. Use ranges from the reference, not universal numbers. Calculate derived dimensions from it. If proportions are not understood, build only the plain primary forms and inspect them before joints/detail. Do not decorate a fundamentally wrong silhouette.
+
+## Ground and floor are part of the object
+
+Choose exactly the relevant physical context:
+- Freestanding machine: modest real floor/workbench under feet; if a display plinth is used, distinguish it from the actual floor and keep it visually subordinate.
+- Interior: floor thickness, room/wall relationship, thresholds, column/wall support and finish appropriate to use. No room-shaped floating platform unless explicitly a cutaway.
+- Outdoor/site: terrain/grading, foundations/paving, drainage/kerbs/access and vegetation tied to the site; not all objects planted in one uniformly raised slab.
+- Small instrument/portable object: no mandatory landscape slab; neutral paper/studio ground may suffice.
+
+One surface table owns elevations and thicknesses. Floor, finish, kerbs and pads meet without coplanar z-fighting, unexplained lips or doubled bases. Feet/wheels actually contact their support. The base may not dominate the image through excessive thickness, saturated beige, huge empty margins or foreground perspective. No stripes, stains, grass or shadow patches added to disguise a missing physical surface. Ground and backdrop colours must be deliberate, not two accidental render/CSS papers.
+
+## Exterior, inside and construction hierarchy
+
+Use a believable progression: base/frame → structural deck/walls → operating mechanism → protective enclosure → controls/service connections. Member sections, spans and plates should agree with the reference's scale; four full-height cage posts should not visually overwhelm a tiny teaching core without purpose. Prefer negative space and a useful inspection angle to dozens of cage bars.
+
+The complete default exterior remains plausible. Inside removes only authored removable covers; it reveals a physically coherent arrangement with supports, shaft bearings, transfer surfaces, actuator guides, pipe runs and access room. Do not invent mystery masses under a deck or leave a functional island floating once covers disappear. Routes terminate at physical ports and avoid working travel. Use real slots/holes and appropriate clearances instead of clipping through a wall. A support chopped off to cure an overlap needs a new real load path.
+
+Materials follow roles: structural steel, coated panels, concrete/floor finish, elastomer belt/feet, glass/plastic, liquid, cable. Use a restrained authored palette with distinct value/roughness/opacity roles; do not give every material the same grey-green tint, opacity and outline. Glass cannot erase the mechanism or turn the entire scene muddy. Liquids stay inside containers. Keep four-tone readability, bounded highlights and consistent contact/shadow scale. The selected visual preset owns the renderer; material role does not authorize another rendering pipeline.
+
+## Five cheap visible acceptance questions
+
+At layout/functional milestones, view hero, reverse and phone; add one Inside close-up if relevant:
+1. Is the complete named object identifiable, proportionate and uncropped, with a subordinate appropriate ground/floor?
+2. Can the input, working element and output be seen and followed without reading a label?
+3. Do supports, thicknesses and connections look like one construction family rather than arbitrary primitive dimensions?
+4. Does Inside reveal sensible occupied space and an actual load/flow path, not empty casing plus decorative greeble?
+5. Are material roles and medium construction readable without noisy tiny edges, oversized controls or view-obscuring frames?
+
+If any answer is no, change primary dimensions/layout/material hierarchy now. Do not proceed to microdetail and explain the bad image away. Test numeric contacts and mechanics separately; these questions are visual quality gates, not engineering certification.
+
+## Detail for less work
+
+Spend effort on reference-defining silhouettes, medium assemblies and correctly seated joints. Reuse one validated bolt/hinge/bearing frame, apply meaningful repeats and stop when more subdivisions disappear at delivery scale. A visible seam, a proper door return and a supported pipe are more useful than fifty tiny washers. Simplify unrequested internal complexity explicitly; never omit identity-bearing exterior/back parts. A scene should be both physically understandable and visually composed before adding wear or decorative props.
diff --git a/references/reliability.md b/references/reliability.md
new file mode 100644
index 0000000..e9c65cd
--- /dev/null
+++ b/references/reliability.md
@@ -0,0 +1,70 @@
+# Construction and repair adapter
+
+The core is normative. This adapter turns the electricity-campus failure pattern into reusable checks for buildings, machines, characters, furniture and moving assemblies. It does not claim arbitrary mesh collision or load-bearing physics certification.
+
+## Small implementation contract
+
+1. **Assemble from a placement table.** Keep unit, datum, parent-local position/axis, footprint, required members and interface IDs together. Build a cylinder/pipe from its two mating endpoints using native +Y → direction quaternion; use centre coordinates for a rotated cylinder. A base-Y helper offsets before rotation and therefore does not describe the final underside. Keep real ports/holes and actual support members in the same assembly definition.
+2. **Separate physical ownership, selection scope and appearance.** Return `{group, pieces, interfaces, anchors}` from each builder. An exclusive physical leaf registry owns each independently placed/working assembly for pair coverage. A separate selectable scope can union several leaves (e.g. City load contains three buildings); selecting that scope must not remove building/building checks. Inspection's single controller still requires disjoint ownership among its active top-level scopes; a clicked piece refines a scope. Register all façades/fittings/bases/descendants by semantic role, not material/type/coordinate filters. Floor/roads are context. Reject duplicates, unknown IDs and empty expected members; never put the entire scene in one physical assembly to evade checks.
+3. **Store anchors locally.** Derive `anchor.local` from a real mesh face/vertex/port once, transform from the live source every evaluation. If using geometry bounds, recompute after a geometry revision. Both ends of a cable and the insulator it meets share that interface record. Callout, emitter, pick target and focus cannot maintain separate guessed world-coordinate lists. A screen label then projects world → NDC → actual canvas client rectangle and is clamped/occlusion-tested; this helper supplies world points, not screen/UI behavior.
+4. **Use actual geometry.** After parents update, transform position attributes into world coordinates and validate finite values/counts. Don't choose fixtures by geometry constructor/type/parameters: RoundedBoxGeometry can inherit unit-box metadata. Test physically relevant extremes, not object origins. AABB broad phase is conservative: holes, concave saddles, thin angled struts and unions containing empty gaps need authored narrower proxies or analytic/mesh checks before a clearance claim. Never suppress a flagged assembly just because it looks okay.
+5. **Trace supports.** Each supported member has a declared surface/joint and local contact patch. For a simple axis-aligned base, measure bottom minus pad-top plus positive overlap on both transverse axes. For curved, angled or moving contacts use actual transformed mating surfaces/analytic residuals, not an assembly's global min/max. Check a connected support graph from required members to named roots; its edges require measured geometry, not ID strings alone. A passing graph is not structural-strength proof.
+
+## Copy-in coarse audit
+
+Copy `templates/scene-contract.js`; inject the scene's existing THREE instance. Use a **dedicated physical audit root** before adding selection overlays/particles. Every mesh under that root must be registered and owned exactly once; expected counts come from the independent inventory. Do not omit inconvenient geometry. For imported skinned/morphed/instanced meshes use a compatible evaluated-geometry/proxy adapter and retain explicit coverage; the rigid helper rejects unsupported classes.
+
+```js
+const audit = createSceneContract(THREE, {
+ root: physicalRoot, expectedAssemblies: 2, expectedMeshes: 2,
+ tolerance: 1e-5, // choose against scene units, not this example
+});
+audit.mesh('pad.solid', pad).mesh('unit.body', body)
+ .assembly('pad', {meshes: ['pad.solid']})
+ .assembly('unit', {meshes: ['unit.body'], anchors: {
+ label: {mesh: 'unit.body', local: [0, bodyHeight / 2, 0]},
+ }})
+ .contact({id: 'unit-on-pad', upper: 'unit', lower: 'pad',
+ axis: 'y', tolerance: contactTolerance, minOverlap: requiredPatch});
+const report = audit.evaluate(state);
+// Full-assembly world envelopes + exact registered member bounds are in report.
+const sweep = audit.sample(phases, phase => evaluateScene(phase));
+```
+
+`mesh`, `assembly` and `contact` declarations are sealed on first evaluation. All live physical-root meshes remain covered. Contact is only an axis-aligned envelope face/overlap test. Envelopes are keep-outs; union-gap overlaps also flag conservatively. A flagged pair needs geometry correction or a documented narrow-phase method. Intended overlap is not permission for an unrestricted exemption: an exact mesh-pair exclusion must have an explicit penetration budget, rationale and active state/phase condition if moving; it cannot exempt another member or certify a real surface. See the helper's API and tests before using `exclude`. If the selected method cannot validate an opening or interlocking part, report UNVERIFIED and add a subject-specific check; do not game the helper by grouping colliders together.
+
+**Adjudicate, don't silence:** retain the raw conservative report. A scene-level coverage ledger may resolve a candidate only with `{pair, memberSurfaces, phases, method, tolerance, worstResidual, sourceHash, testCommand, negativeFixture, proofPath, result}` from an executed analytic/mesh test. A union-gap candidate with all member pairs proven clear can be resolved there; the helper's raw `ok:false` remains recorded, not rewritten. Final physical acceptance requires every relevant candidate and internal pair covered and no FAIL/UNVERIFIED—not raw helper `ok` alone. An arbitrary callback, prettier screenshot or unbounded exclusion is not adjudication.
+
+**Internal interfaces:** the top-level helper tests different physical leaves, not pairs within one leaf. Keep selection semantics unchanged; build a dedicated per-interface sub-audit fixture using clones with their actual world transforms, registered as `housing`/`shaft`/`support` audit participants, or run the subject's analytic/triangle test directly. Never reparent the live scene or omit caps/bevels. For a bored plate: use actual bore axis/end-plane residuals and radial clearance including bevel intrusion, plus actual beam/flange solid tests; the outer housing AABB necessarily contains the shaft and cannot prove a bore. Record these internal pairs separately in the same ledger. `mechanism-contract.mjs` validates scalar/interface budgets; its passing result still needs actual opening geometry evidence.
+
+The helper has no renderer, material selection, UI, source hashing, exact holes, rotational sweep or continuous collision solver. Run its regression fixture with `node verify/scene-contract.mjs` in the installed skill, setting `THREE_MODULE` to the project's installed Three module when needed. The host still owns detailed per-scene coverage and a built-artifact browser run.
+
+## Bounded failure injections
+
+Make these test-copy mutations and require the matching check to fail; restore before final build:
+
+| Mutation | Detect with |
+| --- | --- |
+| Remove required member / select fixture matches zero objects | Explicit expected ID/count and finite nonempty geometry |
+| Lift or bury foundation; move a support off the pad | Signed contact gap + transverse contact patch + support graph |
+| Make a canopy/roof cross the neighbouring lot | Complete assembly envelope, then actual close-pair method |
+| Shift one repeated bearing or use wrong cylinder axis | All-instance shared-frame residual + transformed axes/end planes |
+| Fill a bore / add a beam through it | Actual bore section/triangle or analytic solid check, not scalar radius alone |
+| Move/rotate an assembly after callout registration | Anchor follows live transform; endpoints/focus/pick ownership follow too |
+| Exclude one mating pair then collide a different pair | Exact-pair policy and penetration/window budgets |
+| Switch a glass façade to wrong material controller | Map/class preservation, shader compile, selected pixels + exact restoration |
+| Run stale bundle/report | Loaded artifact identity equals successful fresh build hash |
+
+## Repair dependency closure
+
+Never finish a relocation by changing just `position`:
+
+- **Position/scale/geometry:** recompute lots, base heights, supports, approaches, swept bounds and fit; update geometry-derived anchor frames, ports, cables, emitters, useful focus, picker ownership and annotation occlusion. Retest neighbouring lots, not only the moved object.
+- **Hierarchy/merge:** rebind semantic ownership, pieces, anchors, animation handles and support graph to surviving meshes; verify no old unparented object is used as world position.
+- **Material/selection:** retest every owned member including Basic/maps/arrays; excluded neighbours; preserved original materials; clear/Reset/Inside; overlay lifetime/counts; browser shader errors.
+- **Copy/metric:** check selected card AND shortened callout AND source/units; component-specific explanation must match visible geometry and live state. A cooling tower metric is not coal-plant efficiency.
+- **Any shipped source change:** successful rebuild, fresh hash and affected probes/screenshots on the output. Never reuse stale passing evidence. Expand tests when the repair reveals a missing invariant, rather than adding another guessed offset.
+
+## Evidence provenance
+
+Electricity-campus repair, 31 October 2026: city towers and battery bodies intersected; rotated/base-height conventions caused unsupported details; relocating a cooling tower left the callout at old world coordinates; colour/coordinate filtering omitted glazing and a tower from City load emphasis. The repair measured complete city envelopes and supports, tested 48 owned tower meshes/12 glazing planes with exact restoration, derived the cooling anchor from the moved assembly and captured both reverse and selected views. These are local failure examples, not a benchmark that guarantees unrelated future scenes.
diff --git a/references/render-preset-gate-ask-once-every-project.md b/references/render-preset-gate-ask-once-every-project.md
new file mode 100644
index 0000000..3b206c2
--- /dev/null
+++ b/references/render-preset-gate-ask-once-every-project.md
@@ -0,0 +1,69 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Render Preset Gate (ask once, every project)
+
+Before the first mesh — and before any palette, material, lighting or post work — ask
+which look the build should use. Ask once per project, not per material, per repair
+or per scene profile. This applies to every profile, including `educational`.
+An existing-project repair retains its recorded preset; read its design/code first,
+record that provenance and do not re-ask unless a new look is requested.
+
+> **Which look should I build this in?**
+>
+> 1. **Pixel art** (default) — palette-snapped pixels, ordered dither, ink contour,
+> flat cut-out on white paper.
+> 2. **Stroked toon / illustrated miniature** — smooth bevelled parts, four-step
+> shading, fine charcoal outlines, clean paper backdrop.
+> 3. **Pixel + stroke hybrid** — the same toon shading and outlines rendered into a
+> low-resolution target and nearest-neighbour upscaled once.
+
+Use the harness's structured-choice surface when there is one, with pixel listed
+first, marked as the recommendation and carrying one sentence of consequence per
+option. Otherwise ask in plain prose, in the user's language, in one short message.
+
+- **An explicit style in the request is already an answer.** "Make it pixel art",
+ "in the stroked-toon look" — record it and skip the question. Do not re-ask.
+- **Naming a look elsewhere is not an answer.** The word "toon", "cartoon",
+ "illustrated", a reference image, a previous project's style, or this skill's own
+ examples do not confirm this build's preset. Ask anyway.
+- **No answer means pixel.** Silence, "you pick", or "whatever looks best" resolves
+ to `pixel` and is recorded as a delegated default. Do not switch later without a
+ new answer, and do not re-offer the alternative at every step.
+- **Waiting does not idle the build.** The grey blockout, the research lookups, asset
+ sourcing and the five-beat staging check are identical in all three presets. Ask
+ first, then start those while the answer is pending; hold the presentation pass —
+ palette for `pixel`, authored colour family and toon lighting for the other two —
+ until it lands.
+- **Record it** in `DESIGN.md` under `Render Preset and Style Confirmation`: preset
+ id, the user's words, and which pixel-only rules the choice replaces.
+ `renderPreset` is per project, never a global preference.
+- **Orbit is not part of this question.** All three presets orbit freely with a
+ deterministic hero pose for QA/reset. Never ask a second style question, and never
+ trade orbit for a look.
+- **Editing this skill is not a project.** Do not ask the preset question to
+ change these files; ask only when a diorama is actually being commissioned.
+
+Once answered, the matching preset section below is authoritative for camera,
+lighting, materials, post and QA. Construction, contact, clipping, animation layers,
+the detail bar and deterministic time are shared by all three.
+
+### Fast path by scene
+
+| If the commission is... | Read next, in this order |
+| --- | --- |
+| educational, mechanism, how-it-works, technical cutaway | Educational Mechanism Profile → Universal Inspection Controls → chosen render preset → Machine Grammar → Verification (profile-aware) |
+| market, food truck, bakery, cafe, shop, laundromat | Cast → Clothed Cast: Heads, Layers, Hands → Service And Queue → Machine Grammar → Carrying, Loading And Mounting → Verification |
+| heist, defence, combat | Detail Bar → Tool/Tower recipes → System And Combat Animation → Combat Readability → Verification |
+| creature battle, game scene, anime/movie fight | Research Before You Model → Field Notes: Two-Creature Combat → Creature Anatomy → System And Combat Animation → Combat Readability → Verification |
+| aquarium, pool, harbour | Cast → base rig → Water templates → Vehicles (boat) → Effects → Verification |
+| station, airport, hotel, transit | Service And Queue → Vehicles → Crowd Variation → Verification |
+| stage, festival, parade | Cast → Secondary Motion → Crowd Variation → System Grammar → Verification |
+| farm, garden, nature | Creature Anatomy → Ambient Loops → Effects → Verification |
+
+The narrative shape is place + repeated ritual + interruption + consequence.
+Educational scenes instead use mechanism + causal sequence + observable result;
+do not add a fictional interruption or cast. The fast path selects the relevant
+reference notes, not extra narrative requirements.
+
diff --git a/references/repair-acceptance-enclosure-fit-and-reference-ui-3-15.md b/references/repair-acceptance-enclosure-fit-and-reference-ui-3-15.md
new file mode 100644
index 0000000..8ae19bd
--- /dev/null
+++ b/references/repair-acceptance-enclosure-fit-and-reference-ui-3-15.md
@@ -0,0 +1,38 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Repair acceptance: enclosure, fit and reference UI (3.15)
+
+Use this short checklist for existing educational scenes before re-reading narrative
+recipes. Evidence: the LEAP-1B repair was requested because its permanent section
+exposed the core, its fit cropped the model, its beige background and crowded panel
+did not match the requested V8 reference. These checks supplement mechanical QA;
+passing enclosure rays or a screenshot does not certify a complete mechanism.
+
+1. **Closed first, explicit Inside.** Unless a permanent section is commissioned,
+ cold load and hero Reset show the complete opaque housing, no tutorial tint,
+ Inside off. Build the missing casing as real connected wall geometry while
+ preserving inlet/outlet openings; a toggle cannot repair absent geometry.
+ Inside is a named semantic button in the single surface. Internal picker or
+ lesson selection may explicitly activate it, but must update its pressed state;
+ leaving the lesson restores the preceding Inside state. Clearing selection
+ preserves an independently enabled Inside state. **Test:** load → Inside on/off
+ → internal selection → clear → lesson exit → Reset; check visible ancestors,
+ nearest opaque ray hits, exact material restoration and open-mouth rays.
+2. **Fit the assembly in the space actually available.** Measure canvas layout
+ after the dock/panel; use actual complete assembly bounds including covers,
+ supports and swept extrema, not a default slab. Fit the safe rectangle with
+ padding; if UI overlays the canvas, solve its offset as well as distance.
+ With direction target→camera, depth is `distance - along`, so each fit bound
+ contributes `abs(transverse)/tanHalf + along` (not minus along). Do not clamp
+ distance below the solved fit or distort portrait aspect. Re-measure on layout,
+ disclosure, resize/orientation and zoom changes without hijacking user orbit.
+ **Test:** project covered/exposed swept bounds at desktop, tablet, 390×844,
+ 320×640 and 200% zoom, with lesson/disclosure open; front/back/high captures;
+ fail an injected protrusion and verify near-plane/focus fits separately.
+3. **UI repair:** compare the supplied reference before changing placement;
+ apply `Canonical educational UI and inspection contract`, including rendered
+ background, accessible lesson state and desktop/phone/200% zoom gates. Do not
+ copy the reference subject or introduce a second surface.
+
diff --git a/references/representation.md b/references/representation.md
new file mode 100644
index 0000000..b86d3de
--- /dev/null
+++ b/references/representation.md
@@ -0,0 +1,40 @@
+# Represent the named subject, not automatically a teaching prop
+
+Resolve WHAT is being represented before asset search or geometry. Default `representationMode: real-subject`: depict the actual subject in its appropriate natural/physical form. “Educational”, “explain”, “3D model”, “diorama” or a toon/pixel style does not authorize replacing it with a toy, classroom aid, bench apparatus or museum display.
+
+## Three modes; delegate only when asked
+
+- **real-subject**: the actual thing. Earth is a planet, a heart is the organ, a volcano is terrain. A real machine retains its actual feet/housing; natural objects do not gain an invented base, stand, spindle or mechanism. Scale compression is declared; no false claim of literal size.
+- **teaching-model**: a physical demonstrator deliberately representing the thing: a classroom globe, orrery, mounted anatomical model or tabletop rig. Use only when explicitly requested/confirmed or explicitly delegated with a stated reason. Its supports and mechanisms need plausible construction but must not be confused with how the represented natural subject works.
+- **explanatory**: an openly simplified visualization: section, exploded layout, field/flow arrows, diagrammatic scale or symbolic geometry. Keep subject identity and correct causal explanation. A cutaway or overlay can also be a view of real-subject; it does not require turning the subject into a tangible toy.
+
+A “realistic classroom globe” is still teaching-model; “stylized Earth in space” is still real-subject. An imported asset's form must match the mode: a commercially licensed globe on a stand cannot substitute for a requested planet just because both have the right title. Asset accuracy/role and representation are separate checks.
+
+## Ask only for a material unresolved choice
+
+If the user explicitly names the form, follow it. If they simply ask to explain the subject, use real-subject without another question. The word “model” alone is not an instruction for a physical scale model.
+
+If the brief genuinely leaves competing forms unresolved, ask once:
+
+> **How should I represent the subject?**
+> 1. **The real thing** — actual subject in its appropriate setting.
+> 2. **A physical teaching model** — a tangible demonstrator with intentional supports.
+> 3. **An explanatory visualization** — simplified sections, fields or exploded forms.
+> 4. **You choose** — choose the form that best serves the explanation and state why.
+
+Combine with an already-needed style question where possible. Don't ask again during repairs or per component. If a repair's old design silently substituted a globe/toy for an actual-subject request, correct that mismatch rather than preserving an erroneous surrogate as a supposed prior choice.
+
+## Keep independent decisions independent
+
+- **Render preset:** pixel / toon / hybrid changes visual treatment, not subject identity.
+- **Presentation:** full scene / standalone / both controls surrounding context. Standalone Earth is still a planet, not automatically a globe. Do not force this extra question or implement a dual-mode toggle unless requested or meaningfully unresolved.
+- **Exterior / Inside:** authored explanatory views, not permission to change the subject into a classroom object. Preserve its complete default form unless an explicit permanent section was requested.
+- **Educational profile:** causal text/lessons and inspection behavior, not mandatory legs, casing, platform or a three-part machine analogy for everything.
+
+Record mode and decision origin (`explicit`, `default`, `clarified`, `delegated`) plus one-line rationale in DESIGN. Keep the user's mode during normal repair. Reference/asset searches include the actual form/variant; layout proof checks for unwanted stands, floors, display bases or toy mechanisms before detail. Add explanatory layers to the subject rather than replacing the subject to make labelling easier.
+
+## Small semantic regression set
+
+Expected behavior: “explain Earth”, “3D model of Earth in space”, “pixel volcano”, “standalone beating heart” → real-subject, no representation question or invented display mount. “Classroom globe with stand”, “anatomical teaching model on a plinth” → teaching-model. “Diagrammatic exploded pump”, “schematic Earth layer visualization” → explanatory. “Cutaway of the real pump” → real-subject with a cutaway, not automatically a physical demonstrator. An exhibit brief explicitly undecided between a planet and tabletop globe → clarify. Repair of an explicitly chosen teaching model → retain teaching-model. Style/base preferences alone do not resolve or override these choices.
+
+These are instruction/semantic-consumer fixtures, not an automatic scientific-truth detector or proof of a rendered scene. No Earth scene is commissioned by these examples.
diff --git a/references/research-before-you-model.md b/references/research-before-you-model.md
new file mode 100644
index 0000000..1b13f05
--- /dev/null
+++ b/references/research-before-you-model.md
@@ -0,0 +1,189 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Research Before You Model
+
+Four lookups come before the first mesh: the subject by frames, the asset
+libraries, the motion itself, and the capture loop. Skipping them is how a build
+ends up with a plausible silhouette that matches nothing and animation that reads
+as generic. Budget for them, they are usually faster than the modelling they save.
+
+| Question the research answers | Where it lands |
+| --- | --- |
+| what does it look like, exactly | `refs/<subject>/*.png` contact sheets |
+| what does it do, in what order, how fast | `refs/SOURCES.md` + the beat table |
+| does a rig or clip already exist | `CREDITS.md` + `assets/` |
+| is it actually right on screen | `qa/` captures, compared to the sheets |
+
+### 1. The subject, by frames
+
+Find the real thing moving, not stills. For games, anime, sport or machinery the
+footage *is* the specification: it settles what the shape is, where the motion
+starts, how long each stage lasts and what colour it is at each step.
+
+```bash
+yt-dlp --flat-playlist --print "%(id)s | %(title)s | %(duration)s" "ytsearch6:<subject> animation"
+yt-dlp --extractor-args "youtube:player_client=ios,android" -f 18 -o "refs/clip.%(ext)s" <id>
+ffmpeg -i refs/clip.mp4 -vf "fps=8,scale=300:-1,tile=6x4" refs/sheet-%02d.png
+```
+
+Read the contact sheets with vision, then write the grammar down in words before
+touching geometry: *ball leaves the hand on an arc, opens with a white burst, the
+creature springs out at full size, the ball snaps shut and returns*. A paragraph
+like that is the acceptance test for the effect you are about to build.
+
+Rules that come out of doing this repeatedly:
+
+- Prefer **game footage** over fan animation for game subjects; the game is the
+ canonical grammar, and fan cuts are already an interpretation.
+- Prefer **one clean clip sampled densely** over ten clips sampled sparsely.
+ Twelve frames a second on a 4 second send-out shows the whole sequence.
+- Keep the sheets in `refs/<subject>/` next to the build so the next person can
+ see what you were matching, and so QA has an image to compare against.
+
+### 2. Model sourcing: check the libraries before you build
+
+Hand-building a creature from primitives is the *last* option, not the first. A
+rigged download with real deformation and usable clips beats four hundred lines
+of spheres the moment the camera comes within a metre. Search first, and keep a
+record of what you searched.
+
+**The ladder. Every hero asset walks down it in order.**
+
+1. **Already on disk.** The user's folder often ships a `tools/`, `assets/` or
+ `model/` directory with GLBs in it. List it before anything else.
+2. **A CC0 pack covers it.** Import it. No attribution, no negotiation.
+3. **A CC-BY model covers it** and the page can carry a credit line. Import it,
+ credit it, done.
+4. **Nothing fits the silhouette** and the shape has to be exact. Hand-build it
+ against the reference frames, and say in the log that you searched.
+5. **Never:** ripped game assets, Models Resource / Spriters Resource downloads
+ used as geometry, "editorial use only", NC, ND, or anything with no stated
+ licence. Those are hard stops; ask the user instead of guessing.
+
+**Creatures, characters and rigs**
+
+| Source | Licence | What is actually there | How to search |
+| --- | --- | --- | --- |
+| [Quaternius](https://quaternius.com) | CC0 | hundreds of low-poly creatures, characters, nature, buildings; the Universal Animation Library is 120+ clips | browse `quaternius.com/packs`, grab the pack GLB |
+| [KayKit / Kay Lousberg](https://kaylousberg.itch.io) | CC0 | adventurers, skeletons, dungeon and RPG packs, rigged and animated | itch page, per-pack zip |
+| [Poly Pizza](https://poly.pizza) | CC0 or CC-BY | 10,000+ low-poly props, creatures, vehicles; GLB/OBJ, no login | search by noun, read the badge on each card |
+| [Kenney](https://kenney.nl/assets) | CC0 | kits for props, vehicles, characters, UI, audio | category browse |
+| [Sketchfab](https://sketchfab.com/3d-models) | per model | the long tail: specific machines, animals, buildings | filter **Downloadable** + **CC0**/**CC-BY** before looking at anything |
+| [Smithsonian 3D](https://3d.si.edu) | CC0 | scanned real objects, fossils, artefacts, vehicles | search, check the licence note under the download |
+| [NASA 3D Resources](https://nasa3d.arc.nasa.gov) | public domain | spacecraft, rovers, terrain, helmets | browse by category |
+| [glTF Sample Assets](https://github.com/KhronosGroup/glTF-Sample-Assets) | per model, mostly CC-BY 4.0 | canonical rigged test models (CesiumMan, Fox, BrainStem) | read `LICENSES/` before use |
+| [Objaverse](https://objaverse.allenai.org) | mixed, per object | 800k research objects, good for odd props | verify the per-object licence, most are not clean |
+| [Meshy](https://meshy.ai), [Tripo](https://www.tripo3d.ai), user-supplied | user owns the output | anything the pack libraries do not have, generated from the reference | export GLB, keep the prompt in `CREDITS.md` |
+
+**Animation clips** (motion is usually harder to hand-key than shape is to model)
+
+| Source | Licence | Notes |
+| --- | --- | --- |
+| Quaternius Universal Animation Library | CC0 | 120+ humanoid clips, retargetable, best first stop |
+| [Mixamo](https://www.mixamo.com) | free with an Adobe account | thousands of humanoid clips + characters; check current Adobe terms, retarget in Blender or three.js |
+| [Rokoko Motion Library](https://rokoko.com/products/motion-library) | 150 free clips, paid beyond | mocap quality, good for weight and follow-through |
+| CMU Graphics Lab Motion Capture | free for research and commercial use with credit | raw BVH, huge, needs cleanup |
+| Sketchfab animated models | per model | often ships with an idle/walk/attack set |
+| [Godot4 Open Animation Libraries](https://github.com/catprisbrey/Godot4-OpenAnimationLibraries) | CC0 | Mixamo clips rebaked as Godot `.bin`/GLB banks, already retargeted; `jwelchgames/Godot4-MixamoLibraries` is the other mirror |
+
+**Props, environments, textures, light**
+
+| Source | Licence | Notes |
+| --- | --- | --- |
+| [Poly Haven](https://polyhaven.com) | CC0 | HDRIs, textures, models; the HDRI set is the fastest way to fix flat lighting |
+| [ambientCG](https://ambientcg.com) | CC0 | tiling PBR materials, HDRIs, some models |
+| [OpenGameArt](https://opengameart.org) | mixed | filter to CC0 / CC-BY; 3D section is thin but has good odd props |
+| [madjin/awesome-cc0](https://github.com/madjin/awesome-cc0) | index | a maintained list of CC0 sources when the usual four fail |
+
+**Searching them without a browser.** Three of the libraries have open APIs, so a
+build can check them in a single command and read the licence back:
+
+```bash
+# Sketchfab: downloadable + CC0 only, name and page printed for each hit
+curl -s "https://api.sketchfab.com/v3/search?type=models&downloadable=true&license=cc0&q=dragon&count=24" \
+ | python3 -c "import json,sys;[print(r['name'],'|','https://sketchfab.com/models/'+r['uid']) for r in json.load(sys.stdin)['results']]"
+
+# Poly Haven: models, HDRIs, textures (filter by category)
+curl -s "https://api.polyhaven.com/assets?t=models"
+curl -s "https://api.polyhaven.com/assets?t=hdris&c=studio"
+
+# ambientCG: materials and HDRIs by keyword
+curl -s "https://ambientcg.com/api/v2/full_json?type=Material&limit=20&q=concrete" \
+ | python3 -c "import json,sys;print([a['assetId'] for a in json.load(sys.stdin)['foundAssets']])"
+```
+
+Poly Pizza, Quaternius, KayKit and Kenney are browsed by search on their own
+pages; query them with the noun plus the style (`low poly dragon`, `kaykit
+skeleton`), not with a sentence.
+
+**Reference only, never geometry:** The Spriters Resource, The Models Resource,
+sakugabooru, game rip archives, Pinterest. Use them to learn the shape and the
+timing, then build or buy the actual asset.
+
+### 3. Animation research: how the thing moves
+
+Shape is half the job; the other half is the motion, and it is researched the same
+way. Search the *verb*, not the noun.
+
+```bash
+# the motion itself, canonical first
+web_search: "<subject> <move> animation" # a game doing it
+web_search: "<subject> <move> slow motion" # real footage, for weight
+web_search: "<subject> sprite sheet" # frame-by-frame timing
+yt-dlp "ytsearch6:<subject> <move> animation"
+ffmpeg -i clip.mp4 -vf "fps=12,scale=320:-1,tile=6x4" refs/move-%02d.png
+```
+
+Read the sheet, then **count frames and convert**: `seconds = frames / fps`, and
+scale to the loop length you are building. That is how a 0.42 s anticipation and a
+0.18 s contact become the beat table instead of a guess.
+
+Write four lines per action before animating it:
+
+```
+wind-up 0.00 -> 0.42 weight back, head down, tail still
+contact 0.42 -> 0.55 fastest frames, one pose held for two frames
+follow 0.55 -> 0.90 overshoot, then settle
+recover 0.90 -> 1.30 back to idle
+```
+
+Every attack in the beat sheet needs all four. Missing anticipation is why an
+effect reads as "it just happens", and missing follow-through is why it reads as
+"it snaps back".
+
+For rigs, cross-check the reference against a real clip: if the library has a
+punch, a swipe or a jump that is close, retarget it and offset the acting, rather
+than keying a pose from scratch.
+
+### 4. The research log
+
+Every build writes `refs/SOURCES.md`. It is the proof the searches happened and
+the reason the next person does not repeat them.
+
+```md
+| Question | Searched | Found | Decision |
+| --- | --- | --- | --- |
+| what does the send-out look like | yt: "sword shield send out slow motion" | RoUJ_TWvB3g, orb + white burst | matched, timings below |
+| hero creature rig | poly.pizza "dragon", quaternius characters | nothing matching the silhouette | hand-built from refs/sendout |
+| hit reaction weight | yt: "pokemon take damage animation" | 0.9 s flinch, 1.7 s stagger | HURTS table |
+```
+
+A build with no `SOURCES.md` has not finished its research step, even if the
+scene looks right.
+
+### 5. Prove it with shots
+
+Every beat gets frozen, captured and compared against the reference sheet before
+the next beat is built. The contact sheet of those captures is the review
+artifact, not a paragraph describing them.
+
+- Freeze the loop at the beats the reference showed: `?t=<second>` in the page,
+ `freeze(t)` through the debug hook, screenshot the frame element.
+- Put the captures in a grid next to the reference frames and read them with
+ vision. Anything that needs a caption to explain is not finished.
+- Keep numerical checks alongside the pictures: facing dot products, NaN scans
+ over every geometry, console errors, effect bounding boxes. They catch the
+ failures the eye forgives at 300 px.
+
diff --git a/references/scene-furniture.md b/references/scene-furniture.md
new file mode 100644
index 0000000..50586d2
--- /dev/null
+++ b/references/scene-furniture.md
@@ -0,0 +1,79 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Scene Furniture
+
+- **Slab** 21 x 14 x 0.42 with the street on the camera side (+Z) and the
+ building block at the back (-Z) for an exterior. For an interior cutaway, see
+ **Cutaways And Glass** before placing the street. Deck at y 0 is the street;
+ the pavement is a raised 0.16 slab with a kerb face.
+- **Pavement joints** 2.6 m apart, 0.085 m wide. Anything thinner rasterises to
+ dots that read as noise. `groundY(x,z)` returns street, pavement or step height
+ so every track and shadow samples the same function.
+- **Buildings** are boxes with a parapet, a sign band, recessed windows and a
+ door pivot. At 33 degrees you look down onto roofs: a 4.6 m wall in front of a
+ 5.2 m deep building hides none of its roof, so model the parapet, plant,
+ skylight or stair head, or keep it lower than it is tall.
+- **Doors** are pivots at the jamb with the leaf extending into the opening.
+ Recess them 0.15 so the opening shows a shadow gap, and light the interior so
+ an open door reads as a room, not a hole.
+- **Contact shadows** are one unlit radial-gradient plane per figure, opacity
+ 0.55 to 0.95, scaled to the footprint, 0.018 above the ground it belongs to.
+
+### Night, Practicals And Headlights
+
+Night is a new light ratio and a new palette, not the day rig dimmed. The sun
+table is a daylight default; a 2am scene needs its own numbers and its own test.
+
+| Key | Night default | Why |
+| --- | --- | --- |
+| moon / key | `0x93a7c4` at 0.45 to 0.65 | cool, low, soft shadows |
+| hemisphere | sky `0x1b2740`, ground `0x090b12`, 0.16 | blue ambient, never black |
+| fill | `0x6d7f9e` at 0.10 to 0.16 | keeps the shadow side readable |
+| practical | `0xffb066` at 1.0 to 1.4 | warm bulb/lamp, 2700 K |
+| pool | unlit radial plane, opacity 0.28 to 0.45 | light on the ground, cheap |
+| headlight | `0xfff0c8`, lens + cone + floor ellipse | source, throw and landing |
+
+- **A practical is an object, not a glow.** Bulb sphere, shade/guard, bracket,
+ emissive lens, small halo, and a pool on the surface below. A floating halo with
+ no fixture reads as a firefly.
+- **Use one real point light at the hero practical**, not one per bulb. The rest
+ are emissive + pool decals. Ten point lights flatten the darks and cost more
+ than they return.
+- **Keep three dark values.** Deep shadow, mid shadow and lit edge must be
+ different palette entries; if the night is one black silhouette, lift the
+ hemisphere or add a cool rim. `0x000000` is forbidden, as in daylight.
+- **Headlights are a moving pool, not a global spotlight.** Two lenses, two
+ tapered cones, one elongated floor ellipse that travels with the vehicle.
+ Do not let the cone light the whole facade: it will read as dawn.
+- **Windows are dark glass with a warm interior.** A blue-grey pane, two
+ reflection streaks, and a visible warm room behind it. A fully transparent
+ plane tints the whole interior and kills the cutaway.
+- **Grade for night after the snap:** lift black to about `0x0b1020`, keep warm
+ highlights from clipping. Test a 1:1 crop: three dark values, a visible source,
+ a readable pool, no white blob.
+
+A night scene passes when the unlit areas still have shape and the light sources
+are in the frame. "It is dark" is not a pass.
+
+### Cutaways And Glass
+
+The +Z street convention is for an **exterior**. If the hero action is inside a
+shop and the street is between the camera and the hero, the bus/traffic will
+occlude the beat. Choose one:
+
+- **Exterior scene:** street on +Z, facade behind it, action on the pavement.
+- **Interior cutaway:** omit the camera-side wall entirely (or keep a 0.25 m
+ header and sill), put the street **behind** the room at -Z behind glazing, and
+ keep the camera-side floor open. The room is the stage; the street is the
+ cyclorama.
+- **Foreground traffic:** allowed only if it crosses before or after the hero's
+ contact beat; check the occlusion frame, not just the still.
+
+For glazing, build the frame, mullions, sill and a few reflection streaks. Do not
+lay one transparent plane across the opening: it tints the interior, hides the
+practical lights and turns the cutaway into a fish tank. If the bus must read
+through the glass, give it lit windows and a dark body against the warm interior;
+do not brighten the whole room to compensate.
+
diff --git a/references/service-and-queue.md b/references/service-and-queue.md
new file mode 100644
index 0000000..be4ad47
--- /dev/null
+++ b/references/service-and-queue.md
@@ -0,0 +1,73 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Service And Queue
+
+A market, hatch, ticket window or bakery is a **queue machine**: people arrive,
+advance one slot, order, pay, receive and leave. Build the queue before the
+props; it is the scene's clock.
+
+**Slots.** Lay four to six positions along the counter, 0.65 to 0.80 m apart,
+perpendicular to the hatch. Everyone in the queue shares one lane and one
+heading; a diagonal queue reads as a crowd, not a line.
+
+```js
+const SLOTS = [q0, q1, q2, q3]; // q0 is at the hatch, q3 is the tail
+const toSlot = (p, slot) => ({ x: slot.x, z: slot.z });
+```
+
+- A customer's mover is a sequence of `seg(t0, t1, track)` legs: **enter →
+ tail → advance one slot per serve → counter → exit**. Keep each leg on its own
+ track; re-pathing every serve makes feet slide.
+- Advance the whole queue on the serve timestamp, with a 0.06 to 0.12 s stagger
+ by slot. The person at the hatch does not advance; they receive and turn away.
+- When a customer leaves, the next walks **into** the vacated slot; do not teleport
+ the queue forward while the camera is on it.
+
+**Customer state machine.**
+
+| State | Visible action | Gate |
+| --- | --- | --- |
+| arrive | walk with distance-driven gait | until slot reached |
+| order | point at menu/board, head turns | only when speed = 0 |
+| pay | hand to counter / phone | after order, only when still |
+| wait | idle, weight shift, phone | until bag lands |
+| receive | both hands or one hand out | at bag contact |
+| exit | turn, walk out, carry bag | after receive + 0.3 s |
+
+**The gate is the whole fix.** Never blend a standing gesture (`PAY`,
+`POINT_MENU`, `RECEIVE`) into a walking pose. If the gesture has straight legs
+and the walk has bent knees, the mix straightens the legs while the root keeps
+translating: the figure glides. Compute `state.moving` from the mover and write:
+
+```js
+if (state.moving) pose = walkPose(phase, { amp, arm, carry });
+else if (t < orderEnd) pose = mixPose(idle, POINT_MENU, bell(t, order));
+else pose = idlePose(t, phase);
+```
+
+- Serve **after** the counter arrival, by at least 0.25 s. A bag that lands before
+ the customer reaches the hatch is the second-most-reported queue bug.
+- One action at a time: order, then pay, then receive. Overlapping windows make
+ the arms fight.
+- A late customer may arrive after the queue empties, but only once; reusing the
+ same slot for a second invisible customer reads as a spawn.
+
+**Machine slots.** A laundromat, workshop or gym uses the same clock with
+machines in the slots: washer drum → dryer drum → fold table. Advance the batch
+on the **end-of-cycle** timestamp, not on a fixed beat, and land the next action
+0.25 s after the lid/door closes. A drum that starts tumbling before the door
+shuts is the machine version of serving before arrival.
+
+**Staff side.** The cook works the grill; the cashier takes payment and hands the
+bag across the hatch. Their gestures are independent loops, but the bag's release
+comes from the cashier's hand position, not a fixed world point. Keep a stack of
+paper bags at the hatch and decrement it per serve; the last bag is the goal
+object.
+
+**Proof.** Freeze the approach every 0.25 s for two strides and log root speed,
+`moving`, hip/shoulder angles and slot. The strip passes when the feet alternate,
+the root advances smoothly, no standing gesture appears while `moving` is true,
+and the serve timestamp is after the arrival timestamp.
+
diff --git a/references/skill-maintenance.md b/references/skill-maintenance.md
new file mode 100644
index 0000000..8f3f8e1
--- /dev/null
+++ b/references/skill-maintenance.md
@@ -0,0 +1,62 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Skill Maintenance
+
+After a scene repair, keep its observed failures and tests in the PROJECT's DESIGN/QA notes. Do not mutate the installed skill as part of an ordinary scene commission. Promote a reusable rule only during an explicit skill-maintenance request, with filesystem approval where required. Preserve the compact core; put subject-specific evidence here or in the relevant reference, never append another universal checklist.
+
+1. **Add at most three rules per routine project.** A skill that grows by fifty
+ small rules becomes unreadable and the next reader skips it; a deliberate
+ major overhaul is a versioned release, not a stealth append.
+2. **Every rule needs evidence and a test.** "Clear the threshold" came from a
+ screenshot of smoke above a portal; the test is a 1:1 crop of the pocket.
+ "The club must touch the door" came from a still at 41.075; the test is the
+ contact frame plus 0.2 s.
+3. **Promote repeated fixes.** If the same bug appears twice, it is a missing
+ rule, not a one-off.
+4. **Retire stale rules.** If a template or pipeline change makes a rule
+ obsolete, remove it in the same edit.
+5. **Bump the version.** Patch for wording, minor for a new rule/section, major
+ for a new contract or a reorganisation. Keep `SKILL.md.bak-v<old>` beside it.
+6. **Update the templates and the project layout in the same pass.** A rule that
+ points at a file that does not exist is worse than no rule.
+7. **Test the skill on a new subject.** After a major edit, give a fresh model
+ only this file and ask it to fill `DESIGN.md` for a different diorama. Fix
+ every contradiction it finds; that is cheaper than discovering them after a
+ build.
+
+A useful postmortem entry has this shape:
+
+```
+BUG: the club read as a rock at the gate
+CAUSE: end-on pose; haft hidden; no bands
+RULE: turn the boss 0.35 rad to the goal; build haft + bands + studs
+TEST: contact crop at the gate-hit timestamp; haft visible, head on door
+```
+
+Two entries from the truck-diorama correction pass:
+
+```
+BUG: a light-grey rectangle floated beside the jumbotron
+CAUSE: a flat, untextured, additive PlaneGeometry used as a glow
+RULE: halos need a radial-alpha map, an emissive lens, or deletion
+TEST: qa/audit.mjs FLAT_GLOW plus a 1:1 crop of the board at the hero time
+```
+
+```
+BUG: both trucks vanished at the gate before the run-out finished
+CAUSE: visible=false keyed to a beat, not to world bounds clearing the slab
+RULE: hide only after the box is outside slab + 0.2–0.5 m; never fade solids
+TEST: qa/audit.mjs EARLY_HIDE over the full loop; exit strip at 0.2 s spacing
+```
+
+```
+BUG: the yellow truck smoked while parked, from a cloud above the cab
+CAUSE: continuous idle haze plus a guessed emitter point inside the body
+RULE: one start/rev event window, puffs born at the real stack tip; offset the
+ birth point downstream if a canopy hides it, never the source anchor
+TEST: qa/audit.mjs IDLE_EMITTER / ORPHAN_EMITTER; event frame present,
+ event + 1.5 s absent
+```
+
diff --git a/references/starting-a-new-diorama.md b/references/starting-a-new-diorama.md
new file mode 100644
index 0000000..b4fc52d
--- /dev/null
+++ b/references/starting-a-new-diorama.md
@@ -0,0 +1,26 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Starting A New Diorama
+
+When the subject is new, the first deliverable is a design sheet, not a scene.
+With a one-line prompt, fill it from the defaults in `One Prompt, One Build` and
+do not ask the user to complete it.
+
+1. Copy `templates/DESIGN.md` into the project as `DESIGN.md`.
+2. Write the premise as a verb, not a noun. Name the place, the repeated action,
+ who interrupts it, and the payoff.
+3. Fill the cast and system sheets. If a role has no action, cut it. If a system
+ has no visible consequence, cut it.
+4. Pick five beats and five QA timestamps. A beat without a timestamp is not
+ staged.
+5. Block out in grey at the reset hero camera and shoot the five beats at 1:1.
+ This is a staging check, not a production pass: no palette, no post, no
+ materials. Redesign staging before committing to it.
+6. Once the blockout reads, run the production pipeline below. Palette is the
+ first production pass; the grey blockout does not count as one. Detail
+ multiplies a readable blockout; it cannot rescue an unreadable one.
+
+The rest of this file is the recipe for each pass.
+
diff --git a/references/surface-motion-and-event-fx.md b/references/surface-motion-and-event-fx.md
new file mode 100644
index 0000000..759ca97
--- /dev/null
+++ b/references/surface-motion-and-event-fx.md
@@ -0,0 +1,55 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Surface, Motion And Event FX
+
+These are the failures that survive a good first render: a finished-looking set
+with one raw seam, a clean loop with a vehicle that teleports out, or an effect
+that is technically present but reads as a grey rectangle. Audit them as a
+system, on every subject.
+
+- **Finish the edge, not just the field.** A heightfield, bank, road, water or
+ terrain piece that meets the slab must feather to the slab height over the last
+ 0.5–1.0 m. Never end a terrain in a lip, a vertical wall or a portal-shaped
+ hole. Prove it with a 1:1 crop of each visible slab edge at two nearby times,
+ not a wide shot where the seam is 2 px.
+- **A mover has not exited until its bounds clear the slab.** Keep the whole
+ group — body, lights, shadow, cargo — visible through the complete run-out.
+ Hide only after the world-space box is wholly outside the slab plus a 0.2–0.5 m
+ margin. No early `visible = false`, no parking at the gate, no portal. If the
+ scene uses a clip plane, the mover may be cut by it, but the cut body must
+ continue moving out; a cut that freezes is the same bug.
+- **Never fade a solid hero with material opacity.** Per-material opacity on a
+ multi-mesh vehicle or figure produces ghosting and sort artefacts: some parts
+ turn transparent before others, and the result is a see-through prop, not a
+ fade. Cut, clip, or hide only when the bounds have cleared. Transparent glass
+ and FX are exempt; whole-object fades are not.
+- **Effects are events, not weather.** Exhaust, steam, dust bursts and impact
+ puffs belong to explicit windows: start, rev, launch, hit, landing, open. If
+ the brief does not ask for idle smoke, do not emit while the source is parked.
+ A continuous plume erases the timing of the event it was meant to sell.
+ One-shot exhaust is roughly **0.7–1.2 s**, with a short fade tail under 1 s.
+ Check the event frame and event + 1.5 s: present then absent.
+- **Anchor an emitter at the physical nozzle.** For a vehicle, the source is the
+ exhaust-tip object (`(±0.66, 3.74, -0.74) * scale` on the truck recipe), not
+ the engine centre, cab roof or a point chosen by eye. Put the tip
+ in `userData` during construction and use that same object for the smoke. A
+ plume that starts above or behind the stack reads as a floating cloud. If a
+ canopy hides the tip, offset the birth point downstream in the open direction,
+ not the source anchor; the audit's `maxOffset` allows that.
+- **A halo is a sprite, not a quad.** A flat, untextured, low-opacity additive
+ `PlaneGeometry` is a light-grey rectangle at the palette snap, especially over
+ a dark board or wall. Use `haloPlane`/`softDiscTexture` from `detail.js`, a real
+ emissive lens, or no halo. This is the single most common "what is that
+ rectangle?" report.
+- **Event FX must not cover the thing you are pointing at.** A smoke cloud that
+ grows over a sign, jumbotron, face or gate has become the subject. Cap size,
+ cap life, and move the source to the open side of the prop; verify at the
+ event frame, not only at 60% of the burst.
+- **Every correction gets a regression check.** For these failures the checks
+ are: edge crop pair, mover bounds log, whole-group fade scan, emitter
+ active/quiet windows, source-to-puff distance, flat-glow scan, and margin
+ scan. `templates/qa/audit.mjs` runs the mechanical ones; the 1:1 crops remain
+ human evidence.
+
diff --git a/references/system-and-combat-animation.md b/references/system-and-combat-animation.md
new file mode 100644
index 0000000..ca471b0
--- /dev/null
+++ b/references/system-and-combat-animation.md
@@ -0,0 +1,229 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## System And Combat Animation
+
+The character section above covers body mechanics. This section covers the
+systems that carry a diorama: towers, projectiles, reactions, deaths,
+bosses, crowds and secondary motion. Every one is a pure function of `t`, driven
+by a pre-simulated event list.
+
+### The Five Layers In Code
+
+| Layer | Driver | Typical period | Use |
+| --- | --- | --- | --- |
+| ambient | `sin(t*f + phase)` | 1.5 to 5 s | breath, flame, flag, scan |
+| locomotion | distance along a path | stride length | walk, fly, hop, slither |
+| action | absolute event time | 0.3 to 1.2 s | fire, swing, slam, dive |
+| reaction | event time + direction | 0.15 to 0.5 s | flinch, flash, knockback |
+| death | absolute death time | 0.6 to 1.4 s | collapse, debris, residue |
+
+If an action and a reaction share a clock, derive both from the **same event
+timestamp**. Two independent cycles will drift apart even if they match on the
+frame you happened to inspect.
+
+### Deterministic Timeline
+
+```js
+const DT = 1 / 40;
+const LOOP = 46.0;
+
+const pulse = (t, t0, tau) => (t < t0 ? 0 : Math.exp(-(t - t0) / tau));
+const win = (t, t0, dur) => clamp((t - t0) / dur, 0, 1);
+const easeOutCubic = (u) => 1 - Math.pow(1 - u, 3);
+const spring = (t, t0, freq = 9, damp = 6) => {
+ const a = t - t0;
+ return a < 0 ? 0 : Math.exp(-damp * a) * Math.cos(freq * a);
+};
+```
+
+Run the battle at `DT` from 0 to `LOOP` once at load. Store:
+
+```js
+events.push({ t, kind: 'shot', tower, target, from, to, flight, damage });
+events.push({ t, kind: 'impact', x, y, z, species, dir });
+events.push({ t, kind: 'death', id, type, x, y, z, t });
+events.push({ t, kind: 'gate', x, y, z, hit: n });
+```
+
+The render loop reads the events whose time has passed. It never re-simulates
+and never carries state between frames. `?t=12.4` freezes the whole system,
+including effects, so every QA shot is reproducible.
+
+### Tower Attack Grammar
+
+A tower attack needs five visible stages. Cut one and the tower reads as a
+spawner, not a weapon.
+
+| Stage | What the player sees | Time |
+| --- | --- | --- |
+| acquire | head/turret turns; crew leans; crystal brightens | 0.15 to 0.4 s |
+| wind-up | rail pulls back, arm cocks, coil charges, barrel vents | 0.1 to 0.35 s |
+| release | muzzle flash, string snap, beam origin flare, arc jump | 1 to 2 frames |
+| travel | bolt, ball, beam, chain, projectile with trail | 0.05 to 0.6 s |
+| impact | flash on target, dust/goo/ice/feathers, ring | 0.1 to 0.25 s |
+| recovery | recoil returns, crew resets, smoke clears | 0.2 to 0.5 s |
+
+Tower archetypes:
+
+- **Ballista / arrow.** Slow traverse, rail recoil 0.15 m, string snap, bolt
+ with a short trail, thunk and a small dust puff. Reload is a winch crank.
+- **Cannon / bombard.** Breech recoil 0.2 m, muzzle flash and a smoke ring,
+ arcing iron ball, impact dust and a ground ring. Never rock debris.
+- **Beam / lance.** Crystal pulses, origin flare, a sustained channel with a
+ scrolling texture, a target flash, a heat ramp. The beam dies on the frame its
+ target dies and respects line of sight. Never a static white cylinder.
+- **Tesla / chain.** Coil hum, charge glow, a jagged arc that hops to two or
+ three targets, capacitor fade. The arc must visibly leave the coil.
+- **Support / aura.** A ground ring with a clear radius, a pulse that travels
+ outward, a colour shift on affected units, and a caster animation that shows
+ the source. No invisible buff. Audit it as a field, not a shot: origin, area,
+ ramp, affected-target change, decay.
+- **Rotating emitter / lighthouse.** A continuous sweep is not a turret. Keep the
+ base sweep `theta(t)`, add a short dwell window when a target crosses the
+ beam, and ease in/out of the dwell so the housing never snaps. Fire inside the
+ dwell; return to the sweep with the same phase it would have had. If the beam
+ can point into the goal pocket, mask that sector physically (back-screen,
+ shroud) rather than breaking line of sight with a special case.
+
+If the tower has a crew, the crew reacts: brace, pull, cover ears, crank. A
+crew that stands in the same pose through a cannon shot is a mannequin.
+
+### Machine Grammar (non-combat)
+
+A loom, press, crane, oven, pump or lighthouse lens is not a tower, but it needs
+the same causality. Replace "attack" with **work**:
+
+| Stage | What the player sees | Time |
+| --- | --- | --- |
+| engage | clutch drops, belt tightens, valve opens, lamp housing turns | 0.15 to 0.4 s |
+| work | beam sweep, flywheel spin, ram stroke, dough stretch, water flow | 0.3 to 3 s |
+| output | light pool, pressed sheet, lifted crate, baked loaf, water rise | 0.1 to 0.5 s |
+| settle | flywheel coasts, valve closes, belt slackens, lamp returns | 0.2 to 1 s |
+
+Audit: **input** (what feeds it), **motion** (what turns/strokes), **output**
+(what changes in the world), **residue** (waste, heat, crumbs, steam). A machine
+with a beautiful motion and no output is a kinetic sculpture; give it a product
+and show the product.
+
+### Goal Response Vocabulary
+
+A boss or disaster must act on a **goal**, not just a door. Pick the response
+from the goal's material:
+
+| Goal | Contact response | Failure |
+| --- | --- | --- |
+| door / gate | flash, shake, crack, dust from the lintel | leaf hangs, ward closes |
+| valve / pipe | spray, gauge drop, pipe shudder, hiss | pressure falls, lamp starves |
+| rope / bridge | slack, sag, strands snap, deck drops | span falls, route closes |
+| wall / dam | chip, crack, water seep, block falls | breach, flood |
+| tree / mast | bark split, creak, tilt, leaves fall | trunk breaks, canopy drops |
+
+Put the contact point on the **silhouette edge** of the goal, not buried in its
+body, and keep it clear of the boss's shoulder/weapon. If the goal is tall, put
+the contact at chest height and turn the boss 0.3 to 0.4 rad so the weapon shaft
+crosses the frame. The response and the contact must share the same timestamp.
+
+### Projectile Grammar
+
+1. Spawn at the **muzzle, rail tip, hand or crystal**, not the tower centre.
+2. Give it a fixed flight time or a solved arc; do not integrate physics in the
+ render loop.
+3. Add one trail or one tumble. A bare sphere is a debug object.
+4. On impact, switch to a **species-specific** effect: dust and ring for iron,
+ splinters for wood, goo for slime, feathers for flyers, ice shards for frost.
+5. Remove it on the impact frame. No projectile survives its target.
+
+A projectile that is visible after the target is dead is a bug, not a flourish.
+
+### Creature Animation Grammar
+
+| Archetype | Locomotion | Action | Reaction | Death |
+| --- | --- | --- | --- | --- |
+| small scrapper | scamper, 2-beat | quick stab | flinch + skid | cloth, knife, stain |
+| brute | heavy walk, shoulder roll | overhead cleaver | stagger, shoulder dip | iron plates, sword, dust |
+| slime | squash-hop | lunge | wobble, split | goo splat, two lets |
+| flyer | flap, bank, hover | dive | spiral, feather burst | feathers, spiral fall |
+| boss | weight shift, slow stride | telegraph + slam | recoil, knee dip | collapse, gear, weapon, soul |
+
+Every creature gets a **hit flash** on the body material for 0.08 to 0.12 s and
+a **directional flinch** opposite the impact. Do not reset the whole pose on a
+hit; blend a flinch over the current pose and recover.
+
+Death is a sequence, not a switch:
+
+1. **Impact frame:** freeze or compress the body, flash, drop the weapon.
+2. **Collapse:** 0.25 to 0.5 s; knees buckle, torso folds, flyer spirals.
+3. **Species debris:** 5 to 8 pieces of cloth, iron, goo, feathers, bone.
+4. **Residue:** a stain, scorch, splat or dropped gear that stays for 1 to 3 s.
+5. **Soul:** a brief additive flicker or wisp, 0.2 to 0.4 s, then gone.
+
+A death that is a sphere burst, a grey puff or a rock shower fails the bar even
+if the particle count is high.
+
+### Boss Choreography
+
+A boss exists to **act on a place**, not to have more hit points.
+
+- Stop it outside the threshold by **body depth + weapon reach**. At the gate,
+ that was 2.0 m short of the path end, which left the troll on the drawbridge
+ with the door visible behind the club.
+- Turn it **three-quarter to the goal** (about 0.35 rad off the door axis) so
+ the weapon shaft reads across the frame instead of end-on. An end-on club
+ head is a grey rock at the door.
+- Build the weapon as a separate group: haft, head, two iron bands, six studs,
+ six spikes, and a visible hand attachment. A stone head with no haft is a
+ floating rock.
+- **Telegraph** 0.4 to 0.7 s, contact 0.1 s, recovery 0.3 to 0.5 s. The contact
+ pose is driven by the same gate-hit pulse as the door flash and crack.
+- Put the door response on the same timestamp: flash, shake, crack, dust. If
+ the club hits at 41.075, the door cracks at 41.075, not 41.2.
+- Lose the tower's line of sight to the gate pocket while the boss is there.
+ A beam arriving at the same pixels as the club steals the beat.
+- Prove it with two shots: contact frame and contact +0.2 s. The first shows
+ contact and flash; the second shows recoil. If the club is hidden at contact
+ and only appears on recoil, the pose is late.
+
+### Crowd Variation
+
+- Phase offset per actor: `phase = hash(i) * TAU`, never one global `sin(t)`.
+- Vary speed by 4 to 8 percent, scale by 2 to 4 percent, and idle by phase.
+- Stagger spawns and attack windows by at least 0.15 s. A shared window makes a
+ group move like a chorus line.
+- Give each actor a lane or offset on the path; two actors at the same waypoint
+ stack into one silhouette.
+- At a shared door or gate, one actor reaches the threshold; the rest hold back
+ at `0.9 + i * 0.8` along their own path.
+
+### Secondary Motion
+
+Flags, banners, cloth, chains, hanging bones, smoke and fire are the cheapest
+way to make a static scene feel alive. Rules:
+
+- Drive with `sin(t * f + phase)` and a phase offset per object.
+- Add a lag of 0.1 to 0.2 s behind the parent motion; cloth that moves exactly
+ with the body looks rigid.
+- Keep amplitude small: 0.03 to 0.12 rad for cloth, 0.02 to 0.06 for chains.
+- Cap the count. Six flags at different phases read as wind; twenty read as
+ noise.
+- Never let a secondary object enter the threshold pocket or cover a face.
+
+### Animation QA
+
+For every hero actor, capture:
+
+- a **6-frame strip** of locomotion at 0.1 s spacing;
+- the **action contact frame** and contact +0.2 s;
+- the **death** at impact, mid-collapse and residue;
+- the **boss contact** at the door plus recoil;
+- the **beam** at full channel and the frame after the target dies;
+- a **pivot parentage strip**: freeze at minimum and maximum yaw and log the world
+ positions of every fixed deck prop. They must not move; only the turret and its
+ carriage should. Also check world bounding-box overlap between the fixed
+ station and every mesh under the yaw group: zero hits.
+
+The strip passes when feet plant, knees bend backward, no joint opens a wedge,
+no part floats, and the silhouette changes between frames. A still cannot prove
+an animation; a strip can.
+
diff --git a/references/the-animation-bar.md b/references/the-animation-bar.md
new file mode 100644
index 0000000..7fd4866
--- /dev/null
+++ b/references/the-animation-bar.md
@@ -0,0 +1,37 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## The Animation Bar
+
+An actor is animated when it has all five of these, not just a walk cycle:
+
+1. **Idle / ambient.** Breathing, sway, scan, flame, flag, wing settle. Two
+ loops minimum in the environment.
+2. **Locomotion.** Distance-driven walk, run, hop, flap or slither, with feet
+ planted and joints filled.
+3. **Action.** A readable wind-up, contact and recovery: fire, swing, slam,
+ dive, throw, open, build.
+4. **Reaction.** A directional flinch, hit flash, knockback, stagger or squash
+ that recovers to the same pose.
+5. **Exit / consequence.** In a combat diorama, a body-specific collapse plus
+ debris, dropped gear, a ground stain and a brief residue — never a generic
+ sphere burst. In a social diorama, the equivalent is a role-specific exit:
+ turn, walk out with the bag, close the shutter, or sit back down. The scene
+ must show that the actor changed the place.
+
+Background actors need 1, 2 and 5. Hero actors need all five. A tower is an
+actor too: idle hum, aim, fire, recoil, reload. A service actor's action is
+order/pay/receive, its reaction is a look-up or step-back, and its exit is the
+walk-out with the prop. A prop with a moving part (door, flag, wheel, pulley,
+cauldron) needs its own loop.
+
+**Motion is data.** Author beats as absolute times or travel distances, then
+read them at `t`. Do not hide a state machine inside render-frame conditionals;
+it will pop on a seek, drift on a loop, and be impossible to screenshot.
+
+**Nothing at hero scale is static.** A tower that spawns a projectile from its
+centre without recoil, a boss that stands at a door without touching it, a
+creature that slides without a step: all read as unfinished, even with good
+geometry.
+
diff --git a/references/the-cast.md b/references/the-cast.md
new file mode 100644
index 0000000..acb9fe7
--- /dev/null
+++ b/references/the-cast.md
@@ -0,0 +1,121 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## The Cast
+
+A 1.69 m figure built from primitives, with an anatomical group per joint so
+limbs overlap when they bend. Faces +Z.
+
+| Constant | Value | Notes |
+| --- | --- | --- |
+| hipY | 0.86 | pelvis group height above the root |
+| hipX | 0.10 | half stance width |
+| thigh | 0.42 | hip to knee |
+| shin | 0.40 | knee to ankle |
+| shoulderY | 0.415 | above the pelvis |
+| shoulderX | 0.182 | half shoulder width |
+| upperArm | 0.30 | shoulder to elbow |
+| foreArm | 0.27 | elbow to wrist |
+| headY | 0.584 | neck to head group |
+
+The base swimwear rig uses two spheres (cranium 0.115, jaw 0.089) plus a nose
+box. For a clothed cast, replace that with the skull/jaw/cheek head below. Torso
+and pelvis are lathes (0.135→0.198 and 0.105→0.180), flattened 0.72 in Z so the
+body is an oval, not a tube.
+
+Construction rules:
+
+1. Build joint groups at the pivot, hang geometry **down (-Y)** from them, so a
+ rotation is an anatomical rotation.
+2. Every joint gets a sphere filler just inside the limb radius. Without it a 90
+ degree bend shows a wedge-shaped hole.
+3. Limbs are capsules; torso and pelvis are lathes for a tapered silhouette.
+4. Clothing is layered over the body as its own lathe slightly larger than the
+ pelvis or torso, plus a band cylinder at the waist or chest.
+5. Never parent a part to a group that has not been created yet in the function
+ body: straps added before the torso exists throw on load.
+
+Pose API: `setPose(person, pose)`, `easePose(p, pose, 1-exp(-22*dt))`,
+`blendPose(a, b)` (component-wise add). Angles are `[x,y,z]` radians per joint:
+`torso, head, shoulderL/R, elbowL/R, wristL/R, hipL/R, kneeL/R, ankleL/R`,
+optional `pelvis`.
+
+**Sign conventions, get these right once:**
+
+- Facing +Z. Positive hip X swings the thigh **backward**; negative forward.
+- Positive knee X bends the heel **backward**. Negative hyperextends and reads as
+ a broken leg. This single sign error is the most common "the walk is broken".
+- Positive shoulder X swings the arm backward, negative forward.
+- Negative elbow X folds the forearm toward the face.
+- Positive shoulder Z abducts an arm away from the body; mirror the sign.
+
+Detail that pays, in order: the skull/jaw head in **Clothed Cast** (hair cap
+theta 1.22, eyes at ±0.037, 0.110, 0.101); cap as a crown cylinder, band and
+brim; brow and lid creases; a narrow nose bridge; a three-layer mouth; ears as
+flattened spheres; hands as a palm plus a finger block and thumb; feet with a toe
+box. Fingers, nostrils and micro-seams do not survive 30 px.
+
+Balaclava: one sphere shell over cranium and jaw (r 0.134, scale 1.0/1.10/0.99)
+plus a neck gaiter cylinder running into the collar. A cover cut at the equator
+leaves a band of skin under the hem that reads as a bare head, and eye openings
+tucked under the shell disappear: put pale lids a few millimetres proud of it. A
+darker skin material is `skin.clone()` with `color.multiplyScalar(0.86)`.
+
+### Clothed Cast: Heads, Layers, Hands
+
+The skeleton is shared; the person is made by the head, the garment silhouette
+and the hand contact. For a clothed cast, start from
+`templates/peopleModel-street.js`; `templates/peopleModel.js` remains the
+swimwear/aquatic variant.
+
+**Head.** A skull plus a jaw, not two stacked balls.
+
+- Cranium: sphere r 0.100 at y 0.118, scale [0.98, 1.16, 0.98]. Jaw: r 0.079
+ at y 0.054, scale [0.78, 0.80, 0.86]; chin r 0.029 at y 0.029, z 0.079.
+- Ears: flattened spheres at x ±0.098, y 0.101, with a darker inner bowl. They
+ are what makes the head read in profile.
+- Eyes: a shade socket, a dark iris r 0.0145 scaled flat, a pale catchlight.
+ Brow above, lid crease below, cheek plane under that. At 30 px the socket and
+ brow carry the expression; the iris just anchors the look.
+- Nose: a narrow bridge box plus a tip sphere, 0.022 wide. A single box reads as
+ a beak from three-quarter.
+- Mouth: upper lip in shade, dark seam, lower lip in skin. Three thin layers at
+ most; a wide box reads as a letterbox.
+- Hair: a sphere cap with `thetaLength` 1.22, positioned at y 0.132 and stopping
+ at the hairline. A 1.85 cap swallows the forehead and reads as a helmet. Add a
+ back mass, sideburns, and for a bun a high sphere at y 0.204. Under a hat show
+ a nape tuft; under a full helmet show none.
+- Hats are their own silhouette: beanie (dome + rolled torus + pom), cap (crown
+ + brim + band), bandana (cap + knot + tail), helmet (shell + visor + chin
+ strap + reflective bands). Never draw hair through a helmet or a cap.
+
+**Clothing is geometry, not paint.**
+
+- Base body: torso lathe 0.135→0.198, pelvis lathe 0.105→0.180, flattened 0.72
+ in Z.
+- Garment: a second lathe 4 to 12% larger (`topK` 1.0 tee, 1.05 jacket, 1.12
+ puffer), plus a hem/waistband cylinder. The garment must have a thickness step
+ at the cuff, collar and hem or it reads as body paint.
+- Sleeves: short sleeve ends above the elbow with a cuff ring; long sleeve is a
+ second lathe down the forearm with a ribbed cuff. Do not texture a bare arm and
+ call it a sleeve.
+- Trousers: tapered lathes over thigh and shin with a cuff at the ankle and a
+ break over the shoe. Loose trousers get a wider profile and a deeper cuff, not
+ a scaled leg.
+- Outerwear: jacket shell + zip/lapel/hem; puffer gets 3 horizontal quilt bands;
+ hoodie gets a kangaroo pocket and drawstrings; apron is a front panel with a
+ bib, waist ties and a towel, never a full cylinder around the body.
+- Backpack sits behind the torso with two shoulder straps that cross the front;
+ a bag floating at the spine reads as a growth.
+- High-vis, reflective bands and lanyards are thin boxes proud of the cloth,
+ following the body curve at 2 to 4 mm.
+
+**Hands are the contact proof.** Palm box 0.070 x 0.078 x 0.054, a finger block
+with two grooves and a thumb capsule. A glove is the same geometry in glove
+material, with a cuff. When a hand holds something, the palm and finger block
+must touch it; a wrist near a handle is not a hold.
+
+If the head or the clothing is wrong, fix it before the walk. A good gait cannot
+rescue a sphere head or a painted jacket.
+
diff --git a/references/the-detail-bar.md b/references/the-detail-bar.md
new file mode 100644
index 0000000..bcb941a
--- /dev/null
+++ b/references/the-detail-bar.md
@@ -0,0 +1,127 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## The Detail Bar
+
+A blockout with a camera is not a diorama. The difference between a demo and a
+diorama is **three passes**, and every hero object has to survive all three.
+
+1. **Silhouette.** At 1:1 the object is recognisable from its outline in about
+ 0.2 seconds, before colour or detail.
+2. **Construction.** The silhouette is explained by visible assemblies: posts,
+ rails, bands, plates, wheels, hinges, ropes, fasteners. A single primitive is
+ a placeholder, not a prop.
+3. **Story.** One detail tells you who used it and what happened: a chipped edge,
+ a trophy skull, a repair strap, a spare bolt, a rag, a tally mark, a spent
+ shell. If the detail could be removed without changing the read, it is
+ greeble, not story.
+
+### Whole-object completeness gates (3.17)
+
+Apply these three gates to every hero object in every profile and render preset,
+including educational cutaways. They extend the existing Detail Bar and component
+manifest; they do not add cast, story-prop or mesh-count quotas to educational scenes.
+Evidence is the user's report of a quartz watch missing its straps and back; no
+independent inspection or root-cause diagnosis of that model is claimed here.
+
+1. **Approve the whole-object silhouette, not only the teaching core.** Before
+ detail, record whether the commissioned subject is a complete object, a detached
+ mechanism or an explicit permanent section; default to the complete named object.
+ Reference the entire object and its proportions, not just its most interesting
+ subsystem. A complete wristwatch needs its case and both strap/bracelet sides,
+ not merely a dial or quartz movement. Simplify small surface detail before
+ deleting identity-defining masses. **Evidence:** the reported watch lacked
+ straps despite its watch subject. **Test:** compare grey whole-object front,
+ side and rear views against recorded references, then review desktop/phone
+ delivery frames with the entire silhouette uncropped. Temporarily hide an
+ essential silhouette assembly (for the watch, either strap side); the review
+ must reject it. A close crop of the core cannot pass this gate.
+
+2. **Construct exterior, rear and attachment chains as real assemblies.** An
+ educational explanation of internals does not waive the casing, rear closure,
+ mounting or wearable attachments. Inventory every orbit-exposed side and trace
+ attachments into their seats/joints. For a strapped watch this includes caseback,
+ lugs/spring-bar connections, both strap halves and the reference-appropriate
+ buckle/keeper or clasp; do not impose those exact fittings on a different design.
+ Keep required construction in the model when an explicit Inside mode reveals
+ internals; a label, dark disc or transparency is not a replacement for absent
+ geometry. Honour a commissioned permanent section and document its boundaries.
+ **Evidence:** the same report named the missing back as well as straps.
+ **Test:** review opaque front/rear/side/high orbit crops and attachment-seat
+ close-ups; inspect mesh/group mappings and actual contact/clearance at joints.
+ Exercise cold load → Inside on/off (if present) → Reset to check restoration.
+ Hide the rear closure or disconnect an attachment in a test copy; the matching
+ presence/connection check and visual review must reject it. Existing motion and
+ non-penetration tests still apply; presence alone does not prove sound mechanics.
+
+3. **Close an explicit completeness matrix before claiming completion.** Fill
+ the matching DESIGN sheet before modelling and reconcile it against the built
+ scene before delivery. Give each expected silhouette, exterior/rear, attachment
+ and functional/internal assembly a stable ID, reference or stated assumption,
+ required/simplified/omitted status with scope rationale, mesh/group mapping,
+ connection and proof view plus actual test result. An omission note alone cannot
+ waive an essential part of the commissioned whole object; build it or obtain an
+ explicit scope change. **Evidence:** the reported missing straps/back show why
+ subsystem detail cannot stand in for whole-object coverage. **Test:** reconcile
+ every expected row with nonempty live geometry and reviewed proof; check that
+ the inventory itself covers the whole reference, not just existing meshes.
+ Deliberately remove a required row's mesh, leave its proof blank, and add an
+ unexplained omission in test copies; each must fail the audit. Store commands,
+ results and proof paths in `qa/report.json`. Missing evidence is UNVERIFIED,
+ a missing required assembly is FAIL, and either blocks a completeness pass.
+ This matrix makes omissions reviewable; it is not automatic certification or
+ a guarantee that future agents will comply.
+
+The numbers below are **reference density** from The Hollow Toll, a 21 x 14 m
+slab with four towers, two gate guns, five species, 42 units, one boss, 527
+events and 183 shots. Treat them as a calibration target, not a cap.
+
+| Element | Minimum visible assemblies | Hero target | Required story detail |
+| --- | --- | --- | --- |
+| Tower | 6 | 25 to 45 parts | crew, ammo, livery, wear |
+| Creature | 8 | 12 to 20 parts; boss 40 to 60 | gear, scar, trophy |
+| Prop | 5 | 8 to 15 parts | contents, tool, repair, rag |
+| Landmark | 8 | 30 to 60 parts | one unmistakable silhouette |
+| Death | 3 stages | 5 to 8 pieces + stain + soul | species-specific debris |
+| Environment | 3 scale cues, 3 story props | 2 ambient loops | a before/after trace |
+
+In a social diorama, read the Death row as **Exit**: a role-specific departure
+(turn, walk out, shutter down) with the prop and no debris. The five layers are
+unchanged; the residue is the changed place, not a stain.
+
+**An object can hold two roles.** A lighthouse that is also a beam tower gets
+the landmark budget for its structure **plus** the machine's moving parts; list
+both rows in the design sheet. A boss weapon is a separate group: budget 8 to 12
+parts for the weapon on top of the body, and say so, or the body will be blamed
+for a thin haft.
+
+**Primitive discipline.** No naked box, sphere or cylinder at hero scale. A box
+gets a chamfer, a frame, plank divisions or a band. A sphere becomes a skull,
+bale, sack or head with a snout, ties or a neck. A cylinder gets a foot, cap,
+taper or iron rings. If a shape is still a primitive after the detail pass, it
+will read as a rock, a blob or a placeholder at 30 to 45 px.
+
+**Two to four palette entries per object, plus one accent.** More entries
+turns into noise after the palette snap; fewer turns into a silhouette cut-out.
+Use value contrast for construction and hue for story.
+
+**Detail lives on every orbit-exposed surface.** All presets need coherent backs,
+construction, attachments and cavities; a fixed hero shot is not permission to
+omit parts. Hidden internals may be simplified only if outside the mechanism manifest. Do not add detail
+under about 1.5 screen pixels at the delivery view: it aliases into speckle, not craft.
+
+**Every prop must touch the ground.** Feet, wheels or a structural base must physically meet their declared support surface.
+A contact shadow or stain is visual context, never a substitute for contact. A prop hovering by two centimetres is the single most common "it looks
+cheap" report. Check the shadow and the lowest vertex, not the group origin.
+
+**Every landmark must be the only one of its silhouette.** Two skull trees, two
+red tents or two identical towers read as duplication, not composition. Move,
+scale or redesign the second one. Check overlap by projecting both bounding
+boxes to screen: if they merge into one blob, one is invisible detail.
+
+**Clear thresholds.** For a street-scale narrative, reserve reference-scaled approach space (about 2 m in the calibration scene) in front of a gate,
+portal, spawn mouth or door. No crates, barrels, boulders, bones, vines or
+rising smoke in that pocket. A grey billboard above an arch reads as a rock
+flying out of the entrance even when it is transparent.
+
diff --git a/references/the-look-contract.md b/references/the-look-contract.md
new file mode 100644
index 0000000..1afb34d
--- /dev/null
+++ b/references/the-look-contract.md
@@ -0,0 +1,34 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## The Look Contract
+
+The ten rules below define the **default pixel preset**, not the optional
+stroked-toon preset. Approved stroked-toon builds use the explicit overrides
+above; the remaining scene/animation requirements still hold.
+
+1. **Resettable hero angle + free orbit.** Start azimuth 45, elevation 33, fov
+ 20.5, target just under slab centre. User orbit is enabled in EVERY preset.
+ No auto-spin or timeline camera drift. Reset to this pose before frozen QA.
+2. **Flat cut-out.** A slab with no plinth, no soil sides, background null, page
+ white. Everything below the deck plane hides in the overhang at 33 degrees.
+3. **Palette snap.** Every pixel resolves to one entry of a fixed palette. No
+ gradients survive; banding is the material.
+4. **Ink contour.** A luminance-neighbour edge mixes toward warm near-black at
+ about 0.62, suppressed on the outer rim so figures are not haloed.
+5. **Dither only where tones move.** Ordered Bayer gated by local edge contrast.
+ Flat decks stay flat; ramps stipple.
+6. **Contact shadows, not just cast shadows.** A soft radial patch under every
+ figure and prop is what anchors it to the ground at this scale.
+7. **People read at 30 to 45 px.** Faces need eyes, brows, nose, mouth, ears.
+ Bodies need joint fillers so a bend never opens a wedge.
+8. **Clipped edge.** The slab is a window, not a stage: four world-space clip
+ planes sit on its edges and anything driving in or out is cut at the
+ boundary. Nothing ever floats on the white page outside the block.
+9. **Everything is a pure function of `t`.** No integration that carries state
+ between frames, no `Math.random`, no drift across the loop.
+10. **Empty paper (narrative profile only; educational dock and universal orbit controls are exceptions).** The white page carries no DOM title, caption, HUD or
+ instructions. Put copy on a modelled sign/screen or in the browser title; a
+ label floating on the paper breaks the cut-out.
+
diff --git a/references/universal-inspection-controls.md b/references/universal-inspection-controls.md
new file mode 100644
index 0000000..e329724
--- /dev/null
+++ b/references/universal-inspection-controls.md
@@ -0,0 +1,8 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Universal Inspection Controls
+
+Copy `templates/orbit.js` for EVERY scene and preset. Create it after camera fit with the fitted target; keep animation evaluation independent of camera interaction. Render on control change even when paused. Expose `orbit.reset()` and have the QA freeze wrapper reset it before capture (`freeze(t)` evaluates time synchronously). User pause/freeze UI need not reset their chosen inspection angle. Fit zoom/polar limits to real subject bounds without preventing back/high inspection. No auto-rotation, no camera motion driven by the animation clock. Keep reset + a brief drag/keyboard hint accessible; educational controls and selection follow `Canonical educational UI and inspection contract`.
+
diff --git a/references/vehicles.md b/references/vehicles.md
new file mode 100644
index 0000000..cc8a3b5
--- /dev/null
+++ b/references/vehicles.md
@@ -0,0 +1,263 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Vehicles
+
+A vehicle is the prop the user inspects the moment a door opens, so build it to
+be opened. Model facing +Z.
+
+| Part | Size and place | Note |
+| --- | --- | --- |
+| floor pan | 1.62 x 0.10 x 4.02 at y 0.35 | dark; its top is the cabin floor |
+| rockers | 0.12 x 0.16 x 3.92 at x ±0.87 | stay with the body |
+| front fender | 0.10 x 0.56 x 1.05 at z 1.62 | body side ahead of the front door |
+| rear quarter | 0.10 x 0.56 x 0.72 at z -1.84 | body side behind the rear door |
+| belt moulding | 0.10 x 0.08, one per fixed panel | never one rail across the apertures |
+| bulkheads | 1.84 x 0.56 x 0.16 at z ±2.12 | close the tub |
+| roof | 1.48 x 0.08 x 1.94 at y 1.44 | drip rails at x ±0.76 |
+| pillars | A raked -0.64, B upright, C raked +0.60, 0.075 thick | |
+| windscreen | 1.44 x 0.62 x 0.05, rotation.x -0.64 | glass between the A pillars |
+| side glass | none | windows down: open holes between the pillars |
+
+Cabin: dash 1.46 x 0.15 x 0.30 at y 1.00 z 0.80; wheel torus r 0.125 at
+(-0.40, 1.10, 0.68) rotated -0.42; front cushions 0.46 x 0.10 x 0.50 at y 0.57
+**z 0.30** with backs at z 0.04; rear bench 1.20 wide at z -0.50 with its back at
+z -0.74.
+
+The windscreen is not a plane at the front of the cabin: rotated -0.64 it sweeps
+back to about z 0.59 at its base. A front seat at z 0.72 therefore sits **inside
+the glass volume**, and every occupant's head prints on the windscreen from every
+angle. Keep the cushion's front edge at least 0.25 behind the glass base and move
+the dash, wheel and column back with it.
+
+**Doors.** Hinge at the shut line, leaf extends backward in -Z: front 1.15 to
+-0.15, rear -0.15 to -1.45, leaf 1.30 long and 0.55 high. Pivot at
+`(side*0.86, 0.62, hingeZ)`, children are outer skin, inner card, sill strip,
+handle, and any livery; `rotation.y = -side * open` swings it out. Swing 1.28 rad
+for a saloon, up to 1.52 for a cruiser. Split every full-length body moulding at
+the shut lines: a moulding left on the shell reads as the top of the door left
+behind when it opens.
+
+**Boot.** Pivot at (0, 0.90, -1.46), lid extends -Z, `rotation.x = +0.95` lifts
+the rear edge. Well floor y 0.44 against a lid underside at 0.89, so cargo must
+fit 0.45: bags r 0.165 at y 0.63 (tops 0.80) clear it. Close the boot off from
+the cabin with a parcel shelf (1.74 x 0.05 x 0.66 at y 0.86, z -1.10) and a
+bulkhead behind the rear seat back (1.74 x 0.46 x 0.06 at y 0.63, z -0.82);
+without them the boot is open to the cabin through the rear windows and the load
+reads as sitting on the closed lid.
+
+Cargo carries `visible = false` until it lands and `userData.noMerge = true`.
+A throw needs an object that travels: keep one world-space bag per thrower and arc
+it hand → slot with `p.y += sin(f*PI)*0.6`, switching the slot's bag on when the
+flight lands, not at release.
+
+### Scooters, Cargo Bikes And Mounts
+
+A scooter is not a car with two wheels. Build it around the contact points: two
+tyres on the ground, a floor pan for the boots, a seat the pelvis can sit on, bars
+the hands can reach, and a cargo crate whose opening is visible from the camera.
+
+Reference local frame, facing +Z, for a delivery scooter at 1.0 scale:
+
+| Part | Place | Note |
+| --- | --- | --- |
+| wheels | r 0.26 at z ±0.62 | tyre + hub + fender; both touch y 0 |
+| floor pan | 0.60 x 0.04 x 0.30 at y 0.30 | top is the boot surface |
+| running boards | 0.12 wide at x ±0.235 | outboard, full length; the left boot lands here |
+| body / shield | 0.46 wide, up to y 0.72 | front leg shield, not a box |
+| seat | top 0.83 at z -0.18 | measure the cushion top, not the body |
+| bars | y 1.06, grips x ±0.33, z 0.52 | raise bars to the rider's hands |
+| cargo crate | 0.52 x 0.44 x 0.46, base y 0.86, z -0.56 | open top, interior floor ~0.91 |
+| bungees | two cords across the opening | clip open during loading |
+
+- **Seat anchor.** `seat = local(0, 0.83, -0.18)`; set the root so the **pelvis
+ mesh** contacts the cushion, then prove it in a seated portrait. On the Night
+ Market scooter that is root y 0.09 against a 0.83 seat; do not copy a
+ `seatY - hipY` formula from a chair, because the pelvis mesh hangs below the
+ hip joint. A copied root puts the rider on the front edge or floating.
+- **Boots.** Add outboard running boards at y 0.30 if the floor pan is narrower
+ than the rider's stance. Ankles at 0.30, knees 1.0 to 1.1, toes forward; both
+ soles flat. Perching one boot on the body is the "doll on a toy" read.
+- **Hands.** Grips at the wrist height; a rider with hands 0.15 m above the bars
+ is not holding them. Move the bar/riser up or soften the elbow; do not
+ hyperextend the shoulder.
+- **Cargo.** A crate with an open top needs an interior floor and side walls;
+ a bag lowered to `baseY + 0.01` sits inside. Keep bungees as a separate group so
+ they can unclip during loading and close over the lid afterwards.
+- **Lights.** One emissive lens plus a small halo sprite; a headlight cone only
+ at night. A large additive disc reads as a floating balloon; a brake light is a
+ second, smaller lens, not a copy of the headlight.
+- **Clipping.** The whole vehicle + rider + cargo move as one mover after
+ departure; clip the group at the slab edge, and hide rider shadow at the same
+ time the vehicle shadow takes over.
+
+Mounting is authored with the sequence in **Carrying, Loading And Mounting**:
+left boot on the board, right leg abducted over the saddle, small root arc,
+pelvis on the seat, hands to the grips. Prove it with the nine-frame side strip.
+
+### Buses, Vans And Long Vehicles
+
+A bus is a moving room. Its job is a window band, a door, a route sign and a
+headlight sweep; the chassis is the least visible part.
+
+| Part | Size / place | Note |
+| --- | --- | --- |
+| body | 9 to 12 m long, 2.5 wide, 3.0 high | one box with a chamfered roof |
+| window band | y 1.35 to 2.45, full length | dark glass + warm interior, not a transparent plane |
+| door | 1.1 wide, front or centre | step well, grab rail, lit interior |
+| wheels | r 0.50, wheelbase 5.5 | two axles; arches cut into the skirt |
+| route sign | front above the windscreen | emissive text/colour blocks, readable at 1:1 |
+| livery | one band + one number | never a full advertising wrap at this scale |
+| headlights | two lenses at y 0.65 | plus cones and a floor ellipse |
+| interior | 4 to 6 lit windows + driver silhouette | a dark box with one warm strip reads as a bus |
+
+- **Speed and weight.** 5 to 8 m/s, no bounce; one brake dip at the stop. A bus
+ that bobs like a car reads as a toy. The body leans 0.01 to 0.02 rad on the
+ brake, no more.
+- **Headlight sweep.** Two cones and one long floor pool travel with the bus.
+ Do not light the facade with the cone; a 12 m vehicle with a global spotlight
+ turns night into noon.
+- **Occlusion.** A bus between the camera and an interior hero covers the beat.
+ Put its lane behind glazing at -Z, or time it before/after the contact. Check
+ the occlusion frame at the hero timestamp.
+- **Doors.** If the door opens, model the step well, a grab rail and an interior
+ light; a black rectangle reads as a hole. For a passing bus, keep the door shut.
+- **Clip.** The whole bus, lights, interior and driver move as one group; hide
+ its contact shadow at the slab edge, same frame as the vehicle.
+
+A bus that reads as a white box with black windows is not finished: the window
+band, route sign, wheel arches and one warm interior strip are the minimum.
+
+### Seats, Exits And Transfers
+
+Seat root = cushion top minus hipY, which is **-0.38** in car space on this rig:
+the hips settle into the cushion and a masked head clears the roof with 6 to 8 cm.
+At -0.18 a hooded head lands about a centimetre under the roof panel and any bob
+prints a dark pixel on the white roof. Measure against the head mesh, not the head
+joint, and lower the seat rather than raising the roof, which is pinned to the
+pillars.
+
+The stand spot is 2.00 m out from the car's centreline and 0.30 behind the hinge
+for a front seat, 0.55 for a rear:
+
+```js
+const exit = toWorld(car, side * 2.00, seatZ - 0.30);
+```
+
+An open leaf hangs in the plane of its hinge, so an exit level with the seat puts
+shoulders and head through the door skin. 0.30 still sits inside the aperture and
+leaves room for a torso plus a swinging arm. 2.00 out is about 1.07 of daylight
+from the flank, and that is not padding: at 45/33 a figure 0.7 off the flank sits
+wholly inside the car's silhouette with his feet on the rocker line and reads as
+welded to the body.
+
+The climb is authored in the **car's own frame**, so it works at any parking
+angle. It ships: `templates/transfer.js` is the whole move (`transfer`,
+`climbAt`, `CLIMB`, `stepPose`, `standSpot`), and `templates/poses.js` carries
+the four climb poses plus the walk and run cycles it blends between. Copy them,
+do not retype them. `k` runs 0 at the open door to 1 at the seat, `dy` is the root height
+above the seated root, and the pose is a real sequence: stand, reach, crouch in,
+sit on the edge, swing the legs in, settle.
+
+```js
+const CLIMB = [
+ { u: 0.00, k: 0.00, dy: 0.380, pose: STAND },
+ { u: 0.16, k: 0.03, dy: 0.330, pose: REACH }, // hand to the roof edge
+ { u: 0.36, k: 0.16, dy: 0.120, pose: CROUCH_IN }, // knees deep, hips dropping
+ { u: 0.56, k: 0.38, dy: 0.010, pose: SIT_EDGE }, // perched, feet still down
+ { u: 0.76, k: 0.66, dy: 0.000, pose: LEGS_IN }, // knees up, feet over the sill
+ { u: 0.90, k: 0.88, dy: 0.000, pose: mix(LEGS_IN, SEATED, 0.55) },
+ { u: 1.00, k: 1.00, dy: 0.000, pose: SEATED },
+];
+```
+
+The transfer wraps that climb: the first `STEP_SHARE` (0.26) of the window is one
+stride from the stand spot to the door, the rest is the climb, and on the way out
+the stride away comes last. The body only reaches cushion height once the hips are
+over the sill, so nobody sinks, floats or slides through the bodywork. `DOOR_STAND_X`
+1.34, `DOOR_STAND_DZ` -0.06, durations 1.05 to 1.20 s each way. Never derive the
+duration from the next beat's start: under about 0.9 s the whole move reads as a
+slide or a blur. Move the following beat later instead.
+
+Facing is the trap. The outward yaw points away from the car, so a figure entering
+with it climbs in backwards: body into the seat, face to the street. On the way in
+every key before the seated ones faces the car, including the standing key that
+gets forgotten. Resolve it from geometry, never from the approach path's tangent:
+a path's opening segment runs along the street, so `path.at(0).yaw + PI` points
+down the kerb and lands the figure a right angle off whichever way he arrived.
+
+```js
+const faceYaw = car.yaw - side * (PI / 2); // square to the open door
+const face = Math.atan2(seat.x - stand.x, seat.z - stand.z); // stand -> seat
+// turn to the windscreen only once the hips are on the cushion
+const turn = smooth(clamp((v - 0.62) / 0.30, 0, 1));
+yaw = lerpAngle(faceYaw, car.yaw, turn);
+```
+
+Staging rules that came out of real reports:
+
+- **One window per actor, staggered 0.2 s or more.** A shared window climbs two
+ men into a seat on the same frame, which reads as choreography, and at 0.1 s
+ they climb through each other.
+- **Separate a pair in screen space, not in world space.** At the reset hero 45/33
+ view, moving a figure further out along the camera axis barely changes where it
+ lands on screen: it stays stacked over the car's flank and still reads as one
+ blob, which is why pushing the stand spot from 1.6 m to 2.0 m did not cure a
+ "stuck" report. What separates them is offset along the car's axis, because that
+ is screen x: rear occupant 0.72 behind his hinge against 0.30 for the front
+ leaves 1.2 m of screen distance instead of 0.8, where two figures merge into one
+ silhouette. Project both actors with `v.project(camera)` and compare pixels
+ before concluding they are spaced.
+- **Doors are a timeline, not a state.** Open the leaf 0.15 s before a transfer,
+ shut it 0.5 s after the last man is clear, reopen just before the entry. A car
+ left open for the eight seconds its crew is away reads as the crew stuck in the
+ doorway, however clean the walk is.
+- **A run that ends at the car must not hand straight into the transfer.** End it
+ 0.4 to 0.6 s early, blend out to STAND over the last 12 percent, hold a beat at
+ the door, then climb.
+- **Seated figures stay visible.** Hiding them when the entry ends sends an empty
+ car down the street, which the user reads as a bug, not a cutaway.
+
+### Clear Spots, Shut Doors
+
+- **A shared doorway needs one lane per actor plus a hold-back on the approach.**
+ Actors on the same waypoints put the second in the first's back and stack at the
+ threshold. Offset the approach per actor, stop each one short of the door by
+ `0.9 + i*0.8` along his own path, stagger the walk-in windows by 0.25 s, and let
+ the lead actor alone reach the threshold: the kick, the first step through. Four
+ men then read as a queue filing in rather than a scrum.
+- **Diagnose "stuck" with numbers, not frames.** Freeze in 0.3 s steps across the
+ beat and print every actor's x/z with the pairs closer than 0.6 m. A pair that
+ holds that close for more than one sample is jammed; a single sample is two men
+ passing. At 12 px a figure a screenshot cannot tell those apart, and nudging
+ spacing by eye fixes the wrong thing: the real cause is usually a route that
+ ends where another actor already stands.
+- **Give every actor a route out of every beat.** Two officers left in a cover
+ crouch at the kerb while everyone else moves is a direction bug, and the report
+ is always "they are stuck" however correctly the two are separated.
+
+### Clipping At The Diorama Edge
+
+Vehicles enter and leave the block, and the slab is a window. Four world-space
+planes on the renderer for the scene pass, cleared before the post quad:
+
+```js
+const CLIP = [
+ new THREE.Plane(new THREE.Vector3( 1, 0, 0), hx + 0.05),
+ new THREE.Plane(new THREE.Vector3(-1, 0, 0), hx + 0.05),
+ new THREE.Plane(new THREE.Vector3( 0, 0, 1), hz + 0.05),
+ new THREE.Plane(new THREE.Vector3( 0, 0,-1), hz + 0.05),
+];
+r.clippingPlanes = clipPlanes; r.setRenderTarget(rt); r.render(scene, camera);
+r.clippingPlanes = []; // before the full-screen quad
+```
+
+A car entering nose-first shows its own front surfaces at the cut, so the cut
+reads clean; one leaving tail-first exposes the cut face, so keep the interior
+modelled and it reads as a cutaway. Route every vehicle one way, in at one end of
+the street and out at the other, no reversing and no angled parking: an angled
+park reads as a collision, and backing in reads as a bug. Two vehicles sharing a
+lane need a departure gap (`pLeaveGap` ~1.15 s) or the far one drives through the
+near one.
+
diff --git a/references/verification.md b/references/verification.md
new file mode 100644
index 0000000..94f8cd8
--- /dev/null
+++ b/references/verification.md
@@ -0,0 +1,195 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## Verification
+
+- **Build first, then shoot, then prove the edit landed.** A failed bundle leaves
+ the previous `dist/` in place, and a refused or blocked edit leaves the source
+ untouched, so in both cases every screenshot shows the old app and the fix
+ looks like it did not land. Read the build's own output line, grep for a
+ sentinel string from the change, and only then judge the frame.
+- **Non-vacuous, fresh proof (3.18 evidence + test).** Quartz-watch's rounded
+ box reported runtime `type: BoxGeometry`; a type-name filter produced zero
+ magnet samples and `magnetRadius: 0`, falsely passing clearance. Assert expected
+ object counts, nonempty finite sample sets, positive applicable radii and actual
+ geometry attributes/topology before measuring; never trust a constructor label
+ as shape proof. `templates/mechanism-contract.mjs` assertCoverage and
+ `templates/qa/mechanism-contract.test.mjs` cover helper failure detection;
+ scene probes must additionally inject an empty/type-mismatched sample set,
+ zero radius and a known actual-geometry overlap and reject each. Record fresh
+ source/build hash, successful build command, loaded artifact identity, probe
+ method, counts, tolerances, worst pair/phase and evidence paths in the report.
+ Failures or missing browser/visual/sweep coverage remain FAIL/UNVERIFIED.
+ Never infer full mechanical certification from scalar budgets, 26 numerical
+ highlight states, screenshots alone or a stale successful report. Evidence:
+ historical `quartz-watch/qa/construction-report.json`; no workspace dependency.
+- **Judge orientation from the transform, not the pixels.** At diorama scale a
+ back and a front read the same: a 4x-downscaled strip once made a
+ correctly-facing figure look like he was climbing in backwards, and the
+ "spin" it appeared to do was an artefact of re-reading the crop. Print
+ `group.rotation.y` and compare it with `atan2(dx, dz)` of the expected facing
+ vector before re-shooting a facing fix.
+- Screenshot 1280x800, 1388x950 (iPad landscape) and 390x844 (phone). Zero page
+ errors in all three, and the framing holds at each aspect.
+- Two shots 1.5 s apart differ (the loop is alive) and the camera position is
+ identical after resetting the hero pose.
+- For pixel only, a 1:1 crop shows square pixels, a dark contour and no speckle on flat deck. Toon uses native-resolution smooth contours; hybrid uses one nearest upscale.
+- **Pairwise distance sweep** across every multi-actor beat: freeze in 0.3 s
+ steps, log x/z and the pairs under 0.6 m. Held for two samples means jammed.
+- **Position logs across every one-shot boundary**: consecutive samples differ by
+ centimetres, never by a body length.
+- Isolated portraits per figure: no gaps, knees bend backward, nothing floats.
+- **Queue gate strip.** Sample a walking customer every 0.15 s across two
+ strides; log root speed, `state.moving`, hip/shoulder angles and slot. No
+ standing gesture may be non-zero while speed is non-zero; the leg angles must
+ alternate; serve must be at least 0.25 s after arrival.
+- **Carry contact log.** During every carry beat, print both wrist positions,
+ the prop's world bounds and the distance from each palm to the prop. The palms
+ stay within 0.08 m until release; the prop does not move more than 0.05 m in one
+ frame except during the authored handoff blend.
+- **Mount strip.** Nine side frames from load to seat; log wrists, ankles, prop
+ base and seat. No boot passes through the bars/seat/body, both soles reach the
+ boards, and the rider root follows the seat after departure.
+- **Scale check.** The 30%-smaller request is a camera move; assert
+ `actualDistance / fitDistance ≈ 1 / subjectScale`, the projected slab width fell
+ by the same factor, `post.size ≈ CSS size × renderScale` (capped), the
+ slab/world clip/shadow camera and CSS frame are unchanged, and the standalone
+ still frames on the page.
+- **Night 1:1.** Three distinct dark values, a visible practical with a pool, no
+ clipped white, no pure black. For an interior, the glass must not tint the
+ room; for a passing bus, the occlusion frame at the hero timestamp must still
+ show the hero.
+- **Quadruped strip.** Profile, three-quarter, sit and jump. Ears read as ears,
+ pupils are vertical, rear hocks bend backward, the tail curves; a rabbit or a
+ dog silhouette fails.
+- **Exit strip.** For a social actor: contact, turn, walk out, prop in hand. No
+ debris or stain unless the scene is a death; the residue is the changed place.
+- When a prop never appears, print its world position rather than trusting
+ `visible`. `getWorldPosition` on a merge-eaten object returns local coordinates
+ because the original was unparented; that is the signature of the merge pass.
+
+### Per-entity frame recording
+
+A still cannot prove a jump. A six-frame strip cannot prove that the third
+character in the scene is animating, because the other two are moving in the
+same picture. `qa/frames.mjs` records **one dense series per entity**, and prints
+a verdict for each, so a dead actor cannot hide behind a live neighbour.
+
+```bash
+BASE_URL=http://127.0.0.1:4180/index.html \
+ENTITIES='({ hero: d.cast[0].model, guard: d.cast[1].model })' \
+FROM=4 TO=9 FPS=12 OUT=qa/frames STATIC=guard \
+ node templates/qa/frames.mjs
+```
+
+What it does per entity:
+
+- **Isolates it.** `ISOLATE=scene` (default) hides every mesh not on that
+ entity's branch, so the signature is really about this actor; `siblings` hides
+ the other registry entries only. Restored afterwards.
+- **Fits one camera to the swept bounds** and keeps it for the whole window, so
+ travel stays visible. A camera that follows the actor hides exactly the drift
+ you are looking for.
+- **Samples at `FPS`** (12 by default) across `FROM..TO`, and for each frame logs
+ the world bounds centre in NDC, plus a 32x32 luminance signature.
+- **Scores four ways.** `empty` counts frames where the entity is not on screen,
+ `energy` is the largest mean luminance delta between consecutive on-screen
+ frames (a flat line means the actor is not animating), `step` is the largest
+ NDC jump (a teleport), and `OFFSCREEN` counts frames outside the frustum.
+- **Writes a contact sheet** per entity, `qa/frames/<name>/sheet.png`, and the
+ numbers to `report.json`. Exit code 1 when anything is flagged, so CI can gate.
+
+Reading it:
+
+| Verdict | Means | What to do |
+| --- | --- | --- |
+| `ok` | moved, stayed inside, no jump | still read the sheet for pose quality |
+| `FROZEN` | energy under `MIN_ENERGY` | the pose blend is not reaching this actor |
+| `TELEPORT` | an NDC jump over `MAX_STEP` | a state boundary is snapping, not blending |
+| `EMPTY n/N` | not rendered for over half the window | wrong window, or it spawns later than you think |
+| `NOT-IN-WINDOW` | never rendered in the window | the entity name is wrong, or it is invisible |
+| `OFFSCREEN` | left the frustum | staging, camera fit, or a run that goes too far |
+
+Two rules for the numbers. A blank frame beside a full one must never be allowed
+to supply the energy for a window, so only consecutive on-screen pairs are
+compared. And an entity that is meant to hold still (a seated figure, a guard at
+a post) goes in `STATIC=`, or you will get a `FROZEN` that means nothing.
+
+Run it for every hero actor, and for each scripted beat that involves them:
+send-out, attack, hit, death, exit. The sheet is the evidence; the verdict only
+tells you which sheet to open first.
+
+### Detail And Animation Audit
+
+Run the subject-applicable rows after the build and before shipping.
+Use measured contact plus images; neither alone proves convincing construction.
+
+1. **Grey silhouette.** Hide the palette/post (or desaturate) and shoot the hero
+ frame at 1:1. Every tower, creature, landmark and prop must be nameable from
+ its outline. If two objects merge, restage.
+2. **Hero crops.** One 1:1 crop per tower, one per species, one per landmark, one
+ per large prop. Look for: floating parts, untextured primitives, duplicate
+ silhouettes, sub-pixel speckle, missing contact shadows.
+3. **Threshold crop.** The gate/portal/spawn mouth is empty for 2 m. No smoke,
+ crates, rocks, bones or vines. The boss's weapon is visible against the door.
+4. **Attack strip.** For each weapon tower: acquire, release, travel, impact,
+ recovery. The muzzle/rail/crystal must be visible at release. For a support,
+ aura or field: source, area, ramp, affected-target change, decay. A defence
+ with zero events is a bug in the sim or the data, not "atmosphere".
+5. **Death strip.** For each species: impact, mid-collapse, residue. Debris must
+ be species-specific. A grey puff, sphere burst or rock shower fails.
+6. **Boss contact.** Contact frame plus 0.2 s later. Contact must show the weapon
+ on the goal, the goal's response (flash/crack, spray/gauge drop, sag/snap) and
+ the first consequence; +0.2 s must show recoil or follow-through. The haft
+ and bands must be visible at contact.
+7. **Beam/field on/off.** Full channel, then the frame after the target dies or
+ the field expires. No black band, no beam through the keep, no beam on the
+ corpse, no field left glowing after its timer.
+8. **Crowd strip.** 6 frames at 0.1 s across a group. Actors must not share a
+ phase, stack at one waypoint, or walk through each other.
+9. **Numbers.** Print `events`, `shots` per tower, `deaths` per species, `maxD`
+ per species, loop length and console errors. A species with zero deaths did
+ not finish its route; a tower with zero shots never joined the fight.
+10. **Rectangle and seam test.** Look at every large translucent plane and every
+ slab edge in a 1:1 crop. A hard-edged grey rectangle near a sign is a flat
+ quad halo; a step/lip/black slot at the surface is an unfinished edge. Fix
+ both before the standalone pass.
+11. **Standalone.** Open the built HTML over `file://` once. `ready: true`, no
+ console errors, and a frame that matches the served page.
+
+Keep the proof pack: `shots/hero.png`, `shots/tower-*.png`, `shots/death-*.png`,
+`shots/boss-contact.png`, `shots/boss-recoil.png`, `shots/beam-off.png`. A future
+chat can compare its own pack to these crops.
+
+### New-Chat Handoff
+
+When a different diorama is requested in a fresh chat, the skill should produce
+the same level without re-deriving it:
+
+1. Read SKILL.md and its routed references, then fill `templates/DESIGN.md`. Do not load all references.
+2. Fill the design sheet before coding: premise, camera side, cast, systems,
+ five beats, detail budget.
+3. Block out in grey and shoot the five beats at 1:1.
+4. Build the pipeline in the order in this file: palette, camera, light, post,
+ props, cast, detail pass, animation/systems, effects, QA.
+5. Apply the detail bar per hero object and the animation bar per actor.
+6. Run the detail and animation audit plus `qa/audit.mjs`, not just "does it
+ load".
+7. Ship the standalone and leave `DESIGN.md`, `README.md` and the code agreeing.
+
+If the new subject has no combat, replace tower grammar with **Machine Grammar**
+(loom, press, crane, oven, pump) and creature grammar with **character grammar**
+(customer, worker, animal, vehicle). Audit outputs as fields when there is no
+projectile. The five layers and the audit still apply: idle, locomotion, action,
+reaction, residue.
+
+### Comment Triage
+
+When the user marks a region, project the object instead of guessing pixels:
+`obj.getWorldPosition(v); v.project(camera); px = (v.x*0.5+0.5)*w`.
+If it is not obvious, raycast that pixel and read the first few hits' materials and
+heights: the first hit is the surface they see, the second is what is under it.
+Then fix the marked region and nothing else, and prove it with a zoomed crop at the
+same timestamp.
+
diff --git a/references/when-to-use.md b/references/when-to-use.md
new file mode 100644
index 0000000..be1890b
--- /dev/null
+++ b/references/when-to-use.md
@@ -0,0 +1,24 @@
+# Reference scope
+
+Load only when routed by SKILL.md. The core profile, scale, construction-first and evidence rules take precedence over legacy calibration counts, numerical examples or workflow order here. Subject-specific examples are recipes, not universal requirements. Paths beginning `templates/`, `verify/` or `media/` are relative to the skill root.
+
+## When to Use
+
+- Educational "how does this work?" mechanisms, cutaways and step-through
+ causal explanations; use the Educational Mechanism Profile, not cast quotas.
+- "Make a small diorama / miniature scene / pixel scene of X"
+- A clip or still shows a flat cut-out scene with chunky pixels and little
+ people, and the ask is to match that look
+- An existing 3D scene needs the pixel-art presentation (palette, dither, ink,
+ reset hero angle plus orbit) rather than a smooth render
+- The figures need believable motion: walking, climbing into a car, sitting,
+ swimming, diving, and it has to survive close inspection
+- The ask is for a *staged diorama*, not a model: several systems, a cast, a goal or boss,
+ and a loop that can be frozen at any second
+- The user gives only one line ("a bakery at closing", "a lighthouse under
+ siege"); this skill is designed to turn that into a complete commission
+ without an interview
+
+Don't use for photoreal scenes or full-resolution photographic product renders.
+Every scene MUST support free user orbit by default, including pixel, stroked-toon and pixel-stroke. No separate orbit consent exists. Keep a deterministic hero angle for QA/reset, never auto-spin.
+
diff --git a/templates/DESIGN.md b/templates/DESIGN.md
index 53ae96b..6b24545 100644
--- a/templates/DESIGN.md
+++ b/templates/DESIGN.md
@@ -1,10 +1,56 @@
# <TITLE> — design sheet
> Fill this before modelling. Keep it in sync with `README.md` and the code.
-> A new subject with no verb is a shelf model; give it a conflict.
+> Narrative scenes need scene-first staging, no educational UI by default. Educational scenes need a causal explanation, not cast/ritual quotas.
+> Profile, representation, render preset and UI mode are independent; do not turn an amusement park into a lesson dashboard.
+> Delete educational-only fields below for narrative builds unless that exact feature was requested.
> Delete rows that do not apply, but replace them with the equivalent
> (a machine's goal, a field's area, an ambient loop's period).
+## Profile and hard acceptance
+
+- `sceneProfile`: narrative (default) OR educational; user intent/evidence:
+- `uiMode`: none / minimal-controls / requested-inspection / educational; explicit request or profile reason:
+- `representationMode`: real-subject / teaching-model / explanatory; explicit/default/clarified/delegated + reason:
+- `assetStrategy`: `hybrid` (recommended) / `internet-full` / `authored-only`; explicit answer or delegated choice (unanswered waits):
+- Sourcing gate asked AFTER style; exact user answer; commercial-use/modification/scene-embedding notice shown:
+- Major-role plan: imported vs authored; internet-full gaps need approval before switching to authored; authored-only skips model acquisition, not subject research:
+- Major-role sourcing ledger: role | actual searches | chosen/downloaded source + local file/hash | commercial/modification/scene redistribution evidence | import/style/motion/final-scene inclusion proof | fallback reason:
+- Asset sources/licences: commercial + adaptation + scene redistribution rights; credits/change notices, actual hashes, transitive dependencies and offline packaging:
+### Occupied space and actions (all profiles)
+
+- Independently required physical proxy IDs; actual posed mesh/rig coverage and unsupported cases:
+- Static parcels + doors/awnings/paths; full actor/tail/wing/carry envelopes; clearances in project units:
+- Seats: local support/backrest/footwell frames, rig dimensions, approach/sit/stand/exit states and exclusive time reservations:
+- Dynamic routes: swept width, queue headway, crossing/yield schedule, moving-parent ownership and no doubled root motion:
+- Exact intended contact pairs + phase windows + max depth; separate support-gap checks; nonadjacent self-part coverage:
+- Actual evaluator, unique increasing sample times/events, motion-based refinement + loop seam; sampled/continuous limits:
+- Same-predicate limb/tail/knee/crossing/building fault and restoration results; worst-contact crops/action strip:
+
+### Educational / explicitly requested inspection fields only
+
+Narrative: omit this entire optional block unless the corresponding feature was explicitly requested; do not invent UI, labels or lessons to fill it. Shared geometry, camera and construction checks still apply.
+
+- Educational: one mechanism causal sequence and short input → change → output explanation:
+- Educational UI (only when enabled; explicit UI-free briefs omit): canonical V8 `templates/education-v8.css` + skill DOM contract; ONE reserved 360px right card / bottom dock at <=880px (explicit placement request may override); neutral tokens independent of subject/render preset:
+- Manifest artifact: essential part IDs, parent/support/joint, function/connections, mesh mapping, selection anchor, source, tolerance, proof frame:
+- Declared omissions/symbolic simplifications (unexplained essential omissions fail):
+- Actual drive ratios / phase / units / kinematic equations / contact and clearance invariants:
+- Numeric test command, dense samples + boundaries, results and tolerances:
+- Frozen repeatability / hero desktop + phone / back + high orbit / motion-strip proof:
+- Live local-geometry label anchor → world projection and opaque occlusion checks / nearest visible ray hit / one label at a time:
+- Hidden-part picker: stable assembly ID versus mesh-piece ID/mapping, keyboard access to each intended target, useful revealed view or explicit authored cutaway; no see-through click or disabled depth test:
+- Selection: selected part soft glow + OTHER parts darken, per-mesh shared/multi-material isolation; restore exact material identities/array slots, visibility and cast/receive shadows, dispose owned clones; MeshBasicMaterial receives no added emissive properties:
+- Inspection effect: highlight/dim/ghost settings, declared internal/shell IDs; see skill “Soft glow and holographic inspection — implementation recipe”:
+- Hologram feature-edge threshold/scale filters and decal-edge exclusions, live rigid/deformed/instance transform strategy; authored blocker/reveal plan per hidden target, preserved depth/opaque occlusion, picker exclusion and owned resource cleanup:
+- Glow/hologram proof: per-part desktop/phone before/selected/restored screenshots with measured contrast and occlusion verdicts (emissive > 0 alone never passes an invisible highlight); shared/multi-material exact restore, moving source agreement, Inside-state preservation and rapid reselection without edge/resource growth:
+- Short selection-triggered camera+target focus / fit bounds and panel clearance / previous-view Back + hero Reset:
+- Cancel focus tween on user orbit/pointer/keyboard / no clock-driven chase / reduced-motion immediate view:
+- Acceptance captures: before, selected, restored; rapid reselection; hidden menu selection at multiple frozen phases; Back/Reset and interruption mid-transition:
+- Keyboard focus, dock picker, drag vs click, multitouch cancel, reset proof:
+- Profile/preset checks applied or replaced, reason; UNVERIFIED checks cannot pass:
+- For educational mode delete inapplicable cast, service, multiple-system and ritual sheets below; do not fabricate roles to fill them.
+
## Premise
`[place]` + `[a repeated verb/ritual]` + `[who or what interrupts it]` + `[payoff]`.
@@ -14,17 +60,47 @@ One sentence:
- Archetype (router row):
- Assumption line (scale, loop, systems, cast):
+## Render Preset and Style Confirmation
+
+- Existing repair: original recorded preset/provenance (retain without re-asking), or explicitly requested style change:
+- Gate asked at project start, before the first mesh (SKILL.md `Render Preset Gate`)?:
+- Preset: `pixel` (Classic; recommended) | `stroked-toon` | `pixel-stroke`:
+- User's answer for this build (quote it; never inferred from a reference or from the word "toon"):
+- Explicit style in the request / explicit delegated default ("you pick") -> pixel for new commissions; explicit classic -> pixel; unanswered gate waits:
+- If explicitly delegated: why pixel was kept; no later switch without a new answer. Record a pending question as pending, not answered:
+- Colour family / accent (subject-specific, cream is not mandatory):
+- Paper/background / grain; figure frame/title/readout UI only when explicitly requested (not a toon/hybrid default):
+- Contour width at desktop and phone / no-outline materials and cavities:
+- Camera: mandatory free user orbit + hero reset for EVERY preset, no auto-spin:
+- Render path: Classic PixelPost OR native toon OutlineEffect OR low-res hybrid toon OutlineEffect + nearest upscale; never double edges:
+- Decision receipt: look · sourcing mode · profile · UI mode; unresolved questions and approved exceptions:
+- Shared QA / preset-specific checks / intentionally replaced pixel assertions:
+- Hero construction, attachments, functional connections and related prop clusters:
+
+## Educational UI fidelity (educational with UI only; narrative skips)
+
+- Copied canonical CSS; exact neutral token/computed-style measurements and any user-authorized deviations:
+- One in-card title, Explore default, About closed, no beige/glass/detached masthead/full-height panel:
+- Stage measured separately from card/dock; desktop 1280×800, phone 390×844 and 320×640, 200% zoom proof:
+- Style regression command/results; injected beige/title/full-height failures; missing checks UNVERIFIED:
+- Keyboard tabs/steps/picker, synchronous freeze/text agreement and selected/restored captures:
+
## Camera Side
-- Locked angle: azimuth 45, elevation 33, fov 20.5; fillX/fillY 0.84–0.94
- (fit margin only).
+- Pixel reset hero angle: azimuth 45, elevation 33, fov 20.5; fillX/fillY 0.84–0.94
+ (fit margin only). Approved toon starting point: azimuth 38, elevation 27.5,
+ fov 26; record final fit/angle and mandatory orbit bounds and reset controls:
- Subject scale: 1.0; 0.70 = 30% smaller linearly, more paper (camera only;
frame, slab, clip and shadows unchanged):
+- Closed exterior cold-load/Reset; explicit Inside control and lesson-exit restoration (or commissioned permanent-section exception):
+- Complete swept fit bounds / measured canvas-safe rectangle / protrusion test / desktop-phone-200% zoom proof:
+- Page, renderer, scene and ground/post white-background consistency / empty-corner pixel proof:
- Exterior or interior cutaway:
- Street lane (in front +Z / behind -Z; passing vehicle timing):
- Night palette mix (moon/key / practical / pool):
-- Render buffer: 1× CSS default; 1.2–1.5× renderScale for a small subject;
- 2× only for face close-ups; maxDim / CSS image-rendering:
+- Pixel render buffer: 1× CSS default; 1.2–1.5× renderScale for a small subject;
+ 2× only for face close-ups; maxDim / CSS image-rendering. Approved toon:
+ antialias + native DPR capped at 2, no pixelated CSS; measured fps:
- Slab size / deck height:
- +Z face / hero face (exterior); for an interior cutaway, camera-side wall
omitted and street behind at -Z:
@@ -120,6 +196,34 @@ station / vehicle / creature / prop / landmark. "Parts" is the visible mesh coun
| | | | | | |
| | | | | | |
+## Whole-object completeness matrix (3.17)
+
+Apply the skill's three Whole-object completeness gates to every hero, including
+educational scenes. Keep this sheet even when deleting narrative-only sheets.
+
+- Commissioned scope: complete named object (default) / detached mechanism / explicit permanent section; user wording and section boundaries:
+- Whole-object front/side/rear references, proportions and explicit assumptions:
+- Grey silhouette comparison + uncropped desktop/phone proof paths and reviewed result:
+- Exterior/rear/side/high crops, attachment-seat close-ups and Inside/Reset restoration result (or not applicable with reason):
+
+One row per expected assembly, not merely per mesh already built. Cover silhouette,
+exterior/rear, attachments and functional internals; cross-reference the existing
+component manifest rather than duplicate it. For a strapped quartz wristwatch,
+consider case, dial/crystal, crown, caseback, lugs/spring bars, both strap halves,
+reference-appropriate buckle/keeper or clasp, and the functional movement. Adapt
+to the actual reference; these are not universal fittings or verified watch specs.
+
+| Hero / stable assembly ID | Coverage category | Reference / assumption | Required / simplified / omitted + scope rationale | Live mesh/group mapping | Seat/joint/connection | Proof view/path | Actual check/result |
+| --- | --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | | |
+
+- Reference-to-inventory review (including assemblies absent from the built scene):
+- Required rows reconciled with nonempty live geometry, connection checks and reviewed proof:
+- Negative checks: hidden silhouette assembly, missing rear closure/disconnected attachment, removed required mesh, blank proof and unexplained omission; commands and observed failures:
+- Explicit user-approved scope changes (an omission note alone cannot waive an essential assembly):
+- `qa/report.json` command/results/proof paths; unresolved FAIL / UNVERIFIED items (either blocks completeness pass):
+- Evidence limits: visual/presence checks do not certify mechanics; retain the existing clearance/motion gates:
+
## Contact / Choreography Sheet
Every carry, handoff, load, mount and seat needs a contact timestamp.
@@ -164,13 +268,59 @@ Every carry, handoff, load, mount and seat needs a contact timestamp.
| Ambient loops | | 2+ | |
| Triangles / draw calls | | | |
-## Palette
+## Palette / Authored Colour Family
+Pixel only:
- Length (must equal `uPalette[N]` and the JS array):
- Base entries:
- Accent entries:
- Forbidden: pure black, gradients, unlisted colours.
+Approved stroked-toon only (replace the pixel block above):
+- Named material colours / local contrast / restrained accent:
+- Four shade-ramp bytes / charcoal contour / stroke hierarchy:
+- Lighting and background gradients may survive; no final-pixel palette snap:
+- No-outline materials: cavities, glass, liquid films, decals, vapour:
+- Major/medium/microdetail budget and actual draw-call/fps measurement:
+
+## Animated Effects (arrows, flames, flow)
+
+- Local forward axis and unit test (tip at +Z, base behind, transform dot >.999):
+- Placement: genuinely open volume or a real cut window; never depthTest:false:
+- Depth test/write kept on for effect materials; outline disabled for small FX:
+- Minimum legible scale and exact hide threshold; fade-boundary tested:
+- Measured free band per frame (moving crown/valve faces), positive-gap assert:
+- No port-centreline spline; effect derived from the live free volume:
+- Fit direction-dependent full extent (|dy|*half + flat*head), not the centre:
+- Anchors: tail/tip 0.008 under the valve underside, <=92% of the band:
+- Authored length = max length, so scale <= 1 and the legibility gate is real:
+- One arrow per stroke; never two stacked rows at the same x/z:
+- Effect fades with its source (flame kernel); no orphan arrow:
+- One declared space for every Y constant (scene root lift subtracted):
+- Ignition flash caps: halo opacity <=0.55, halo scale <=0.62, light <=2.2:
+- Full tip/tail/width containment across the complete event, sample interval:
+- Adjacent-degree delta bound on position and scale (no pop/teleport):
+- 15-degree contact sheet per stroke read frame by frame, not four hero stills:
+- Flame kernel: anchor, max height/radius, clearance to crown and head:
+- One idea per primitive; fan separation >= one head-width if used:
+- Phase window per group; mid-stroke counts and zero-leak outside phases:
+- Hollow outlet: connected sleeve+lip, centre-ray open / annulus-ray hit:
+- Real bore/slot at every crossed fixed wall; crossing-plane swept test:
+- Screenshot strip: all strokes from two orbit angles (paths):
+
+## Non-Penetration Gate (all profiles and presets)
+
+- Intended contact/joint pairs, explicitly listed:
+- Non-contact pairs and required positive clearances / units:
+- Full-cycle sweep sample interval, contact-boundary samples and tolerance:
+- Actual complete surface checks (tips, tails, bevels), not centres only:
+- REAL bores/slots through every crossed fixed wall/flange; crossing-plane mesh test:
+- Piston/rod/base flange, cam/follower, head/plug or subject-equivalent checks:
+- Effect free-volume constraints relative to moving solids; depth testing on:
+- Before/contact/after proof frames from two orbit angles:
+- Exact test command, worst measured clearance and report path:
+- Failed or unrun non-penetration check = NOT ACCEPTED:
+
## QA Frames
| Frame | Time | What it proves |
@@ -208,3 +358,35 @@ Every carry, handoff, load, mount and seat needs a contact timestamp.
- Does a boot pass through the bars, seat or body during the mount?
- At night, are there three dark values and a visible practical?
- Does a passing vehicle cover the hero at the contact frame?
+
+
+## Mating interfaces, swept coverage and lesson regression (3.14)
+
+Use project units, explicit local frames and stable surface IDs; do not copy engine dimensions into another subject.
+
+| Interface ID | Parts/surfaces | Source-frame IDs / shaft and bore axes / shared repeated-mount anchor IDs (derive all instances; no separately guessed offsets) | Full shaft/bore or slide geometry + tolerances | Inward bevel/fillet allowance | Radial gap / axial lane/end float + cap endplanes/separation to prevent z-fighting | Source / proof |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+
+| Functional connection | Source port / opening | Destination port / opening | Continuous route and actual bore proof | Support / bearing / bracket / fastener / base load path | Declared simplification |
+| --- | --- | --- | --- | --- | --- |
+| | | | | | |
+
+| Tested surface pair | Full mesh or conservative proxy / exclusions | Full driver range + spacing + extrema/transitions/refinement | Required clearance / worst gap and phase | Intended contact: exact surfaces, window, tolerance, reason | Method limitation / unresolved interval | Command/result/proof crops |
+| --- | --- | --- | --- | --- | --- | --- |
+| | | | | | | |
+
+- Pair coverage inventory and potential-pair omissions (why safe):
+- Nonempty fixture/pair coverage and asserted expected sample counts; actual runtime geometry type (include RoundedBox-labelled geometry reporting Box as a counterexample); injected beam-through-bore, bevel overrun, wrong-axis fillet, lane overflow and non-whitelisted overlap failures:
+- Analytic/continuous bounds versus sampled evidence, explicitly distinguished:
+- Educational UI only (omit for narrative without this request): neutral sans single dock/right-panel layout, progressive disclosure and phone/zoom containment:
+
+Educational lessons only: omit the following step table for ordinary narrative scenes.
+
+| Causal step | Driver phase/time + units | Actual manifest part ID | Input → change → observable result | Frozen evaluator state/readout agreement | Proof |
+| --- | --- | --- | --- | --- | --- |
+| | | | | | |
+
+- Keyboard, focus visibility, touch targets, contrast, reduced motion, no focus trap and no canvas event leakage:
+- QA manifest: final build hash matched to tested geometry/artifacts, exact commands + exit outcomes, expected/actual sample counts, nonempty fixtures, negative-injection failures and proof paths; only for implemented/requested features: UI desktop/phone + 200% zoom, step/scrub agreement, rapid changes, picker and selection/material results. Always test applicable pause/orbit/reset and scene camera fit:
+- Unrun or failing checks (UNVERIFIED/FAIL, never implied pass):
diff --git a/templates/action-clearance.mjs b/templates/action-clearance.mjs
new file mode 100644
index 0000000..10de53d
--- /dev/null
+++ b/templates/action-clearance.mjs
@@ -0,0 +1,200 @@
+/** World-space motion proxies only: no automatic mesh, skin, material or geometry coverage.
+ * Sampled audits are not continuous proofs. Callers must freeze/restore their own scene state.
+ * OBB SAT reports an axis bound, NOT exact Euclidean distance or mesh penetration.
+ * API: sphere(center,radius), capsule(a,b,radius), obb(center,halfSize,quaternion?).
+ * Vectors accept [x,y,z] or THREE.Vector3; quaternion accepts [x,y,z,w] or Quaternion.
+ * auditPose({parts:[{id,owner?,getShape(time)}],requiredIds?,time=0,clearance=0,contacts=[]}).
+ * requiredIds is an independent expected proxy inventory: nonempty, unique, exact match.
+ * Reports coverageVerified:true only with that inventory; omission means unknown coverage,
+ * never certification of complete scene/geometry coverage. Motion propagates this flag.
+ * owner is metadata only: ALL distinct proxies, including same-owner parts, are checked.
+ * Contacts: {a,b,start,end,maxPenetration,reason}; inclusive window, exact proxy ids.
+ * pairCheck(a,b) => {separation,penetration,method}; negative means proxy overlap.
+ * auditPose => {clear,collisions,methods,sampledOnly:true,testedPairs}.
+ * auditMotion({source:{evaluate(t)},times,...pose}) => {clear,samples,worstCases,
+ * methods,sampledOnly:true}; requires >=2 strictly increasing finite times and a
+ * synchronous evaluator; evaluates exactly those times, leaving final state.
+ * Static checks use auditPose; missing/repeated samples are not motion coverage.
+ * timesForInterval(start,end,{maxStep,eventTimes=[]}) builds a sorted distinct grid.
+ */
+export function createActionClearance(THREE) {
+ const { Vector3: V, Quaternion: Q } = THREE;
+ const finite = (n, label) => { if (!Number.isFinite(n)) throw new TypeError(`${label} must be finite`); return n; };
+ const positive = (n, label) => { finite(n, label); if (n <= 0) throw new RangeError(`${label} must be positive`); return n; };
+ const vector = (v, label) => {
+ const a = Array.isArray(v) ? v : [v?.x, v?.y, v?.z];
+ if (a.length !== 3) throw new TypeError(`${label} requires three components`);
+ return new V(...a.map(n => finite(n, label)));
+ };
+ const sphere = (center, radius) => ({ type: 'sphere', center: vector(center, 'center'), radius: positive(radius, 'radius') });
+ const capsule = (a, b, radius) => ({ type: 'capsule', a: vector(a, 'a'), b: vector(b, 'b'), radius: positive(radius, 'radius') });
+ const obb = (center, halfSize, quaternion = [0, 0, 0, 1]) => {
+ const h = vector(halfSize, 'halfSize'); h.toArray().forEach(n => positive(n, 'halfSize'));
+ const a = Array.isArray(quaternion) ? quaternion : [quaternion?.x, quaternion?.y, quaternion?.z, quaternion?.w];
+ if (a.length !== 4) throw new TypeError('quaternion requires four components');
+ a.forEach(n => finite(n, 'quaternion'));
+ const scale = Math.max(...a.map(Math.abs));
+ if (!scale) throw new RangeError('quaternion must be nonzero');
+ const q = new Q(...a.map(n => n / scale)).normalize();
+ return { type: 'obb', center: vector(center, 'center'), halfSize: h, quaternion: q };
+ };
+ const shape = s => {
+ if (s?.type === 'sphere') return sphere(s.center, s.radius);
+ if (s?.type === 'capsule') return capsule(s.a, s.b, s.radius);
+ if (s?.type === 'obb') return obb(s.center, s.halfSize, s.quaternion);
+ throw new TypeError('unsupported or missing proxy shape');
+ };
+ const asCapsule = s => s.type === 'sphere' ? { a: s.center, b: s.center, radius: s.radius } : s;
+ const clamp = n => Math.max(0, Math.min(1, n));
+ function segmentDistance(a, b) {
+ const u = a.b.clone().sub(a.a), v = b.b.clone().sub(b.a), w = a.a.clone().sub(b.a);
+ const A = u.dot(u), B = u.dot(v), C = v.dot(v), D = u.dot(w), E = v.dot(w);
+ let s = 0, t = 0;
+ if (!A && !C) return w.length();
+ if (!A) t = clamp(E / C);
+ else if (!C) s = clamp(-D / A);
+ else {
+ const det = A * C - B * B;
+ s = det > 0 ? clamp((B * E - C * D) / det) : 0;
+ t = (B * s + E) / C;
+ if (t < 0) { t = 0; s = clamp(-D / A); }
+ else if (t > 1) { t = 1; s = clamp((B - D) / A); }
+ }
+ return w.addScaledVector(u, s).addScaledVector(v, -t).length();
+ }
+ // Piecewise quadratic outside distance; inside, minimize the maximum of six
+ // affine face SDFs. Their intersections include the deepest centerline point.
+ function segmentBox(c, box) {
+ const inverse = box.quaternion.clone().invert();
+ const a = c.a.clone().sub(box.center).applyQuaternion(inverse).toArray();
+ const b = c.b.clone().sub(box.center).applyQuaternion(inverse).toArray();
+ const h = box.halfSize.toArray(), d = b.map((n, i) => n - a[i]);
+ const faces = h.flatMap((n, i) => [[a[i] - n, d[i]], [-a[i] - n, -d[i]]]);
+ const cuts = [0, 1];
+ for (const [p, q] of faces) if (q && -p / q > 0 && -p / q < 1) cuts.push(-p / q);
+ cuts.sort((x, y) => x - y);
+ const candidates = [...cuts];
+ for (let i = 0; i < cuts.length - 1; i++) {
+ const mid = (cuts[i] + cuts[i + 1]) / 2;
+ let A = 0, B = 0;
+ for (let k = 0; k < 3; k++) {
+ const x = a[k] + d[k] * mid;
+ if (Math.abs(x) > h[k]) { const p = a[k] - Math.sign(x) * h[k]; A += d[k] ** 2; B += p * d[k]; }
+ }
+ if (A) candidates.push(Math.max(cuts[i], Math.min(cuts[i + 1], -B / A)));
+ }
+ for (let i = 0; i < 6; i++) for (let j = i + 1; j < 6; j++) {
+ const denom = faces[i][1] - faces[j][1];
+ if (denom) { const t = (faces[j][0] - faces[i][0]) / denom; if (t >= 0 && t <= 1) candidates.push(t); }
+ }
+ const sdf = t => {
+ const q = a.map((n, i) => Math.abs(n + d[i] * t) - h[i]);
+ return Math.hypot(...q.map(n => Math.max(n, 0))) + Math.min(Math.max(...q), 0);
+ };
+ return Math.min(...candidates.map(sdf)) - c.radius;
+ }
+ const axes = b => [new V(1, 0, 0), new V(0, 1, 0), new V(0, 0, 1)].map(v => v.applyQuaternion(b.quaternion));
+ function boxSAT(a, b) {
+ const aa = axes(a), bb = axes(b), delta = b.center.clone().sub(a.center);
+ const candidates = [...aa, ...bb, ...aa.flatMap(u => bb.map(v => u.clone().cross(v)))];
+ let separation = -Infinity;
+ for (const axis of candidates) {
+ if (axis.lengthSq() < 1e-24) continue;
+ axis.normalize();
+ const radius = (box, basis) => basis.reduce((s, v, i) => s + Math.abs(axis.dot(v)) * box.halfSize.getComponent(i), 0);
+ separation = Math.max(separation, Math.abs(delta.dot(axis)) - radius(a, aa) - radius(b, bb));
+ }
+ return separation;
+ }
+ function pairCheck(first, second) {
+ const a = shape(first), b = shape(second);
+ let separation, method;
+ if (a.type === 'obb' && b.type === 'obb') { separation = boxSAT(a, b); method = 'obb-obb-sat-axis-bound'; }
+ else if (a.type === 'obb' || b.type === 'obb') {
+ separation = a.type === 'obb' ? segmentBox(asCapsule(b), a) : segmentBox(asCapsule(a), b);
+ method = 'capsule-obb-exact-outside-deepest-centerline-sdf-inside';
+ } else { separation = segmentDistance(asCapsule(a), asCapsule(b)) - a.radius - b.radius; method = 'capsule-capsule-segment-distance'; }
+ finite(separation, 'computed separation');
+ return { separation, penetration: Math.max(0, -separation), method };
+ }
+ function bounds(s, margin) {
+ if (s.type !== 'obb') {
+ const c = asCapsule(s), r = c.radius + margin;
+ return { min: c.a.clone().min(c.b).addScalar(-r), max: c.a.clone().max(c.b).addScalar(r) };
+ }
+ const e = new V(), basis = axes(s);
+ for (let i = 0; i < 3; i++) e.add(basis[i].clone().set(Math.abs(basis[i].x), Math.abs(basis[i].y), Math.abs(basis[i].z)).multiplyScalar(s.halfSize.getComponent(i)));
+ e.addScalar(margin);
+ return { min: s.center.clone().sub(e), max: s.center.clone().add(e) };
+ }
+ const id = v => { if (typeof v !== 'string' || !v.trim()) throw new TypeError('proxy id must be nonempty string'); return v; };
+ const key = (a, b) => JSON.stringify([a, b].sort());
+ function auditPose({ parts, requiredIds, time = 0, clearance = 0, contacts = [] } = {}) {
+ finite(time, 'time'); finite(clearance, 'clearance');
+ if (clearance < 0 || !Array.isArray(parts) || !parts.length || !Array.isArray(contacts)) throw new TypeError('nonempty parts and nonnegative clearance required');
+ const ids = new Set();
+ for (const p of parts) {
+ id(p?.id); if (ids.has(p.id)) throw new TypeError(`duplicate proxy id ${p.id}`); ids.add(p.id);
+ if (typeof p.getShape !== 'function') throw new TypeError('getShape callback required');
+ }
+ const coverageVerified = requiredIds !== undefined;
+ if (coverageVerified) {
+ if (!Array.isArray(requiredIds) || !requiredIds.length) throw new TypeError('requiredIds must be a nonempty unique id array');
+ const expected = new Set();
+ for (const value of requiredIds) { id(value); if (expected.has(value)) throw new TypeError('duplicate required id'); expected.add(value); }
+ if (expected.size !== ids.size || [...expected].some(value => !ids.has(value))) throw new TypeError('proxy coverage mismatch: missing or extra ids');
+ }
+ const evaluated = parts.map(p => {
+ const s = shape(p.getShape(time)); return { id: p.id, shape: s, ...bounds(s, clearance / 2) };
+ });
+ const rules = new Map();
+ for (const c of contacts) {
+ id(c?.a); id(c?.b);
+ if (c.a === c.b || !ids.has(c.a) || !ids.has(c.b)) throw new TypeError('contact references missing or identical proxy ids');
+ finite(c.start, 'contact start'); finite(c.end, 'contact end'); finite(c.maxPenetration, 'maxPenetration');
+ if (c.end < c.start || c.maxPenetration < 0 || typeof c.reason !== 'string' || !c.reason.trim()) throw new TypeError('invalid bounded contact');
+ const k = key(c.a, c.b); if (rules.has(k)) throw new TypeError('duplicate contact pair'); rules.set(k, c);
+ }
+ evaluated.sort((a, b) => a.min.x - b.min.x || (a.id < b.id ? -1 : 1));
+ const collisions = [], methods = new Set(); let active = [], testedPairs = 0;
+ for (const b of evaluated) {
+ active = active.filter(a => a.max.x >= b.min.x);
+ for (const a of active) {
+ if (a.max.y < b.min.y || b.max.y < a.min.y || a.max.z < b.min.z || b.max.z < a.min.z) continue;
+ const result = pairCheck(a.shape, b.shape); testedPairs++; methods.add(result.method);
+ const rule = rules.get(key(a.id, b.id));
+ const allowed = rule && time >= rule.start && time <= rule.end && result.penetration <= rule.maxPenetration;
+ if (result.separation < clearance && !allowed) collisions.push({ a: [a.id, b.id].sort()[0], b: [a.id, b.id].sort()[1], time, ...result, kind: result.separation < 0 ? 'proxy-overlap' : 'clearance-violation' });
+ }
+ active.push(b);
+ }
+ collisions.sort((a, b) => a.a < b.a ? -1 : a.a > b.a ? 1 : a.b < b.b ? -1 : a.b > b.b ? 1 : 0);
+ return { clear: !collisions.length, coverageVerified, collisions, methods: [...methods].sort(), sampledOnly: true, testedPairs };
+ }
+ function timesForInterval(start, end, { maxStep, eventTimes = [] } = {}) {
+ finite(start, 'start'); finite(end, 'end'); positive(maxStep, 'maxStep');
+ if (end < start || !Array.isArray(eventTimes)) throw new TypeError('invalid interval');
+ const n = Math.ceil((end - start) / maxStep);
+ if (!Number.isSafeInteger(n) || n > 1e6) throw new RangeError('sample grid too large');
+ const times = [start, end];
+ for (let i = 1; i < n; i++) times.push(start + (end - start) * (i / n));
+ for (const t of eventTimes) { finite(t, 'event time'); if (t < start || t > end) throw new RangeError('event time outside interval'); times.push(t); }
+ return [...new Set(times)].sort((a, b) => a - b);
+ }
+ function auditMotion({ source, times, ...pose } = {}) {
+ if (typeof source?.evaluate !== 'function' || !Array.isArray(times) || times.length < 2) throw new TypeError('source.evaluate and at least two sample times required');
+ for (let i = 0; i < times.length; i++) {
+ finite(times[i], 'sample time');
+ if (i && times[i] <= times[i - 1]) throw new RangeError('sample times must be strictly increasing');
+ }
+ const samples = times.map(time => {
+ const result = source.evaluate(time);
+ if (result != null && typeof result.then === 'function') throw new TypeError('source.evaluate must be synchronous');
+ return { time, ...auditPose({ ...pose, time }) };
+ });
+ const worst = new Map();
+ for (const sample of samples) for (const c of sample.collisions) { const k = key(c.a, c.b); if (!worst.has(k) || c.separation < worst.get(k).separation) worst.set(k, c); }
+ return { clear: samples.every(s => s.clear), coverageVerified: samples.every(s => s.coverageVerified), sampledOnly: true, samples, worstCases: [...worst.values()], methods: [...new Set(samples.flatMap(s => s.methods))].sort() };
+ }
+ return { sphere, capsule, obb, pairCheck, auditPose, timesForInterval, auditMotion };
+}
diff --git a/templates/camera.js b/templates/camera.js
index 33f77dd..8295d6d 100644
--- a/templates/camera.js
+++ b/templates/camera.js
@@ -1,9 +1,10 @@
import * as THREE from 'three';
/**
- * Locked three-quarter camera. Distance is solved against a set of fit points
- * (slab corners plus the tops of tall props) so the play keeps its white
- * margin at every aspect ratio. Nothing here orbits or drifts.
+ * Reset hero three-quarter camera. Distance is solved against fit points
+ * (slab corners plus tall props) for a stable margin at each aspect ratio.
+ * REQUIRED: attach createDioramaOrbit from orbit.js after fitting in every preset.
+ * This module only solves the deterministic hero pose; it never auto-spins.
*/
export const CAMERA = {
fov: 20.5,
diff --git a/templates/construction-kit.js b/templates/construction-kit.js
new file mode 100644
index 0000000..8e90abb
--- /dev/null
+++ b/templates/construction-kit.js
@@ -0,0 +1,137 @@
+// Dependency injection keeps this module independent of a particular Three.js install.
+export function createConstructionKit(THREE) {
+ const finite = (n, label) => { if (!Number.isFinite(n)) throw new TypeError(`${label} must be finite`); return n; };
+ const positive = (n, label) => { finite(n, label); if (n <= 0) throw new RangeError(`${label} must be positive`); return n; };
+ function vector(value, label) {
+ const a = value?.isVector3 ? [value.x, value.y, value.z] : value;
+ if (!Array.isArray(a) || a.length !== 3) throw new TypeError(`${label} must have three coordinates`);
+ return new THREE.Vector3(...a.map(n => finite(n, label)));
+ }
+ function mesh(parent, material, geometry, name) {
+ if (!parent?.isObject3D || !material?.isMaterial) throw new TypeError('Object3D parent and Material required');
+ const result = new THREE.Mesh(geometry, material);
+ if (name !== undefined) { if (typeof name !== 'string') throw new TypeError('name must be a string'); result.name = name; }
+ parent.add(result);
+ return result;
+ }
+ function boxAtBase(parent, mat, { size, base, name }) {
+ const dimensions = vector(size, 'size');
+ [dimensions.x, dimensions.y, dimensions.z].forEach(n => positive(n, 'size'));
+ const position = vector(base, 'base');
+ position.y += dimensions.y / 2;
+ const result = mesh(parent, mat, new THREE.BoxGeometry(dimensions.x, dimensions.y, dimensions.z), name);
+ result.position.copy(position);
+ return result;
+ }
+ function between(parent, mat, { a, b, radius, radialSegments = 24, name }) {
+ const start = vector(a, 'a'), end = vector(b, 'b');
+ const axis = end.clone().sub(start), length = positive(axis.length(), 'endpoint separation');
+ positive(radius, 'radius');
+ if (!Number.isInteger(radialSegments) || radialSegments < 3) throw new RangeError('radialSegments must be an integer >= 3');
+ const result = mesh(parent, mat, new THREE.CylinderGeometry(radius, radius, length, radialSegments), name);
+ result.position.copy(start).add(end).multiplyScalar(0.5);
+ result.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), axis.normalize());
+ return result;
+ }
+ function gridFrames({ columns, rows, spacing, center }) {
+ if (![columns, rows].every(n => Number.isSafeInteger(n) && n > 0)) throw new RangeError('positive integer grid counts required');
+ if (!Array.isArray(spacing) || spacing.length !== 2) throw new TypeError('spacing is [x,z]');
+ spacing.forEach(n => positive(n, 'spacing'));
+ const origin = vector(center, 'grid center'), frames = [];
+ for (let row = 0; row < rows; row++) for (let column = 0; column < columns; column++) frames.push({
+ row, column, position: origin.clone().add(new THREE.Vector3((column - (columns - 1) / 2) * spacing[0], 0, (row - (rows - 1) / 2) * spacing[1])),
+ quaternion: new THREE.Quaternion(),
+ });
+ return frames;
+ }
+ function radialFrames({ count, radius, center, phase = 0 }) {
+ if (!Number.isSafeInteger(count) || count < 1) throw new RangeError('positive integer radial count required');
+ positive(radius, 'radius'); finite(phase, 'phase'); const origin = vector(center, 'radial center');
+ return Array.from({ length: count }, (_, index) => {
+ const angle = phase + index * Math.PI * 2 / count;
+ return { index, angle, position: origin.clone().add(new THREE.Vector3(radius * Math.cos(angle), 0, -radius * Math.sin(angle))),
+ quaternion: new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle) };
+ });
+ }
+ function plateWithHoles(parent, mat, { width, depth, thickness, holes = [], base, name }) {
+ [width, depth, thickness].forEach(n => positive(n, 'plate dimension'));
+ const position = vector(base, 'base');
+ if (!Array.isArray(holes)) throw new TypeError('holes must be an array');
+ holes.forEach(({ x, z, radius }, i) => {
+ finite(x, 'hole x'); finite(z, 'hole z'); positive(radius, 'hole radius');
+ if (Math.abs(x) + radius >= width / 2 || Math.abs(z) + radius >= depth / 2) throw new RangeError('hole must be strictly inside plate');
+ holes.slice(0, i).forEach(h => { if (Math.hypot(x - h.x, z - h.z) <= radius + h.radius) throw new RangeError('holes must not touch or overlap'); });
+ });
+ // Shape XY -> world XZ: local Y becomes -Z and extrusion +Z becomes +Y.
+ const shape = new THREE.Shape();
+ shape.moveTo(-width / 2, -depth / 2); shape.lineTo(width / 2, -depth / 2);
+ shape.lineTo(width / 2, depth / 2); shape.lineTo(-width / 2, depth / 2); shape.closePath();
+ holes.forEach(({ x, z, radius }) => {
+ const hole = new THREE.Path(); hole.absarc(x, -z, radius, 0, Math.PI * 2, true); shape.holes.push(hole);
+ });
+ const geometry = new THREE.ExtrudeGeometry(shape, { depth: thickness, bevelEnabled: false, curveSegments: 32, steps: 1 });
+ geometry.rotateX(-Math.PI / 2);
+ const result = mesh(parent, mat, geometry, name); result.position.copy(position); return result;
+ }
+ function collectWorldPoints(root) {
+ if (!root?.isObject3D) throw new TypeError('root must be Object3D');
+ root.updateWorldMatrix(true, true);
+ const points = [];
+ function visit(object, visible) {
+ visible = visible && object.visible;
+ if (!visible) return;
+ if (object.isSkinnedMesh || object.isInstancedMesh || Object.values(object.geometry?.morphAttributes || {}).some(a => a.length)) throw new Error('deformed or instanced geometry is unsupported');
+ const geometry = object.geometry;
+ if (geometry) {
+ const position = geometry.getAttribute('position');
+ if (!position || position.itemSize !== 3) throw new Error('geometry needs three-component positions');
+ const index = geometry.index, count = index ? index.count : position.count;
+ const start = geometry.drawRange.start, end = Math.min(count, start + geometry.drawRange.count);
+ for (let i = start; i < end; i++) {
+ const groups = geometry.groups;
+ const material = Array.isArray(object.material)
+ ? groups.filter(g => i >= g.start && i < g.start + g.count).map(g => object.material[g.materialIndex])
+ : [object.material];
+ if (!material.some(m => m && m.visible !== false)) continue;
+ const point = new THREE.Vector3().fromBufferAttribute(position, index ? index.getX(i) : i).applyMatrix4(object.matrixWorld);
+ vector(point, 'world vertex'); points.push(point);
+ }
+ }
+ object.children.forEach(child => visit(child, visible));
+ }
+ let ancestorsVisible = true;
+ for (let p = root.parent; p; p = p.parent) ancestorsVisible &&= p.visible;
+ visit(root, ancestorsVisible);
+ return points;
+ }
+ function fitPerspective(camera, { points, direction, target, aspect = camera.aspect, margin = 0.08 }) {
+ if (!camera?.isPerspectiveCamera || camera.parent) throw new TypeError('unparented PerspectiveCamera required');
+ if (!Array.isArray(points) || !points.length) throw new TypeError('nonempty points required');
+ const vertices = points.map(p => vector(p, 'point'));
+ const outward = vector(direction, 'direction'); positive(outward.length(), 'direction length'); outward.normalize();
+ positive(aspect, 'aspect'); finite(margin, 'margin');
+ if (margin < 0 || margin > 0.4) throw new RangeError('margin must be in [0, 0.4]');
+ positive(camera.near, 'near'); positive(camera.zoom, 'zoom');
+ if (!(camera.fov > 0 && camera.fov < 180) || !Number.isFinite(camera.fov)) throw new RangeError('invalid fov');
+ if (camera.view?.enabled || camera.filmOffset !== 0) throw new Error('asymmetric frustum unsupported');
+ const center = target === undefined ? new THREE.Box3().setFromPoints(vertices).getCenter(new THREE.Vector3()) : vector(target, 'target');
+ const up = new THREE.Vector3(0, 1, 0);
+ if (Math.abs(outward.dot(up)) > 0.999) up.set(0, 0, 1);
+ const right = up.clone().cross(outward).normalize(), vertical = outward.clone().cross(right).normalize();
+ const tanY = Math.tan(THREE.MathUtils.degToRad(camera.fov / 2)) / camera.zoom;
+ const safe = 1 - margin, tanX = tanY * aspect;
+ let distance = camera.near * 1.1;
+ vertices.forEach(p => {
+ const relative = p.clone().sub(center), along = relative.dot(outward);
+ distance = Math.max(distance, along + Math.abs(relative.dot(right)) / (tanX * safe), along + Math.abs(relative.dot(vertical)) / (tanY * safe), along + camera.near * 1.1);
+ });
+ distance *= 1 + 1e-10;
+ finite(distance, 'fit distance');
+ camera.aspect = aspect; camera.up.copy(up); camera.position.copy(center).addScaledVector(outward, distance);
+ const maxDepth = vertices.reduce((depth, p) => Math.max(depth, distance - p.clone().sub(center).dot(outward)), 0);
+ camera.far = Math.max(positive(camera.far, 'far'), maxDepth * 1.1, camera.near * 2);
+ camera.lookAt(center); camera.updateProjectionMatrix(); camera.updateMatrixWorld(true);
+ return { target: center, distance, position: camera.position.clone(), quaternion: camera.quaternion.clone() };
+ }
+ return { boxAtBase, between, gridFrames, radialFrames, plateWithHoles, collectWorldPoints, fitPerspective };
+}
diff --git a/templates/education-dock.css b/templates/education-dock.css
new file mode 100644
index 0000000..f0abb2e
--- /dev/null
+++ b/templates/education-dock.css
@@ -0,0 +1,18 @@
+/* Match renderer clear/scene/ground separately; CSS cannot recolour an opaque canvas. */
+.education-stage { background: #fff; }
+.education-dock { position: fixed; inset: auto 1rem 1rem; margin-inline: auto; width: min(38rem, calc(100% - 2rem)); box-sizing: border-box; max-height: 45dvh; overflow: auto; padding: .85rem; background: #fafafa; color: #18181b; border: 1px solid #d4d4d8; border-radius: .75rem; box-shadow: 0 4px 16px #0000000d; font: 14px/1.45 ui-sans-serif, system-ui, sans-serif; }
+.education-dock h1 { margin: 0; font-size: 1rem; font-weight: 600; }
+.education-dock p { margin: .4rem 0; }
+.education-controls { display: flex; flex-wrap: wrap; align-items: center; gap: .4rem .65rem; }
+.education-controls label { display: inline-flex; align-items: center; gap: .4rem; max-width: 100%; }
+.education-dock button, .education-dock select { font: inherit; color: inherit; background: #fff; border: 1px solid #a1a1aa; border-radius: .4rem; padding: .4rem .6rem; min-height: 44px; max-width: 100%; }
+.education-dock button { cursor: pointer; }
+.education-dock input[type=range] { width: 8rem; min-height: 44px; accent-color: #3f3f46; }
+.education-dock :focus-visible { outline: 2px solid #18181b; outline-offset: 3px; }
+.education-dock summary { cursor: pointer; min-height: 44px; display: list-item; align-content: center; }
+.education-dock [aria-current=step] { background: #18181b; color: #fafafa; }
+.education-dock output { display: block; font-variant-numeric: tabular-nums; }
+.education-dock ol { margin: .3rem 0; padding-left: 1.5rem; }
+.education-sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
+@media (max-width: 480px) { .education-dock { inset: auto .5rem .5rem; width: calc(100% - 1rem); padding: .65rem; font-size: 14px; } }
+@media (prefers-reduced-motion: reduce) { .education-dock *, .education-dock { scroll-behavior: auto; transition: none; animation: none; } }
diff --git a/templates/education-dock.mjs b/templates/education-dock.mjs
new file mode 100644
index 0000000..671c224
--- /dev/null
+++ b/templates/education-dock.mjs
@@ -0,0 +1,58 @@
+// Dependency-free educational surface. Mount outside the canvas. Units/phase
+// convention belong to the scene; adapters must evaluate synchronously.
+// freeze(phase) -> {phase, stepId, partId?, readout}; no separate lesson clock.
+export function createEducationDock({ mount, title, summary, steps, parts,
+ min = 0, max = 1, increment = 0.01, freeze, selectPart, setPlaying, resetView }) {
+ if (!(max > min) || !(increment > 0) || !steps.length || !parts.length) throw new Error('invalid lesson contract');
+ const ids = new Set(parts.map(p => p.id));
+ if (ids.size !== parts.length || new Set(steps.map(s => s.id)).size !== steps.length) throw new Error('duplicate IDs');
+ for (const s of steps) if (!ids.has(s.partId) || !Number.isFinite(s.phase) || s.phase < min || s.phase > max) throw new Error('invalid causal step');
+ const make = (tag, text) => { const e = document.createElement(tag); if (text) e.textContent = text; return e; };
+ const root = make('section'); root.className = 'education-dock'; root.setAttribute('aria-label', title);
+ root.append(make('h1', title), make('p', summary));
+ const controls = make('div'); controls.className = 'education-controls';
+ const play = make('button', 'Play'); play.type = 'button'; play.setAttribute('aria-pressed', 'false');
+ const reset = make('button', 'Reset view'); reset.type = 'button';
+ const phaseLabel = make('label', 'Phase '), slider = make('input');
+ slider.type = 'range'; slider.min = min; slider.max = max; slider.step = increment; slider.value = min;
+ phaseLabel.append(slider);
+ const partLabel = make('label', 'Part '), picker = make('select');
+ for (const p of parts) { const o = make('option', p.label); o.value = p.id; picker.append(o); }
+ partLabel.append(picker); controls.append(play, reset, phaseLabel, partLabel);
+ const readout = make('output'), explanation = make('p');
+ readout.setAttribute('aria-live', 'off'); // only deliberate step changes use status
+ const disclosure = make('details'); disclosure.append(make('summary', 'How it works'));
+ const list = make('ol'), buttons = new Map();
+ const status = make('p'); status.className = 'education-sr-only'; status.setAttribute('role', 'status');
+ let playing = false;
+ const pause = () => { playing = false; setPlaying(false); play.textContent = 'Play'; play.setAttribute('aria-pressed', 'false'); };
+ function sync(state) {
+ if (!state || !Number.isFinite(state.phase) || state.phase < min || state.phase > max) throw new Error('invalid evaluated scene state');
+ const step = steps.find(s => s.id === state.stepId);
+ if (!step || (state.partId && !ids.has(state.partId))) throw new Error('unknown evaluated step/part');
+ slider.value = state.phase; readout.textContent = state.readout ?? String(state.phase);
+ explanation.textContent = `${step.title}: ${step.result}`;
+ picker.value = state.partId ?? step.partId;
+ for (const [id, button] of buttons) { if (id === state.stepId) button.setAttribute('aria-current', 'step'); else button.removeAttribute('aria-current'); }
+ }
+ for (const step of steps) {
+ const li = make('li'), button = make('button', step.title); button.type = 'button';
+ button.addEventListener('click', () => {
+ pause(); const state = freeze(step.phase); sync(state);
+ if (state.stepId !== step.id) throw new Error('lesson phase does not evaluate to requested step');
+ selectPart(step.partId, state); status.textContent = `${step.title}. ${step.result}`;
+ });
+ buttons.set(step.id, button); li.append(button, make('p', step.result)); list.append(li);
+ }
+ disclosure.append(list); root.append(controls, readout, explanation, disclosure, status); mount.append(root);
+ play.addEventListener('click', () => { playing = !playing; setPlaying(playing); play.textContent = playing ? 'Pause' : 'Play'; play.setAttribute('aria-pressed', String(playing)); });
+ reset.addEventListener('click', resetView);
+ slider.addEventListener('input', () => { pause(); sync(freeze(Number(slider.value))); });
+ picker.addEventListener('change', () => selectPart(picker.value));
+ // UI gestures must never become canvas orbit/pick gestures. Defaults remain
+ // intact so native controls, disclosure and keyboard navigation still work.
+ const stop = event => event.stopPropagation();
+ const events = ['pointerdown', 'pointerup', 'pointermove', 'pointercancel', 'click', 'wheel', 'keydown', 'keyup'];
+ for (const name of events) root.addEventListener(name, stop);
+ return { root, sync, dispose() { pause(); root.remove(); } };
+}
diff --git a/templates/education-v8.css b/templates/education-v8.css
new file mode 100644
index 0000000..6acfe06
--- /dev/null
+++ b/templates/education-v8.css
@@ -0,0 +1,98 @@
+/* Canonical V8 educational UI. Keep neutral UI independent of subject/render preset. */
+:root {
+ --paper: #f7f7f5;
+ --card: #fff;
+ --ink: #18181b;
+ --muted: #71717a;
+ --rule: #e4e4e7;
+ --secondary: #f4f4f5;
+ --accent: #2563eb;
+ --sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
+}
+* { box-sizing: border-box; }
+[hidden] { display: none !important; }
+html, body { margin: 0; height: 100%; background: var(--paper); color: var(--ink); }
+body { font: 14px/1.5 var(--sans); -webkit-font-smoothing: antialiased; }
+button, select { font: inherit; color: inherit; -webkit-tap-highlight-color: transparent; }
+button, summary, select { cursor: pointer; }
+button { touch-action: manipulation; }
+button, select, summary { transition: background-color 140ms, border-color 140ms, box-shadow 140ms; }
+:focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; }
+.viewer { display: grid; grid-template-columns: minmax(0,1fr) 360px; height: 100vh; height: 100dvh; padding-right: 24px; gap: 0; overflow: hidden; align-items: center; }
+.stage-wrap { position: relative; height: 100%; min-width: 0; min-height: 0; overflow: hidden; }
+#stage { display: block; width: 100%; height: 100%; outline: none; touch-action: none; cursor: grab; }
+#stage:active { cursor: grabbing; }
+#stage:focus-visible { outline: 2px solid var(--accent); outline-offset: -5px; }
+.panel { min-height: 0; max-height: calc(100dvh - 48px); padding: 22px; display: flex; flex-direction: column; gap: 18px; background: var(--card); border: 1px solid var(--rule); border-radius: 14px; box-shadow: 0 1px 3px #18181b08, 0 8px 32px #18181b03; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; }
+.panel > * { flex-shrink: 0; }
+.panel-top { position: sticky; top: -22px; z-index: 3; background: white; display: grid; gap: 16px; margin: -22px -22px 0; padding: 22px 22px 14px; border-bottom: 1px solid var(--rule); }
+.panel-head { display: grid; gap: 4px; }
+.title-row { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
+h1 { margin: 0; font-size: 21px; line-height: 1.35; letter-spacing: -.6px; font-weight: 650; }
+.badge { background: var(--secondary); border-radius: 6px; padding: 2px 7px; color: #52525b; font-size: 11px; font-weight: 500; }
+.lede, .section-note { margin: 0; color: var(--muted); font-size: 12px; line-height: 1.6; }
+.tabs { display: grid; grid-template-columns: 1fr 1fr; padding: 4px; gap: 3px; background: var(--secondary); border-radius: 9px; }
+.tabs button { border: 0; border-radius: 6px; height: 34px; font-size: 12px; font-weight: 550; background: none; color: var(--muted); }
+.tabs button[aria-selected='true'] { background: white; box-shadow: 0 1px 3px #00000012; color: var(--ink); }
+.tabs button:hover { color: var(--ink); }
+#learn-panel { display: grid; gap: 12px; }
+.lesson-steps { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; }
+.lesson-step { display: flex; align-items: center; gap: 8px; text-align: left; min-height: 38px; border: 1px solid var(--rule); background: white; border-radius: 7px; font-size: 12px; padding: 7px 10px; }
+.lesson-step span { width: 18px; height: 18px; display: grid; place-items: center; border-radius: 4px; background: var(--secondary); color: var(--muted); font-size: 10px; }
+.lesson-step[aria-pressed='true'] { border-color: #a1a1aa; background: #fafafa; font-weight: 600; }
+.lesson-step[aria-pressed='true'] span { background: var(--ink); color: white; }
+.readout { --stroke: #2563eb; }
+.status-row { display: flex; gap: 7px; align-items: center; }
+.status-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--stroke); }
+.phase-title { font-size: 13px; font-weight: 600; margin: 0; }
+.phase-meta { font-size: 11px; font-variant-numeric: tabular-nums; color: var(--muted); margin: 4px 0 0; }
+.cycle { height: 3px; background: var(--secondary); border-radius: 3px; overflow: hidden; margin: 11px 0; }
+.cycle i { display: block; height: 100%; width: 100%; transform: scaleX(0); transform-origin: left; background: var(--stroke); }
+.explain { margin: 0; font-size: 12px; line-height: 1.7; color: #52525b; min-height: 5.1em; }
+.controls { display: flex; align-items: center; gap: 6px; }
+.btn { height: 36px; border: 1px solid var(--rule); border-radius: 7px; background: white; display: inline-flex; align-items: center; justify-content: center; gap: 6px; padding: 0 10px; font-size: 12px; font-weight: 500; white-space: nowrap; box-shadow: 0 1px 2px #00000004; }
+.btn:hover, .lesson-step:hover { background: var(--secondary); }
+.btn.primary { background: var(--ink); border-color: var(--ink); color: white; min-width: 80px; margin-right: auto; }
+.btn.primary:hover { background: #3f3f46; }
+#playGlyph { font-size: 12px; width: 12px; text-align: center; }
+.btn.icon { width: 34px; padding: 0; }
+svg { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; flex-shrink: 0; }
+.btn.toggle[aria-pressed='true'] { background: var(--secondary); border-color: #a1a1aa; }
+#explore-panel { display: grid; gap: 8px; }
+.label { font-size: 12px; font-weight: 500; }
+#parts { width: 100%; height: 36px; border: 1px solid var(--rule); border-radius: 7px; padding: 0 10px; background: white; font-size: 12px; box-shadow: 0 1px 2px #00000004; }
+.disclosure { border-top: 1px solid var(--rule); padding-top: 12px; margin-top: 6px; }
+.disclosure summary { display: flex; align-items: center; justify-content: space-between; list-style: none; font-size: 12px; font-weight: 500; min-height: 24px; }
+.disclosure summary::-webkit-details-marker { display: none; }
+.disclosure[open] summary svg { transform: rotate(180deg); }
+.disclosure .section-note { margin-top: 10px; }
+.order { display: grid; grid-template-columns: repeat(8,minmax(0,1fr)); gap: 4px; margin-top: 12px; }
+.chip { height: 32px; border: 1px solid var(--rule); border-radius: 6px; padding: 0; background: white; font-size: 11px; }
+.chip.on { background: var(--ink); color: white; border-color: var(--ink); }
+.help { margin-top: 0; }
+.help summary { color: var(--muted); }
+.shortcuts { font-size: 11px; }
+.link { border: 0; background: none; padding: 0; text-align: left; font-size: 12px; color: var(--muted); align-self: flex-start; }
+.link:hover { color: var(--ink); text-decoration: underline; }
+.gesture { position: absolute; left: 24px; bottom: 20px; margin: 0; font-size: 11px; color: var(--muted); pointer-events: none; }
+.loading, .fallback { position: absolute; inset: 0; display: grid; place-items: center; background: var(--paper); color: var(--muted); padding: 24px; }
+.loading { transition: opacity 200ms; }
+.loading.done { opacity: 0; pointer-events: none; }
+.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }
+html.clean .viewer { grid-template-columns: minmax(0,1fr); padding: 0; }
+html.clean .panel, html.clean .gesture { display: none; }
+@media (max-width: 880px) {
+ .viewer { grid-template-columns: minmax(0,1fr); grid-template-rows: minmax(0,1fr) auto; padding: 0; gap: 0; }
+ .panel { max-height: 48dvh; border-radius: 14px 14px 0 0; padding: 16px 18px calc(16px + env(safe-area-inset-bottom)); gap: 14px; width: 100%; }
+ .panel-top { top: -16px; margin: -16px -18px 0; padding: 16px 18px 12px; gap: 12px; }
+ .lede { display: none; }
+ h1 { font-size: 19px; }
+ .gesture { left: 16px; bottom: 14px; font-size: 10px; }
+ .btn { height: 40px; }
+ .btn.icon { width: 40px; }
+ .lesson-step, #parts { min-height: 40px; }
+ .tabs button { height: 36px; }
+ .explain { min-height: 0; }
+ html.clean .viewer { grid-template-rows: minmax(0,1fr); }
+}
+@media (prefers-reduced-motion: reduce) { *, *::before, *::after { transition: none !important; scroll-behavior: auto !important; } }
diff --git a/templates/educational-asset-gate.mjs b/templates/educational-asset-gate.mjs
new file mode 100644
index 0000000..432b084
--- /dev/null
+++ b/templates/educational-asset-gate.mjs
@@ -0,0 +1,131 @@
+/**
+ * Recorded-evidence policy gate only: no network, legal, scientific, copyright,
+ * trademark, privacy, publicity or other third-party-rights verification.
+ * Schema (all fields required unless noted):
+ * {sourceURL,downloadURL,title,creator,retrievedAt:'YYYY-MM-DD',
+ * license:{spdx,url,evidenceURL,reviewed:true,costUSD:0,commercial:true,
+ * modify:true,redistribute:true,embed:true,restrictions:[]},
+ * attribution:{text,licenseURL,changes:[string],retainedNotices:true},
+ * files:[{name,sha256:64hex,licenseReviewed:true}],
+ * dependencies:[], // recursive records with the same rights fields; no role/readiness needed
+ * accuracy:{referenceURL,identityMatches:true,dimensionsChecked:true,
+ * unitsAndScaleChecked:true,criticalGeometryChecked:true},
+ * structure:{partsMapped:true,pivotsValidated:true,interfacesValidated:true},
+ * import:{tested:true,finiteGeometry:true,complete:true,styleMatched:true},
+ * role:'teaching'|'exterior'|'context',
+ * distribution:{dependenciesEmbedded:boolean}}
+ * dependencies lists ALL transitive assets (nested records allowed); files lists
+ * ALL delivered files. Completeness itself is recorded, not independently proved.
+ * CC0 attribution.text may be empty; CC-BY text must be nonblank. changes:[] is
+ * an explicit declaration of no modifications. Exact canonical license URLs only.
+ * Exterior/context require identity, dimensions, units/scale and import checks,
+ * not internal mechanics. Teaching additionally requires critical geometry and
+ * every structure check. Online does not establish offline readiness.
+ * Result: {status,rightsAllowed,ready,reasons:[{code,path,message}]}.
+ * Missing/invalid evidence and non-allowlisted licenses hold for review; explicit
+ * policy conflicts reject. Readiness failures hold without revoking rightsAllowed.
+ */
+const OFFICIAL = Object.freeze({
+ 'CC0-1.0': 'https://creativecommons.org/publicdomain/zero/1.0/',
+ 'CC-BY-4.0': 'https://creativecommons.org/licenses/by/4.0/',
+});
+const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
+const text = value => typeof value === 'string' && value.trim().length > 0;
+const url = value => {
+ if (!text(value) || value !== value.trim()) return false;
+ try {
+ const parsed = new URL(value);
+ return ['http:', 'https:'].includes(parsed.protocol) && !!parsed.hostname &&
+ !parsed.username && !parsed.password;
+ } catch { return false; }
+};
+const date = value => {
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
+ const parsed = new Date(`${value}T00:00:00.000Z`);
+ return Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
+};
+
+export function evaluateEducationalAsset(record, { delivery = 'offline' } = {}) {
+ const reasons = [];
+ let rightsAllowed = true;
+ let ready = true;
+ let rejected = false;
+ const issue = (code, path, message, { rights = true, reject = false } = {}) => {
+ reasons.push({ code, path, message });
+ if (rights) rightsAllowed = false;
+ else ready = false;
+ rejected ||= reject;
+ };
+ const requiredURL = (value, path, rights = true) => {
+ if (!url(value)) issue('invalid-url', path, 'Require an HTTP(S) URL without credentials.', { rights });
+ };
+ const flag = (value, path, rights = true) => {
+ if (value !== true) issue(value === false ? 'failed-check' : 'missing-check', path,
+ 'Recorded evidence must be exactly true.', { rights, reject: rights && value === false });
+ };
+ if (!['offline', 'online'].includes(delivery)) {
+ issue('invalid-delivery', 'delivery', 'Choose offline or online.');
+ }
+ const active = new Set();
+ function rights(asset, path) {
+ if (!object(asset)) { issue('invalid-record', path, 'Require an asset record.'); return; }
+ if (active.has(asset)) { issue('dependency-cycle', path, 'Dependency evidence must be acyclic.'); return; }
+ active.add(asset);
+ for (const key of ['sourceURL', 'downloadURL']) requiredURL(asset[key], `${path}.${key}`);
+ for (const key of ['title', 'creator']) {
+ if (!text(asset[key])) issue('missing-metadata', `${path}.${key}`, 'Require nonblank metadata.');
+ }
+ if (!date(asset.retrievedAt)) issue('invalid-date', `${path}.retrievedAt`, 'Require a real YYYY-MM-DD date.');
+ const license = object(asset.license) ? asset.license : {};
+ const canonical = Object.hasOwn(OFFICIAL, license.spdx) ? OFFICIAL[license.spdx] : undefined;
+ if (!canonical) {
+ const prohibited = typeof license.spdx === 'string' &&
+ (/(?:^|-)NC(?:-|$)|(?:^|-)ND(?:-|$)/i.test(license.spdx) || /editorial/i.test(license.spdx));
+ issue('license-not-allowlisted', `${path}.license.spdx`,
+ 'Only CC0-1.0 and CC-BY-4.0 auto-pass; SA and custom/unknown licenses require manual review, not a claim of illegality.',
+ { reject: prohibited });
+ }
+ requiredURL(license.url, `${path}.license.url`);
+ requiredURL(license.evidenceURL, `${path}.license.evidenceURL`);
+ if (canonical && license.url !== canonical) issue('official-license-mismatch', `${path}.license.url`, 'Require the exact official canonical URL.');
+ flag(license.reviewed, `${path}.license.reviewed`);
+ if (license.costUSD !== 0) issue('nonzero-or-unknown-cost', `${path}.license.costUSD`, 'Require a recorded numeric zero cost.',
+ { reject: typeof license.costUSD === 'number' && Number.isFinite(license.costUSD) && license.costUSD > 0 });
+ for (const key of ['commercial', 'modify', 'redistribute']) flag(license[key], `${path}.license.${key}`);
+ if (delivery === 'offline') flag(license.embed, `${path}.license.embed`);
+ else if (typeof license.embed !== 'boolean') issue('missing-check', `${path}.license.embed`, 'Record embedding permission explicitly.');
+ if (!Array.isArray(license.restrictions) || license.restrictions.length) issue('additional-terms', `${path}.license.restrictions`, 'Require an explicitly empty restrictions array.', { reject: Array.isArray(license.restrictions) && license.restrictions.length > 0 });
+ const attribution = object(asset.attribution) ? asset.attribution : {};
+ if (typeof attribution.text !== 'string' || (license.spdx === 'CC-BY-4.0' && !text(attribution.text))) issue('missing-attribution', `${path}.attribution.text`, 'CC-BY requires nonblank credit; CC0 still records a text field.');
+ requiredURL(attribution.licenseURL, `${path}.attribution.licenseURL`);
+ if (canonical && attribution.licenseURL !== canonical) issue('attribution-license-mismatch', `${path}.attribution.licenseURL`, 'Require the exact official canonical URL.');
+ if (!Array.isArray(attribution.changes) || !Array.from(attribution.changes).every(text)) issue('missing-changes', `${path}.attribution.changes`, 'Declare changes as nonblank strings, or [] for none.');
+ flag(attribution.retainedNotices, `${path}.attribution.retainedNotices`);
+ if (!Array.isArray(asset.files) || !asset.files.length) issue('missing-files', `${path}.files`, 'List every delivered file.');
+ else Array.from(asset.files).forEach((file, i) => {
+ const base = `${path}.files[${i}]`;
+ if (!object(file)) { issue('invalid-file', base, 'Require a file record.'); return; }
+ if (!text(file.name)) issue('missing-file-name', `${base}.name`, 'Require a file name.');
+ if (typeof file.sha256 !== 'string' || !/^[a-fA-F0-9]{64}$/.test(file.sha256)) issue('invalid-sha256', `${base}.sha256`, 'Require exactly 64 hexadecimal characters.');
+ flag(file.licenseReviewed, `${base}.licenseReviewed`);
+ });
+ if (!Array.isArray(asset.dependencies)) issue('missing-dependencies', `${path}.dependencies`, 'Declare all dependencies, or [] for none.');
+ else Array.from(asset.dependencies).forEach((dependency, i) => rights(dependency, `${path}.dependencies[${i}]`));
+ const embedded = asset.distribution?.dependenciesEmbedded;
+ if (delivery === 'offline') flag(embedded, `${path}.distribution.dependenciesEmbedded`);
+ else if (typeof embedded !== 'boolean') issue('missing-check', `${path}.distribution.dependenciesEmbedded`, 'Record dependency embedding explicitly.');
+ active.delete(asset);
+ }
+ rights(record, 'record');
+ if (object(record)) {
+ if (!['teaching', 'exterior', 'context'].includes(record.role)) issue('invalid-role', 'record.role', 'Choose teaching, exterior or context.', { rights: false });
+ requiredURL(record.accuracy?.referenceURL, 'record.accuracy.referenceURL', false);
+ for (const key of ['identityMatches', 'dimensionsChecked', 'unitsAndScaleChecked']) flag(record.accuracy?.[key], `record.accuracy.${key}`, false);
+ if (record.role === 'teaching') {
+ flag(record.accuracy?.criticalGeometryChecked, 'record.accuracy.criticalGeometryChecked', false);
+ for (const key of ['partsMapped', 'pivotsValidated', 'interfacesValidated']) flag(record.structure?.[key], `record.structure.${key}`, false);
+ }
+ for (const key of ['tested', 'finiteGeometry', 'complete', 'styleMatched']) flag(record.import?.[key], `record.import.${key}`, false);
+ } else ready = false;
+ return { status: rejected ? 'rejected' : rightsAllowed && ready ? 'accepted' : 'needs-review', rightsAllowed, ready, reasons };
+}
diff --git a/templates/educational-asset-record.json b/templates/educational-asset-record.json
new file mode 100644
index 0000000..2def3cf
--- /dev/null
+++ b/templates/educational-asset-record.json
@@ -0,0 +1,50 @@
+{
+ "sourceURL": "",
+ "downloadURL": "",
+ "title": "",
+ "creator": "",
+ "retrievedAt": "",
+ "license": {
+ "spdx": "",
+ "url": "",
+ "evidenceURL": "",
+ "reviewed": null,
+ "costUSD": null,
+ "commercial": null,
+ "modify": null,
+ "redistribute": null,
+ "embed": null,
+ "restrictions": []
+ },
+ "attribution": {
+ "text": "",
+ "licenseURL": "",
+ "changes": [],
+ "retainedNotices": null
+ },
+ "files": [],
+ "dependencies": [],
+ "accuracy": {
+ "referenceURL": "",
+ "identityMatches": null,
+ "dimensionsChecked": null,
+ "unitsAndScaleChecked": null,
+ "criticalGeometryChecked": null
+ },
+ "structure": {
+ "partsMapped": null,
+ "pivotsValidated": null,
+ "interfacesValidated": null
+ },
+ "import": {
+ "tested": null,
+ "finiteGeometry": null,
+ "complete": null,
+ "styleMatched": null
+ },
+ "role": "teaching",
+ "distribution": {
+ "dependenciesEmbedded": null
+ },
+ "evidenceNotes": "Fill only from reviewed source terms, actual file hashes and executed import/geometry tests. This blank template deliberately does not pass. Group files belonging to one copyright work; list differently licensed works as dependencies."
+}
diff --git a/templates/flow-primitives.js b/templates/flow-primitives.js
new file mode 100644
index 0000000..1446ca9
--- /dev/null
+++ b/templates/flow-primitives.js
@@ -0,0 +1,104 @@
+import * as THREE from 'three';
+
+/**
+ * Copy-in motion-graphics primitives for educational / mechanical scenes.
+ *
+ * Failure modes this file exists to prevent (see SKILL.md v3.12.0):
+ * - a cone built with swapped radii, so every arrow flows backwards
+ * - arrows drawn along the centreline of an opaque pipe, then "fixed" with
+ * depthTest:false (x-ray)
+ * - effects that fade to a two-pixel speck instead of disappearing
+ * - sizing against a cached deck height instead of the moving free volume
+ * - a spline through a cutaway that spears the valve disc; derive the arrow
+ * from the live free band (crown to valve underside) instead
+ * - clamping only the arrow centre, so the head pierces the crown/valve
+ * - authored lengths shorter than the desired length (scale > 1), which
+ * defeats the legibility gate
+ *
+ * SPACE: every Y passed here must be in the same space as the constants used
+ * for the crown/valve/ceiling. If the effect group is parented to a lifted
+ * scene root, either subtract that lift or author the constants locally.
+ *
+ * CONVENTION: an arrow points along local +Z. The cone tip is a single point at
+ * +Z, the wide base sits behind it, and the tail is at -Z. `setArrowTransform`
+ * maps +Z onto the requested flow tangent.
+ */
+
+export function makeFlowArrow({
+ length = 0.4,
+ shaftRadius = 0.023,
+ headRadius = 0.079,
+ headRatio = 0.34,
+ material,
+} = {}) {
+ if (!material) throw new Error('makeFlowArrow: material is required');
+ if (material.transparent || material.depthTest === false) {
+ throw new Error('makeFlowArrow: effects must be opaque and depth-tested');
+ }
+ const group = new THREE.Group();
+ const headLen = length * headRatio;
+ const shaftLen = length - headLen;
+ const shaft = new THREE.Mesh(new THREE.CylinderGeometry(shaftRadius, shaftRadius, shaftLen, 12), material);
+ // radiusTop is the +Y end; after rotation.x = +90deg, +Y becomes +Z.
+ const head = new THREE.Mesh(new THREE.CylinderGeometry(0, headRadius, headLen, 18), material);
+ shaft.rotation.x = Math.PI / 2;
+ head.rotation.x = Math.PI / 2;
+ shaft.position.z = -length * 0.5 + shaftLen * 0.5;
+ head.position.z = length * 0.5 - headLen * 0.5;
+ shaft.castShadow = head.castShadow = false;
+ shaft.receiveShadow = head.receiveShadow = false;
+ group.add(shaft, head);
+ group.userData = {
+ length,
+ shaftRadius,
+ headRadius,
+ tipLocal: new THREE.Vector3(0, 0, length * 0.5),
+ tailLocal: new THREE.Vector3(0, 0, -length * 0.5),
+ shaft,
+ head,
+ };
+ return group;
+}
+
+export function setArrowTransform(group, point, tangent, scale = 1) {
+ group.position.copy(point);
+ group.quaternion.setFromUnitVectors(new THREE.Vector3(0, 0, 1), tangent.clone().normalize());
+ group.scale.setScalar(scale);
+}
+
+/**
+ * Fit the COMPLETE arrow (tip, tail, head width) into a vertical band and the
+ * bore radius. Returns false and hides the arrow when it cannot be legible,
+ * instead of leaving a spec. `minScale` should be ~0.32 for a chamber-sized
+ * arrow read at a normal orbit distance; 0.22 is only for very large arrows.
+ */
+export function placeArrowInBand(arrow, point, direction, desiredScale, floor, roof, {
+ minScale = 0.22,
+ boreRadius = 0.40,
+} = {}) {
+ const dir = direction.clone().normalize();
+ const half = (arrow.userData.length ?? 0.4) * 0.5;
+ const head = arrow.userData.headRadius ?? 0.079;
+ const extentY = half * Math.abs(dir.y) + head * Math.sqrt(Math.max(0, 1 - dir.y * dir.y));
+ const horizontal = half * Math.hypot(dir.x, dir.z) + head;
+ const radial = Math.hypot(point.x, point.z);
+ const band = roof - floor;
+ const scale = Math.min(
+ desiredScale,
+ band / (2 * Math.max(extentY, 0.001)),
+ (boreRadius - radial) / Math.max(horizontal, 0.001),
+ );
+ if (!Number.isFinite(scale) || scale < minScale) {
+ arrow.visible = false;
+ return false;
+ }
+ arrow.visible = true;
+ point.y = THREE.MathUtils.clamp(point.y, floor + extentY * scale, roof - extentY * scale);
+ setArrowTransform(arrow, point, dir, scale);
+ return true;
+}
+
+/** Minimum legible scale check shared by build-time and QA code. */
+export function isLegibleArrow(arrow, minScale = 0.32) {
+ return arrow.visible && arrow.scale.z >= minScale;
+}
diff --git a/templates/inspection.js b/templates/inspection.js
new file mode 100644
index 0000000..9902be3
--- /dev/null
+++ b/templates/inspection.js
@@ -0,0 +1,179 @@
+// Copy-in rigid-mesh inspection. Dependency injection avoids a second THREE copy.
+// Host owns raycasting, useful camera focus, V8 DOM, time, and authored cutaways.
+// No bloom, depth override, whole-mechanism transparency, or geometry certification.
+export function createInspection(THREE, {
+ parts, contextMeshes = [], resolveVisibility = () => ({}), onChange = () => {},
+ style = {},
+} = {}) {
+ const config = { selectedColor: 0x80dbff, selectedMix: 0.32,
+ emissive: 0x169bdf, emissiveIntensity: 0.65, dimFactor: 0.32,
+ edgeColor: 0x62d5ff, edgeOpacity: 0.85, edgeAngle: 38, ghostOpacity: 0.105,
+ edgeEligible: () => true, ...style };
+ for (const key of ['selectedMix', 'dimFactor', 'edgeOpacity', 'ghostOpacity'])
+ if (!Number.isFinite(config[key]) || config[key] < 0 || config[key] > 1) throw new Error(`invalid inspection style: ${key}`);
+ if (!Number.isFinite(config.emissiveIntensity) || config.emissiveIntensity < 0
+ || !Number.isFinite(config.edgeAngle) || config.edgeAngle < 0 || config.edgeAngle > 180)
+ throw new Error('invalid inspection emission/edge angle');
+ if (!(parts instanceof Map) && (!parts || typeof parts !== 'object')) throw new Error('parts Map/object required');
+ const registry = parts instanceof Map ? parts : new Map(Object.entries(parts));
+ if (!registry.size) throw new Error('nonempty inspection parts required');
+ const saved = new Map(), owners = new Map(), variants = new Map();
+ const overlays = [];
+ let selection = null, disposed = false, visibility = {};
+ const slots = material => Array.isArray(material) ? material : [material];
+ const alive = () => { if (disposed) throw new Error('inspection controller disposed'); };
+ function register(mesh, owner) {
+ if (!mesh?.isMesh || !mesh.geometry || !mesh.material || !mesh.geometry.attributes?.position?.count)
+ throw new Error('actual nonempty mesh/material required');
+ if (mesh.isSkinnedMesh || mesh.isInstancedMesh || Object.keys(mesh.geometry.morphAttributes || {}).length)
+ throw new Error('inspection helper supports rigid meshes only; author a deformation-aware path');
+ if (saved.has(mesh)) throw new Error('mesh registered twice or owned by multiple parts');
+ if (!slots(mesh.material).length || slots(mesh.material).some(m => !m?.isMaterial || typeof m.clone !== 'function' || !m.color?.lerp))
+ throw new Error('colour-bearing material slots required; custom shaders need an authored adapter');
+ owners.set(mesh, owner);
+ saved.set(mesh, { material: mesh.material, visible: mesh.visible,
+ castShadow: mesh.castShadow, receiveShadow: mesh.receiveShadow });
+ }
+ for (const [id, rec] of registry) {
+ if (!id || !rec || !Array.isArray(rec.meshes) || !rec.meshes.length) throw new Error(`nonempty mesh list required: ${id}`);
+ for (const mesh of rec.meshes) register(mesh, id);
+ }
+ for (const mesh of contextMeshes) register(mesh, null);
+ function restore() {
+ for (const [mesh, original] of saved) {
+ mesh.material = original.material; mesh.visible = original.visible;
+ mesh.castShadow = original.castShadow; mesh.receiveShadow = original.receiveShadow;
+ }
+ }
+ function removeEdges() {
+ for (const edge of overlays) { edge.removeFromParent(); edge.geometry.dispose(); }
+ overlays.length = 0;
+ }
+ function variant(source, mode) {
+ let modes = variants.get(source);
+ if (!modes) variants.set(source, modes = new Map());
+ if (modes.has(mode)) return modes.get(mode);
+ const material = source.clone();
+ material.userData = { ...source.userData };
+ if (source.userData?.outlineParameters)
+ material.userData.outlineParameters = { ...source.userData.outlineParameters };
+ if (mode.startsWith('selected')) {
+ material.color?.lerp(new THREE.Color(config.selectedColor), config.selectedMix);
+ // Adding emissive to MeshBasicMaterial breaks Three's uniform refresh.
+ if (material.emissive?.set) {
+ material.emissive.set(config.emissive);
+ material.emissiveIntensity = config.emissiveIntensity;
+ }
+ } else if (mode === 'ghost') {
+ material.transparent = true; material.opacity = config.ghostOpacity;
+ material.depthWrite = false; material.depthTest = true;
+ material.side = THREE.FrontSide; material.blending = THREE.NormalBlending;
+ if (material.emissive?.set) material.emissiveIntensity = 0;
+ if (material.userData.outlineParameters) material.userData.outlineParameters.visible = false;
+ } else {
+ material.color?.multiplyScalar(config.dimFactor);
+ if (material.emissive?.set) material.emissiveIntensity = 0;
+ }
+ // Preserve maps, ramps, opacity, side, depth, blending and original contours.
+ // Feature edges below replace selected contours on eligible rigid meshes.
+ if (mode === 'selected-edge' && material.userData.outlineParameters)
+ material.userData.outlineParameters.visible = false;
+ material.needsUpdate = true;
+ modes.set(mode, material);
+ return material;
+ }
+ const edgeMaterial = new THREE.LineBasicMaterial({ color: config.edgeColor,
+ transparent: true, opacity: config.edgeOpacity, depthTest: true,
+ depthWrite: false, toneMapped: false });
+ function eligible(mesh) {
+ const materials = slots(saved.get(mesh).material);
+ return materials.every(m => !m.transparent && !m.map)
+ && mesh.userData.inspectionEdge !== false
+ && !mesh.userData.symbolicSignal && config.edgeEligible(mesh);
+ }
+ function apply() {
+ alive();
+ try {
+ removeEdges(); restore();
+ visibility = resolveVisibility(selection ? { ...selection } : null) || {};
+ const hidden = new Set(visibility.hiddenMeshes || []);
+ for (const id of visibility.hiddenPartIds || []) {
+ if (!registry.has(id)) throw new Error(`unknown authored cutaway part: ${id}`);
+ if (id === selection?.partId) throw new Error('cutaway cannot hide the selected assembly');
+ for (const mesh of registry.get(id).meshes) hidden.add(mesh);
+ }
+ for (const mesh of hidden) {
+ const part = registry.get(owners.get(mesh));
+ if (!saved.has(mesh) || !part) throw new Error('context/unregistered meshes cannot be hidden');
+ const internalCutaway = part.inspectionOccluder === true && selection
+ && typeof visibility.description === 'string' && visibility.description.trim();
+ if (part.shell !== true && !internalCutaway)
+ throw new Error('hiding requires a manifest shell or explained inspectionOccluder selection plan');
+ if (owners.get(mesh) === selection?.partId && (!selection.mesh || mesh === selection.mesh))
+ throw new Error('cutaway cannot hide the selected assembly or piece');
+ }
+ const ghost = new Set(visibility.ghostMeshes || []);
+ for (const id of visibility.ghostPartIds || []) {
+ if (registry.get(id)?.shell !== true) throw new Error(`only manifest shell parts may ghost: ${id}`);
+ for (const mesh of registry.get(id).meshes) ghost.add(mesh);
+ }
+ for (const mesh of ghost) {
+ if (!saved.has(mesh) || registry.get(owners.get(mesh))?.shell !== true)
+ throw new Error('ghost mesh must belong to a manifest shell part');
+ if (hidden.has(mesh)) throw new Error('cutaway cannot both hide and ghost a mesh');
+ if (owners.get(mesh) === selection?.partId) throw new Error('selected shell must remain solid');
+ }
+ for (const [mesh, original] of saved) {
+ if (owners.get(mesh) === null) continue; // floor/stand/UI context never dims or reveals
+ const chosen = selection && owners.get(mesh) === selection.partId
+ && (!selection.mesh || selection.mesh === mesh);
+ if (hidden.has(mesh)) { mesh.visible = false; mesh.castShadow = false; continue; }
+ if (!selection && !ghost.has(mesh)) continue;
+ const mode = ghost.has(mesh) ? 'ghost' : chosen ? (eligible(mesh) ? 'selected-edge' : 'selected') : 'dim';
+ const materials = slots(original.material).map(m => variant(m, mode));
+ // Each mesh gets its own array, exact source array identity restores on clear.
+ mesh.material = Array.isArray(original.material) ? materials : materials[0];
+ if (ghost.has(mesh)) mesh.castShadow = false;
+ if (chosen && original.visible && eligible(mesh)) {
+ // Cached variants can be shared; do not mutate their outline parameters
+ // per mesh. Use one eligible-selected variant branch for contour suppression.
+ const edge = new THREE.LineSegments(new THREE.EdgesGeometry(mesh.geometry, config.edgeAngle), edgeMaterial);
+ edge.userData.inspectionOverlay = true; edge.raycast = () => {};
+ mesh.add(edge); overlays.push(edge);
+ }
+ }
+ onChange({ selection: selection ? { ...selection } : null,
+ visibility: { ...visibility }, overlays: overlays.length });
+ } catch (error) {
+ removeEdges(); restore(); selection = null; visibility = {};
+ throw error;
+ }
+ }
+ function select({ partId, mesh = null } = {}) {
+ alive();
+ if (!registry.has(partId)) throw new Error(`unknown inspection part: ${partId}`);
+ if (mesh && owners.get(mesh) !== partId) throw new Error('selected mesh is not a member of that part');
+ selection = { partId, mesh }; apply();
+ }
+ function clear() { alive(); selection = null; apply(); }
+ function piecePickerEntries(partId, { visibleOnly = false } = {}) {
+ alive(); if (!registry.has(partId)) throw new Error(`unknown inspection part: ${partId}`);
+ return registry.get(partId).meshes.filter(mesh => {
+ if (mesh.userData.symbolicSignal) return false;
+ if (!visibleOnly) return true;
+ for (let p = mesh; p; p = p.parent) if (!p.visible) return false;
+ return true;
+ }).map((mesh, i) => ({ value: mesh.uuid, mesh,
+ label: mesh.userData.inspectionLabel || mesh.name || `${partId} piece ${i + 1}` }));
+ }
+ function dispose() {
+ if (disposed) return;
+ removeEdges(); restore();
+ for (const modes of variants.values()) for (const material of modes.values()) material.dispose();
+ variants.clear(); edgeMaterial.dispose(); selection = null; disposed = true;
+ }
+ return { select, clear, refresh: apply, dispose, piecePickerEntries,
+ get selection() { return selection ? { ...selection } : null; },
+ get stats() { return { meshes: saved.size, overlays: overlays.length,
+ variants: [...variants.values()].reduce((n, modes) => n + modes.size, 0), disposed }; } };
+}
diff --git a/templates/interface-checks.js b/templates/interface-checks.js
new file mode 100644
index 0000000..bdd195b
--- /dev/null
+++ b/templates/interface-checks.js
@@ -0,0 +1,133 @@
+// Dependency-injected, rigid triangle checks. No collision/triangle-intersection certificate.
+export function createInterfaceChecks(THREE) {
+ const axes = ['x', 'y', 'z'];
+ const fail = message => { throw new Error(`interface-checks: ${message}`); };
+ const finite = values => values.every(Number.isFinite);
+ const meshOK = mesh => {
+ if (!mesh?.isMesh || mesh.isSkinnedMesh || mesh.isInstancedMesh || mesh.isBatchedMesh)
+ fail('expected an ordinary rigid Mesh');
+ if (mesh.geometry?.morphAttributes && Object.values(mesh.geometry.morphAttributes).some(a => a.length))
+ fail('deformed/morph geometry is unsupported');
+ if (mesh.material && (Array.isArray(mesh.material) ? mesh.material : [mesh.material])
+ .some(m => m.displacementMap || m.isShaderMaterial || m.isRawShaderMaterial || m.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile))
+ fail('shader/displacement deformation is unsupported');
+ };
+ function matrix(mesh, frame) {
+ mesh.updateWorldMatrix(true, false);
+ const m = mesh.matrixWorld.clone();
+ if (frame) {
+ if (!frame.isObject3D) fail('frame must be an Object3D');
+ frame.updateWorldMatrix(true, false);
+ if (!finite(frame.matrixWorld.elements) || frame.matrixWorld.determinant() === 0) fail('invalid frame');
+ m.premultiply(frame.matrixWorld.clone().invert());
+ }
+ if (!finite(m.elements) || m.determinant() === 0) fail('invalid mesh transform');
+ return m;
+ }
+ function vertices(mesh, frame) {
+ meshOK(mesh);
+ const g = mesh.geometry, p = g?.getAttribute?.('position'), index = g?.getIndex?.();
+ if (!p || p.itemSize !== 3 || !Number.isInteger(p.count) || !p.count) fail('missing/empty position');
+ if (index && (index.itemSize !== 1 || !Number.isInteger(index.count))) fail('malformed index');
+ const count = index ? index.count : p.count, range = g.drawRange;
+ if (!range || !Number.isInteger(range.start) || range.start < 0 || range.start > count ||
+ !(range.count === Infinity || Number.isInteger(range.count) && range.count >= 0)) fail('invalid drawRange');
+ const end = Math.min(count, range.start + range.count);
+ if (end <= range.start || range.start % 3 || (end - range.start) % 3) fail('empty/malformed triangle range');
+ const transform = matrix(mesh, frame), result = [];
+ for (let i = range.start; i < end; i++) {
+ const j = index ? index.getX(i) : i;
+ if (!Number.isInteger(j) || j < 0 || j >= p.count) fail('invalid vertex index');
+ const v = new THREE.Vector3().fromBufferAttribute(p, j);
+ if (!finite(v.toArray())) fail('nonfinite vertex');
+ v.applyMatrix4(transform);
+ if (!finite(v.toArray())) fail('nonfinite transformed vertex');
+ result.push(v);
+ }
+ let physical = false;
+ for (let i = 0; i < result.length; i += 3) {
+ const cross = new THREE.Vector3().subVectors(result[i + 1], result[i])
+ .cross(new THREE.Vector3().subVectors(result[i + 2], result[i]));
+ if (!finite(cross.toArray())) fail('nonfinite triangle area');
+ if (cross.lengthSq() > 0) physical = true;
+ }
+ if (!physical) fail('no nondegenerate active triangle');
+ return result;
+ }
+ function bounds(mesh, { frame } = {}) {
+ return new THREE.Box3().setFromPoints(vertices(mesh, frame));
+ }
+ // Only undeformed, full BoxGeometry envelopes aligned with the supplied axes.
+ function support(mesh, frame) {
+ const points = vertices(mesh, frame), b = new THREE.Box3().setFromPoints(points);
+ if (mesh.geometry.type !== 'BoxGeometry') fail('seated supports only full axis-aligned BoxGeometry');
+ const size = b.getSize(new THREE.Vector3()), eps = 1e-7 * Math.max(1, ...size.toArray());
+ if (size.toArray().some(s => s <= eps)) fail('degenerate support');
+ if (points.some(p => axes.some(a => Math.min(Math.abs(p[a] - b.min[a]), Math.abs(p[a] - b.max[a])) > eps)))
+ fail('support is not axis-aligned');
+ const area = Array(6).fill(0);
+ for (let i = 0; i < points.length; i += 3) {
+ const tri = points.slice(i, i + 3);
+ const face = axes.flatMap((a, k) => ['min', 'max'].map((side, s) =>
+ tri.every(p => Math.abs(p[a] - b[side][a]) <= eps) ? k * 2 + s : -1)).filter(n => n >= 0);
+ const n = new THREE.Vector3().subVectors(tri[1], tri[0]).cross(new THREE.Vector3().subVectors(tri[2], tri[0])).length() / 2;
+ if (face.length !== 1 || n <= eps * eps) fail('unsupported support faces');
+ area[face[0]] += n;
+ }
+ if (area.some((n, i) => Math.abs(n - axes.filter((_, k) => k !== Math.floor(i / 2)).reduce((v, a) => v * size[a], 1)) > eps * Math.max(...size.toArray())))
+ fail('support must contain its complete box surface');
+ return b;
+ }
+ function seated(upper, lower, { frame, axis = 'y', tolerance = 1e-5, minOverlap = 0 } = {}) {
+ if (!axes.includes(axis) || !finite([tolerance, minOverlap]) || tolerance < 0 || minOverlap < 0) fail('invalid seating options');
+ const u = support(upper, frame), l = support(lower, frame), gap = u.min[axis] - l.max[axis];
+ const overlaps = Object.fromEntries(axes.filter(a => a !== axis).map(a => [a, Math.min(u.max[a], l.max[a]) - Math.max(u.min[a], l.min[a])]));
+ return { pass: Math.abs(gap) <= tolerance && Object.values(overlaps).every(v => v > 0 && v >= minOverlap), gap, overlaps, method: 'axis-aligned-box-envelope-mating-faces' };
+ }
+ function outsideBox(mesh, { frame, box, clearance = 0 } = {}) {
+ if (!box?.isBox3 || box.isEmpty() || !finite([...box.min.toArray(), ...box.max.toArray(), clearance]) || clearance < 0) fail('invalid box/clearance');
+ const envelope = bounds(mesh, { frame });
+ const gaps = Object.fromEntries(axes.map(a => [a, Math.max(box.min[a] - envelope.max[a], envelope.min[a] - box.max[a])]));
+ return { status: Object.values(gaps).some(g => g > clearance) ? 'clear' : 'candidate', gaps, envelope, method: 'conservative-aabb-separation' };
+ }
+ function scopedMeshes({ required, registered } = {}) {
+ for (const list of [required, registered]) {
+ if (!Array.isArray(list) || !list.length || new Set(list).size !== list.length) fail('scope must be nonempty and unique');
+ list.forEach(mesh => vertices(mesh));
+ }
+ const missing = required.filter(m => !registered.includes(m)), extra = registered.filter(m => !required.includes(m));
+ return { pass: !missing.length && !extra.length, missing, extra };
+ }
+ function worldAnchor({ mesh, local, callback, root } = {}) {
+ meshOK(mesh);
+ // Run bounds at build validation; this live path only checks geometry presence.
+ const position = mesh.geometry?.getAttribute?.('position');
+ if (!position || position.itemSize !== 3 || !Number.isInteger(position.count) || position.count < 3) fail('anchor missing geometry');
+ if (!root?.isObject3D) fail('anchor root required');
+ let node = mesh;
+ while (node && node !== root) node = node.parent;
+ if (node !== root) fail('anchor detached from root');
+ if (local !== undefined && callback !== undefined) fail('choose local or callback');
+ const value = callback ? callback(mesh.geometry, mesh) : typeof local === 'function' ? local(mesh.geometry, mesh) : local;
+ if (!Array.isArray(value) || value.length !== 3 || !finite(value)) fail('invalid local anchor');
+ return new THREE.Vector3(...value).applyMatrix4(matrix(mesh));
+ }
+ function projectPoints(points, camera, { margin = 0 } = {}) {
+ if (!Array.isArray(points) || !points.length || !camera?.isCamera || !Number.isFinite(margin) || margin < 0 || margin >= 1) fail('invalid projection input');
+ camera.updateWorldMatrix(true, false);
+ for (const m of [camera.matrixWorld, camera.projectionMatrix])
+ if (!finite(m.elements) || !Number.isFinite(m.determinant()) || m.determinant() === 0) fail('singular/nonfinite camera');
+ camera.matrixWorldInverse.copy(camera.matrixWorld).invert();
+ if (!finite([...camera.projectionMatrix.elements, ...camera.matrixWorldInverse.elements])) fail('invalid camera');
+ const projected = points.map(p => {
+ const xyz = Array.isArray(p) ? p : p?.toArray?.();
+ if (!xyz || xyz.length !== 3 || !finite(xyz)) fail('invalid projection point');
+ const clip = new THREE.Vector4(...xyz, 1).applyMatrix4(camera.matrixWorldInverse).applyMatrix4(camera.projectionMatrix);
+ if (!finite(clip.toArray()) || clip.w === 0) fail('invalid clip point');
+ const ndc = new THREE.Vector3(clip.x / clip.w, clip.y / clip.w, clip.z / clip.w);
+ return { ndc, clipped: clip.w <= 0 || Math.abs(ndc.x) > 1 - margin || Math.abs(ndc.y) > 1 - margin || Math.abs(ndc.z) > 1 };
+ });
+ return { pass: projected.every(p => !p.clipped), projected };
+ }
+ return { bounds, seated, outsideBox, scopedMeshes, worldAnchor, projectPoints };
+}
diff --git a/templates/mechanism-contract.mjs b/templates/mechanism-contract.mjs
new file mode 100644
index 0000000..fde5f4c
--- /dev/null
+++ b/templates/mechanism-contract.mjs
@@ -0,0 +1,108 @@
+// Unit-agnostic scalar interface checks; all values must share manifest units.
+// Not a geometry engine: actual mesh/proxy and swept-motion QA is still required.
+const finite = (x, name) => {
+ if (!Number.isFinite(x)) throw new Error(`${name}: finite number required`);
+ return x;
+};
+export function checkInterface({ id, shaftRadius, boreRadius, inwardBevel = 0,
+ requiredRadial, laneWidth, memberWidth, axialIntrusion = 0, requiredAxial }) {
+ if (!id) throw new Error('interface id required');
+ for (const [name, value] of Object.entries({ shaftRadius, boreRadius, inwardBevel,
+ requiredRadial, laneWidth, memberWidth, axialIntrusion, requiredAxial })) {
+ finite(value, name);
+ if (value < 0) throw new Error(`${id}: negative ${name}`);
+ }
+ const radial = boreRadius - inwardBevel - shaftRadius;
+ // Axial is the TOTAL remaining lane gap; specify a doubled requiredAxial
+ // if the requirement is a per-side clearance on a centred member.
+ const axial = laneWidth - memberWidth - axialIntrusion;
+ if (radial < requiredRadial || axial < requiredAxial) {
+ throw new Error(`${id}: insufficient interface budget radial=${radial}, axial=${axial}`);
+ }
+ return { id, radial, axial };
+}
+export function anchorResidual(a, b) {
+ if (a.length !== 3 || b.length !== 3) throw new Error('world anchor triples required');
+ return Math.hypot(...a.map((v, i) => finite(v, 'anchor') - finite(b[i], 'anchor')));
+}
+// Pass world-space directions derived from each part's actual world matrix.
+export function checkAxes(a, b, tolerance = 1e-6) {
+ const length = v => Math.hypot(...v.map(x => finite(x, 'axis')));
+ if (a.length !== 3 || b.length !== 3 || length(a) === 0 || length(b) === 0) throw new Error('nonzero axis triples required');
+ finite(tolerance, 'axis tolerance');
+ if (tolerance < 0 || tolerance >= 1) throw new Error('axis tolerance out of range');
+ const alignment = Math.abs(a.reduce((sum, x, i) => sum + x * b[i], 0) / (length(a) * length(b)));
+ if (1 - alignment > tolerance) throw new Error(`mating axes misaligned: ${alignment}`);
+ return alignment;
+}
+// One source of truth for repeated XY mounts, local +Z shaft/bore axes.
+// Transform BOTH mating frames by the same authored parent/world transforms.
+export function createMountAnchors({ frameId, count, radius, z = 0,
+ startAngle = Math.PI / 4, prefix = 'mount' }) {
+ if (!frameId || !prefix || !Number.isInteger(count) || count < 1) throw new Error('named frame and positive mount count required');
+ finite(radius, 'mount radius'); finite(z, 'mount z'); finite(startAngle, 'start angle');
+ if (radius <= 0) throw new Error('positive mount radius required');
+ return Object.freeze(Array.from({ length: count }, (_, i) => {
+ const angle = startAngle + 2 * Math.PI * i / count;
+ return Object.freeze({ id: `${prefix}-${i + 1}`, frameId,
+ position: Object.freeze([radius * Math.cos(angle), radius * Math.sin(angle), z]),
+ axis: Object.freeze([0, 0, 1]) });
+ }));
+}
+export function assertCoverage({ id, expectedIds, observedIds, expectedSamples, actualSamples }) {
+ if (!id || !Array.isArray(expectedIds) || !Array.isArray(observedIds)
+ || expectedIds.length === 0 || expectedIds.some(x => typeof x !== 'string' || !x)
+ || new Set(expectedIds).size !== expectedIds.length || new Set(observedIds).size !== observedIds.length)
+ throw new Error('nonempty unique expected/observed coverage IDs required');
+ if (expectedIds.length !== observedIds.length || expectedIds.some(x => !observedIds.includes(x)))
+ throw new Error(`${id}: subject coverage mismatch`);
+ if (!Number.isInteger(expectedSamples) || expectedSamples < 1
+ || !Number.isInteger(actualSamples) || actualSamples !== expectedSamples)
+ throw new Error(`${id}: sample coverage mismatch expected=${expectedSamples} actual=${actualSamples}`);
+ return { id, subjects: observedIds.length, samples: actualSamples };
+}
+export function checkRepeatedInterfaces({ id, expectedIds, pairs, positionTolerance = 1e-6, axisTolerance = 1e-6 }) {
+ finite(positionTolerance, 'position tolerance');
+ if (positionTolerance < 0 || !Array.isArray(pairs)) throw new Error('nonnegative position tolerance and mating pairs required');
+ assertCoverage({ id, expectedIds, observedIds: pairs.map(p => p.anchorId), expectedSamples: expectedIds.length, actualSamples: pairs.length });
+ let worstResidual = 0;
+ for (const p of pairs) {
+ const residual = anchorResidual(p.shaft.position, p.bore.position);
+ if (residual > positionTolerance) throw new Error(`${p.anchorId}: mating anchor residual ${residual}`);
+ checkAxes(p.shaft.axis, p.bore.axis, axisTolerance);
+ worstResidual = Math.max(worstResidual, residual);
+ }
+ return { id, count: pairs.length, worstResidual };
+}
+// Coordinates increase along the declared shaft axis. Cap outer face must not
+// coincide with the shaft end; the shaft must still reach the cap's inner seat.
+export function checkEndPlanes({ id, shaftEnd, capInnerFace, capOuterFace, minimumSeparation }) {
+ for (const [name, value] of Object.entries({ shaftEnd, capInnerFace, capOuterFace, minimumSeparation })) finite(value, name);
+ if (!id || minimumSeparation <= 0 || capOuterFace <= capInnerFace)
+ throw new Error('valid end-plane interface and positive separation required');
+ const separation = capOuterFace - shaftEnd;
+ if (shaftEnd < capInnerFace || separation < minimumSeparation)
+ throw new Error(`${id}: unsupported or coplanar cap/shaft end planes`);
+ return { id, separation };
+}
+
+// Surface IDs, not group/type IDs. Driver phase is in unwrapped manifest units.
+// Wraparound contact windows must be split explicitly into [start,end] intervals.
+export function checkPair({ a, b, phase, gap, requiredClearance, contacts = [] }) {
+ if (!a || !b || a === b) throw new Error('distinct surface IDs required');
+ finite(phase, 'phase'); finite(gap, 'signed gap');
+ finite(requiredClearance, 'requiredClearance');
+ if (requiredClearance < 0) throw new Error('negative clearance');
+ for (const c of contacts) {
+ if (!c.reason || !c.a || !c.b || c.a === c.b) throw new Error('scoped contact rationale required');
+ for (const k of ['from', 'to', 'maxPenetration', 'maxGap']) finite(c[k], k);
+ if (c.to < c.from || c.maxPenetration < 0 || c.maxGap < 0) throw new Error('invalid contact window/tolerance');
+ }
+ const permitted = contacts.filter(c => ((a === c.a && b === c.b) || (a === c.b && b === c.a))
+ && phase >= c.from && phase <= c.to);
+ if (permitted.length > 1) throw new Error('ambiguous contact policy');
+ const c = permitted[0];
+ const ok = c ? gap >= -c.maxPenetration && gap <= c.maxGap : gap >= requiredClearance;
+ if (!ok) throw new Error(`${a}/${b} phase=${phase} gap=${gap}: ${c ? 'contact tolerance' : 'clearance'} failed`);
+ return { a, b, phase, gap, intendedContact: Boolean(c) };
+}
diff --git a/templates/orbit.js b/templates/orbit.js
new file mode 100644
index 0000000..94fc8b7
--- /dev/null
+++ b/templates/orbit.js
@@ -0,0 +1,68 @@
+// All presets: deterministic hero pose + user orbit; never auto-spin.
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+
+export function createDioramaOrbit(camera, canvas, {
+ target, minDistance = 1, maxDistance = 100,
+ minPolarAngle = 0.08, maxPolarAngle = Math.PI - 0.08,
+ clickSlop = 5, onSelect = () => {}, onChange = () => {},
+} = {}) {
+ const controls = new OrbitControls(camera, canvas);
+ if (target) controls.target.copy(target);
+ controls.enablePan = false;
+ controls.autoRotate = false;
+ // No damping tail: a drag must not move the camera after QA resets it.
+ controls.enableDamping = false;
+ Object.assign(controls, { minDistance, maxDistance, minPolarAngle, maxPolarAngle });
+ controls.update();
+ const heroPosition = camera.position.clone(), heroTarget = controls.target.clone();
+ const heroZoom = camera.zoom;
+ const pointers = new Map();
+ let gesture = false;
+ function down(e) {
+ pointers.set(e.pointerId, { x: e.clientX, y: e.clientY, moved: false });
+ if (pointers.size > 1) { gesture = true; for (const p of pointers.values()) p.moved = true; }
+ }
+ function move(e) {
+ const p = pointers.get(e.pointerId);
+ if (p && Math.hypot(e.clientX - p.x, e.clientY - p.y) > clickSlop) p.moved = true;
+ }
+ function up(e) {
+ const p = pointers.get(e.pointerId);
+ pointers.delete(e.pointerId);
+ if (p && Math.hypot(e.clientX - p.x, e.clientY - p.y) > clickSlop) p.moved = true;
+ if (p && !p.moved && !gesture && (e.button === 0 || e.pointerType === 'touch')) onSelect(e);
+ if (!pointers.size) gesture = false;
+ }
+ function cancel(e) { pointers.delete(e.pointerId); if (!pointers.size) gesture = false; }
+ function reset() {
+ pointers.clear(); gesture = false;
+ camera.position.copy(heroPosition); camera.zoom = heroZoom;
+ controls.target.copy(heroTarget); camera.updateProjectionMatrix(); controls.update();
+ onChange();
+ }
+ function key(e) {
+ if (e.target !== canvas) return;
+ if (e.key.toLowerCase() === 'r') { e.preventDefault(); reset(); return; }
+ const delta = { ArrowLeft: [-0.12, 0], ArrowRight: [0.12, 0], ArrowUp: [0, -0.12], ArrowDown: [0, 0.12] }[e.key];
+ if (!delta) return;
+ e.preventDefault();
+ const offset = camera.position.clone().sub(controls.target);
+ const r = offset.length(), theta = Math.atan2(offset.x, offset.z) + delta[0];
+ const phi = Math.max(minPolarAngle, Math.min(maxPolarAngle, Math.acos(offset.y / r) + delta[1]));
+ offset.set(r * Math.sin(phi) * Math.sin(theta), r * Math.cos(phi), r * Math.sin(phi) * Math.cos(theta));
+ camera.position.copy(controls.target).add(offset); controls.update(); onChange();
+ }
+ const oldTabIndex = canvas.getAttribute('tabindex');
+ if (oldTabIndex === null) canvas.tabIndex = 0;
+ const listeners = [['pointerdown', down], ['pointermove', move], ['pointerup', up], ['pointercancel', cancel], ['keydown', key]];
+ // Capture movement before OrbitControls or app bubbling handlers consume it.
+ for (const [name, fn] of listeners) canvas.addEventListener(name, fn, true);
+ controls.addEventListener('change', onChange);
+ return { controls, reset, heroPosition, heroTarget,
+ dispose() {
+ for (const [name, fn] of listeners) canvas.removeEventListener(name, fn, true);
+ controls.removeEventListener('change', onChange); controls.dispose(); pointers.clear();
+ if (oldTabIndex === null) canvas.removeAttribute('tabindex');
+ },
+ };
+}
diff --git a/templates/pixel-stroke.js b/templates/pixel-stroke.js
new file mode 100644
index 0000000..c39a267
--- /dev/null
+++ b/templates/pixel-stroke.js
@@ -0,0 +1,34 @@
+// Optional pixel+stroke hybrid. Project style confirmation required.
+// Render toon + selective geometry outlines ONCE into a low-res target,
+// then nearest upscale. Never stack PixelPost/Sobel/another edge pipeline.
+import * as THREE from 'three';
+import { createStrokedToon } from './stroked-toon.js';
+
+export function createPixelStroke(renderer, { width = 320, height = 200, ...options } = {}) {
+ const look = createStrokedToon(renderer, { ...options, dpr: 1, maxDpr: 1 });
+ const target = new THREE.WebGLRenderTarget(1, 1, {
+ minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter,
+ depthBuffer: true, stencilBuffer: false,
+ });
+ target.texture.generateMipmaps = false;
+ // Linear target; final fullscreen material performs output colour conversion.
+ const material = new THREE.MeshBasicMaterial({ map: target.texture, depthTest: false, depthWrite: false, transparent: true });
+ const geometry = new THREE.PlaneGeometry(2, 2);
+ const screen = new THREE.Scene(); screen.add(new THREE.Mesh(geometry, material));
+ const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ function setSize(w, h) {
+ if (![w, h].every(n => Number.isInteger(n) && n > 0)) throw new Error('pixel-stroke size must be positive integers');
+ target.setSize(w, h);
+ }
+ setSize(width, height);
+ return { ...look, preset: 'pixel-stroke', target, setSize,
+ render(scene, viewCamera) {
+ const previous = renderer.getRenderTarget();
+ try {
+ renderer.setRenderTarget(target); renderer.clear(); look.render(scene, viewCamera);
+ renderer.setRenderTarget(previous); renderer.clear(); renderer.render(screen, camera);
+ } finally { renderer.setRenderTarget(previous); }
+ },
+ dispose() { target.dispose(); material.dispose(); geometry.dispose(); look.dispose(); },
+ };
+}
diff --git a/templates/pose-bounds.mjs b/templates/pose-bounds.mjs
new file mode 100644
index 0000000..a7816fb
--- /dev/null
+++ b/templates/pose-bounds.mjs
@@ -0,0 +1,64 @@
+// CPU posed bounds for QA. Caller evaluates its real driver/mixer first.
+// Includes hidden/transparent physical meshes. Bounds are conservative, not mesh collision.
+export function createPoseBounds(THREE) {
+ const fail = message => { throw new Error(`pose-bounds: ${message}`); };
+ const finite = a => a.every(Number.isFinite);
+ function measure(mesh, { instanceId, frame, includePoints = false } = {}) {
+ if (!mesh?.isMesh || mesh.isBatchedMesh) fail('ordinary, skinned or explicit rigid instance Mesh required');
+ const geometry = mesh.geometry, position = geometry?.getAttribute?.('position');
+ if (!position || position.itemSize !== 3 || !Number.isInteger(position.count) || position.count < 3) fail('nonempty geometry required');
+ for (const m of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
+ if (!m?.isMaterial || m.isShaderMaterial || m.isRawShaderMaterial || m.displacementMap ||
+ m.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile) fail('unmeasured shader/displacement geometry');
+ }
+ mesh.updateWorldMatrix(true, false);
+ if (mesh.isSkinnedMesh) {
+ mesh.updateMatrixWorld(true); // also refresh attached bindMatrixInverse
+ if (!mesh.skeleton?.bones?.length) fail('missing skeleton');
+ for (const bone of mesh.skeleton.bones) bone.updateWorldMatrix(true, false);
+ mesh.skeleton.update();
+ }
+ const matrix = mesh.matrixWorld.clone();
+ if (mesh.isInstancedMesh) {
+ if (!Number.isInteger(instanceId) || instanceId < 0 || instanceId >= mesh.count || mesh.morphTexture) fail('explicit rigid instance id required; instance morph unsupported');
+ const instance = new THREE.Matrix4(); mesh.getMatrixAt(instanceId, instance); matrix.multiply(instance);
+ } else if (instanceId !== undefined) fail('instanceId on non-instanced mesh');
+ if (frame) {
+ if (!frame.isObject3D) fail('Object3D frame required');
+ frame.updateWorldMatrix(true, false);
+ if (!finite(frame.matrixWorld.elements) || frame.matrixWorld.determinant() === 0) fail('invalid frame');
+ matrix.premultiply(frame.matrixWorld.clone().invert());
+ }
+ if (!finite(matrix.elements) || matrix.determinant() === 0) fail('invalid world transform');
+ const index = geometry.getIndex();
+ if (index && (index.itemSize !== 1 || !Number.isInteger(index.count))) fail('malformed index');
+ const count = index ? index.count : position.count, range = geometry.drawRange;
+ if (!range || !Number.isInteger(range.start) || range.start < 0 || range.start > count ||
+ !(range.count === Infinity || Number.isInteger(range.count) && range.count >= 0)) fail('invalid drawRange');
+ const end = Math.min(count, range.start + range.count);
+ if (end <= range.start || range.start % 3 || (end - range.start) % 3) fail('empty/malformed triangle range');
+ if (typeof mesh.getVertexPosition !== 'function') fail('Three.js getVertexPosition support required');
+ const bounds = new THREE.Box3(), points = includePoints ? [] : undefined;
+ let nondegenerate = false; const triangle = [];
+ for (let i = range.start; i < end; i++) {
+ const vertex = index ? index.getX(i) : i;
+ if (!Number.isInteger(vertex) || vertex < 0 || vertex >= position.count) fail('invalid index');
+ const point = mesh.getVertexPosition(vertex, new THREE.Vector3());
+ if (!finite(point.toArray())) fail('nonfinite posed vertex');
+ point.applyMatrix4(matrix);
+ if (!finite(point.toArray())) fail('nonfinite transformed vertex');
+ bounds.expandByPoint(point); if (points) points.push(point.clone());
+ triangle.push(point);
+ if (triangle.length === 3) {
+ const cross = new THREE.Vector3().subVectors(triangle[1],triangle[0]).cross(new THREE.Vector3().subVectors(triangle[2],triangle[0]));
+ if (!Number.isFinite(cross.lengthSq())) fail('invalid triangle');
+ nondegenerate ||= cross.lengthSq() > 0; triangle.length = 0;
+ }
+ }
+ if (bounds.isEmpty() || !nondegenerate) fail('empty/collapsed posed geometry');
+ return { bounds, points, vertexCount: end-range.start,
+ method: mesh.isSkinnedMesh ? 'cpu-skinned-active-vertices' : mesh.morphTargetInfluences?.length ? 'cpu-morphed-active-vertices' : 'rigid-active-vertices',
+ limitation: 'At this pose only; group/material ranges may be over-covered. No GPU deformation or continuous/mesh-intersection proof.' };
+ }
+ return { measure };
+}
diff --git a/templates/post.js b/templates/post.js
index ad963c9..d240c21 100644
--- a/templates/post.js
+++ b/templates/post.js
@@ -1,3 +1,6 @@
+// CLASSIC PIXEL ONLY (renderPreset: 'pixel'). Not Pixel Art V2.
+// V2 ('pixel-v2') requires a separate low-resolution depth-edge renderer;
+// see SKILL.md's Pixel Art V2 contract and references/pixel-v2.md.
import * as THREE from 'three';
import { PALETTE_RGB } from './palette.js';
diff --git a/templates/qa/README.md b/templates/qa/README.md
index 6bbf3d8..2c64146 100644
--- a/templates/qa/README.md
+++ b/templates/qa/README.md
@@ -108,7 +108,7 @@ only with a written reason in `DESIGN.md`.
## What "passing" looks like
- `no console errors` at 1280×800, 1388×950 and 390×844, and the camera position
- identical across all three samples of the same viewport (the angle is locked).
+ identical across all three samples of the same viewport (reset the hero pose before every sample).
- `audit passed` with no `ERROR` lines. Warnings are allowed at the default
strictness; `STRICT=1` makes them fail too. The margin limit is
`MARGIN_RATIO=0.0002` (0.02% of the sampled margin).
@@ -168,7 +168,7 @@ FROM=4 TO=9 FPS=12 OUT=qa/frames STATIC=guard \
- `ENTITIES` is a JS expression evaluated in the page, returning `{name: Object3D}`.
The build should expose `window.__diorama.entities` so the default works.
- `VIEW=portrait` (default) fits one camera to the entity's swept bounds, so the
- whole move stays in frame and fills it. `VIEW=scene` keeps the locked camera and
+ whole move stays in frame and fills it. `VIEW=scene` keeps the reset hero camera and
crops to the entity instead.
- `ISOLATE=scene` hides every mesh that is not on the entity's branch, so the
motion signature is about that actor alone. `siblings` hides only the other
@@ -181,3 +181,29 @@ Each entity gets `qa/frames/<name>/f###.png`, a contact sheet, and a row in
on any flag, so a build can gate on it. Read the sheets; the numbers only say
which sheet to open first.
+
+
+## 3.14 interface and educational UI regression helpers
+
+`mechanism-contract.test.mjs` imports `../mechanism-contract.mjs`; it has no dependencies. Run `node templates/qa/mechanism-contract.test.mjs` from the skill root. `templates/mechanism-contract.mjs` exposes `createMountAnchors`, `checkRepeatedInterfaces`, `assertCoverage` and `checkEndPlanes` for these scalar checks, not mesh certification. Check scalar bore/bevel/axial budgets, source-frame IDs, shaft/bore axes and shared anchors for every repeated mount (derive full geometry + tolerances, never separately guessed offsets), world-anchor residual, cap endplanes with anti-z-fighting separation, and strict surface-pair/window contact policy, including injected violations. Scalar helpers do NOT inspect meshes or certify swept collision safety. Supply project-specific transformed geometry/proxy tests, axis assertions, full-cycle/transition/refined sweeps and two-angle section crops. Assert nonempty fixtures/pairs and expected sample counts; inspect actual runtime geometry types, including a RoundedBox-labelled fixture whose geometry reports Box, rather than trusting helper names. Record pair coverage, exclusions, worst gap/phase, units, tolerance, geometry revision and method limitations. Vertex/triangle sampling is not exact continuous proof; unexplained omissions or unrun checks remain UNVERIFIED.
+
+`education-dock.test.mjs` imports `../education-dock.mjs` and its CSS and needs `playwright-core` plus Chromium. Run `CHROME=/absolute/path/to/chrome node templates/qa/education-dock.test.mjs`; optionally set `DIORAMA_TEST_PACKAGE=/absolute/path/to/project/package.json` for dependency resolution. It uses synthetic input/link/output data at desktop and narrow-phone sizes, keyboard disclosure/step, frozen phase/text/part sync, scrub, play, picker, reset, UI-event isolation, reduced-motion emulation and disposal. The dependency-free DOM template is a starting point, not a second timeline: call `dock.sync(evaluatedState)` after the real scene evaluates; step `freeze(phase)` must synchronously evaluate it. Mount outside canvas; wire `selectPart` to the scene's tested reversible selection/highlight without automatically focusing the camera on lesson steps; reserve camera focus for a deliberate Inspect action, `setPlaying` to its clock and `resetView` to orbit reset. Initialize with evaluated state; dispose on teardown.
+
+Per-scene UI acceptance still requires desktop/phone and 200% zoom captures, mechanism not covered by the dock, actual geometry selection/hidden picker, material restoration, camera interruption, rapid reselection/steps, pause+orbit, keyboard-only full task, contrast and focus review. Template helpers do not prove scene accessibility, real ports/supports, axis orientation or exact collision absence. Neither helper requires React, Tailwind or shadcn.
+
+## Soft glow and holographic inspection regression
+
+Follow the single authoritative recipe under Canonical educational UI and inspection contract in the skill. `templates/inspection.js` exposes `createInspection(THREE, ...)`, `.select({ partId, mesh })`, `.clear()`, `.refresh()`, `.dispose()` and `.piecePickerEntries()`. Author `resolveVisibility` with `hiddenPartIds`/`hiddenMeshes` + `description`: hidden owners require `shell: true`, or `inspectionOccluder: true` with an active explained selection-only cutaway. Optional `ghostPartIds`/`ghostMeshes` apply strictly to `shell: true`. Context meshes never dim/hide/ghost; selected scope cannot self-hide. Never ghost the whole mechanism.
+
+Run from the skill root, resolving existing `three`, `esbuild` and `playwright-core` from the consumer project; no install step is required:
+
+```bash
+DIORAMA_TEST_PROJECT=/absolute/consumer/project node templates/qa/inspection.test.mjs
+DIORAMA_TEST_PROJECT=/absolute/consumer/project DIORAMA_QA_OUT=/absolute/output node templates/qa/inspection-browser.mjs
+```
+
+`CHROME_PATH` overrides the default macOS Chrome executable. The browser fixture checks synthetic rendered pixel contrast, depth/occlusion and restoration across three presets. Its Home/End keyboard adapter is fixture-only, not consumer keyboard certification. Record actual command exit outcomes; availability of these helpers is not a test-pass claim. All per-scene acceptance below must be rerun on the consumer build.
+
+Per-scene checks: stable assembly versus mesh-piece IDs/mapping and keyboard picker coverage; shared/multi-material clone isolation and exact restoration of material identities/array slots, visibility and cast/receive shadows; MeshBasicMaterial must acquire no added emissive properties. Use an authored warm or cool highlight with demonstrably visible contrast and retained form rather than bloom or a white blob; tune colour/emission for the active preset, not a fixed universal intensity. Use explicit shell-only ghosting and an authorized blocker/reveal plan per hidden target. Selected feature edges exclude decals, keep depth testing on/depth writes off and raycasting disabled. Verify two frozen phases plus moving source transforms, opaque-occluder rejection, Inside state independent of selection clear, and repeated selection/reset/teardown without stale edges or resource growth. Test flat/toon and the active pixel/native/hybrid pipeline, desktop/phone and non-colour cues. Generic EdgesGeometry supports rigid geometry, not automatic skin/morph/instance deformation. Every selectable part needs before/selected/restored screenshots and a reviewed contrast/occlusion verdict; emissive > 0 is not evidence of a visible highlight.
+
+Gate release on nonempty fixtures and asserted expected/actual sample counts, with negative injections for invisible/occluded highlights, wrong picker granularity, decal edges, blocker-plan omissions and restoration failures. Tie each QA manifest to the final build hash and tested geometry/artifact revision, exact commands and exit outcomes, proof paths and injected failures. Rebuilds invalidate stale evidence; missing commands, screenshots or coverage remain UNVERIFIED, never a pass.
diff --git a/templates/qa/education-dock.test.mjs b/templates/qa/education-dock.test.mjs
new file mode 100644
index 0000000..a49f15f
--- /dev/null
+++ b/templates/qa/education-dock.test.mjs
@@ -0,0 +1,50 @@
+// Run where playwright-core resolves; CHROME may override the executable.
+import { createRequire } from 'node:module';
+import { readFile } from 'node:fs/promises';
+import assert from 'node:assert/strict';
+const require = createRequire(process.env.DIORAMA_TEST_PACKAGE || import.meta.url);
+const { chromium } = require('playwright-core');
+const source = await readFile(new URL('../education-dock.mjs', import.meta.url), 'utf8');
+const css = await readFile(new URL('../education-dock.css', import.meta.url), 'utf8');
+const browser = await chromium.launch({ executablePath: process.env.CHROME || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', headless: true });
+try {
+ for (const viewport of [{ width: 1280, height: 800 }, { width: 390, height: 844 }, { width: 320, height: 640 }]) {
+ const page = await browser.newPage({ viewport, reducedMotion: 'reduce' });
+ const errors = []; page.on('pageerror', error => errors.push(error.message));
+ await page.setContent('<main id="mount"></main>'); await page.addStyleTag({ content: css });
+ await page.evaluate(async ({ source }) => {
+ const { createEducationDock } = await import(`data:text/javascript,${encodeURIComponent(source)}`);
+ window.calls = []; document.body.addEventListener('pointerdown', () => calls.push('leaked'));
+ const steps = [{ id: 'a', title: 'Input moves', phase: 0, partId: 'input', result: 'The input pushes the link.' },
+ { id: 'b', title: 'Output follows', phase: 1, partId: 'output', result: 'The link moves the output.' }];
+ window.dock = createEducationDock({ mount: document.querySelector('#mount'), title: 'Link lesson',
+ summary: 'Input → link → output', steps, parts: [{ id: 'input', label: 'Input' }, { id: 'output', label: 'Output' }],
+ freeze(phase) { calls.push(['freeze', phase]); return { phase, stepId: phase < .5 ? 'a' : 'b', readout: `Phase ${phase}` }; },
+ selectPart(id) { calls.push(['select', id]); }, setPlaying(p) { calls.push(['playing', p]); }, resetView() { calls.push('reset'); } });
+ dock.sync({ phase: 0, stepId: 'a', readout: 'Phase 0' });
+ }, { source });
+ const disclosure = page.getByText('How it works', { exact: true });
+ await disclosure.focus(); await page.keyboard.press('Enter');
+ await page.getByRole('button', { name: 'Output follows', exact: true }).focus(); await page.keyboard.press('Enter');
+ assert.equal(await page.locator('output').textContent(), 'Phase 1');
+ assert.equal(await page.locator('[aria-current=step]').textContent(), 'Output follows');
+ assert.equal(await page.locator('select').inputValue(), 'output');
+ await page.locator('input').fill('0');
+ assert.equal(await page.locator('output').textContent(), 'Phase 0');
+ await page.getByRole('button', { name: 'Play', exact: true }).click();
+ assert.equal(await page.getByRole('button', { name: 'Pause', exact: true }).getAttribute('aria-pressed'), 'true');
+ await page.getByRole('button', { name: 'Reset view' }).click();
+ await page.locator('select').selectOption('output');
+ assert(await page.evaluate(() => calls.some(c => c[0] === 'select' && c[1] === 'output')));
+ assert(await page.evaluate(() => calls.includes('reset')));
+ assert(!await page.evaluate(() => calls.includes('leaked')));
+ if (process.env.DIORAMA_SHOTS) await page.screenshot({ path: `${process.env.DIORAMA_SHOTS}/dock-${viewport.width}.png` });
+ const overflow = await page.evaluate(() => document.documentElement.scrollWidth > innerWidth);
+ assert.equal(overflow, false);
+ assert(await page.locator('input').evaluate(e => e.labels.length === 1));
+ await page.evaluate(() => { dock.dispose(); });
+ assert.equal(await page.locator('.education-dock').count(), 0);
+ assert.deepEqual(errors, []); await page.close();
+ }
+ console.log('PASS: 1280/390/320px, keyboard disclosure/step, frozen state sync, scrub, play, picker, reset, event isolation, disposal, reduced-motion');
+} finally { await browser.close(); }
diff --git a/templates/qa/inspection-browser.mjs b/templates/qa/inspection-browser.mjs
new file mode 100644
index 0000000..02a8be6
--- /dev/null
+++ b/templates/qa/inspection-browser.mjs
@@ -0,0 +1,92 @@
+// Rendered helper regression, not a substitute for the subject's own QA/UI.
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import path from 'node:path';
+const project=path.resolve(process.env.DIORAMA_TEST_PROJECT||process.cwd());
+const require=createRequire(path.join(project,'package.json'));
+const { build }=require('esbuild');const { chromium }=require('playwright-core');
+const templates=path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const out=path.resolve(process.env.DIORAMA_QA_OUT||path.join(project,'qa','skill-inspection'));
+await mkdir(out,{recursive:true});
+const imported=name=>JSON.stringify(path.join(templates,name));
+const fixture=`
+import * as THREE from 'three';
+import { createInspection } from ${imported('inspection.js')};
+import { createStrokedToon } from ${imported('stroked-toon.js')};
+import { createPixelStroke } from ${imported('pixel-stroke.js')};
+import { PixelPost } from ${imported('post.js')};
+const preset=new URLSearchParams(location.search).get('preset');
+const canvas=document.querySelector('canvas');
+const renderer=new THREE.WebGLRenderer({canvas,antialias:preset==='stroked-toon',preserveDrawingBuffer:true});
+renderer.setPixelRatio(1);renderer.setSize(600,400,false);
+let look;
+if(preset==='pixel-stroke')look=createPixelStroke(renderer,{width:300,height:200});
+else if(preset==='pixel'){look=new PixelPost(renderer);look.setSize(600,400);renderer.toneMapping=THREE.NoToneMapping;}
+else look=createStrokedToon(renderer,{dpr:1,maxDpr:1});
+const scene=new THREE.Scene();scene.add(new THREE.HemisphereLight(0xffffff,0x505b69,1.5));
+const light=new THREE.DirectionalLight(0xffffff,2);light.position.set(-3,5,8);scene.add(light);
+const camera=new THREE.OrthographicCamera(-4.5,4.5,3,-3,.1,100);camera.position.set(5,4,9);camera.lookAt(0,0,0);
+const ramp=new THREE.DataTexture(new Uint8Array([68,122,184,246]),4,1,THREE.RedFormat);ramp.minFilter=ramp.magFilter=THREE.NearestFilter;ramp.needsUpdate=true;
+const shared=new THREE.MeshToonMaterial({color:0x87633d,gradientMap:ramp});shared.userData.outlineParameters={visible:true,thickness:.003};
+const basic=new THREE.MeshBasicMaterial({color:0x315444});basic.userData.outlineParameters={visible:false};
+const a=new THREE.Mesh(new THREE.BoxGeometry(1.3,1.3,1),shared);a.position.x=-2.1;
+const sibling=new THREE.Mesh(new THREE.BoxGeometry(.4,.4,.4),shared);sibling.position.set(-2.1,1,0);
+const b=new THREE.Mesh(new THREE.BoxGeometry(1.3,1.3,1),basic);
+const multi=new THREE.Mesh(new THREE.BoxGeometry(1.3,1.3,1),[shared,basic,shared,basic,shared,basic]);multi.position.x=2.1;
+const meshes=[a,sibling,b,multi];meshes.forEach((m,i)=>{m.name='fixture-piece-'+i;scene.add(m)});
+// An unregistered opaque foreground object must keep occluding depth-tested edges.
+const direction=camera.position.clone().normalize();
+const occluder=new THREE.Mesh(new THREE.BoxGeometry(.36,.36,.3),new THREE.MeshBasicMaterial({color:0x242424}));occluder.position.copy(a.position).add(new THREE.Vector3(.65,0,.5)).addScaledVector(direction,1.2);scene.add(occluder);
+const parts=new Map([['shared',{meshes:[a,sibling]}],['basic',{meshes:[b]}],['multi',{meshes:[multi]}]]);
+function render(){look.render(scene,camera)}
+const inspect=createInspection(THREE,{parts,onChange:render});
+const part=document.querySelector('#part'),piece=document.querySelector('#piece');
+function entries(){piece.replaceChildren(new Option('Whole assembly',''));if(inspect.selection)for(const e of inspect.piecePickerEntries(inspect.selection.partId))piece.add(new Option(e.label,e.value));}
+part.onchange=()=>{inspect.select({partId:part.value});entries()};
+piece.onchange=()=>inspect.select({partId:part.value,mesh:inspect.piecePickerEntries(part.value).find(e=>e.value===piece.value)?.mesh||null});
+// Explicit fixture Home/End adapter avoids an OS-native popup in headless runs;
+// this proves this adapter only, not keyboard operation of a consuming scene.
+piece.onkeydown=event=>{if(!['Home','End'].includes(event.key))return;event.preventDefault();piece.selectedIndex=event.key==='End'?piece.options.length-1:0;piece.dispatchEvent(new Event('change',{bubbles:true}));};
+document.querySelector('#clear').onclick=()=>{inspect.clear();entries()};
+function pixels(){render();const gl=renderer.getContext(),data=new Uint8Array(600*400*4);gl.readPixels(0,0,600,400,gl.RGBA,gl.UNSIGNED_BYTE,data);return data;}
+function region(mesh){const p=mesh.getWorldPosition(new THREE.Vector3()).project(camera);return{x:Math.round((p.x+1)*300),y:Math.round((p.y+1)*200)};}
+function meanDifference(a,b,region){let total=0,count=0;for(let y=region.y-30;y<=region.y+30;y++)for(let x=region.x-30;x<=region.x+30;x++){const i=(y*600+x)*4;total+=Math.abs(a[i]-b[i])+Math.abs(a[i+1]-b[i+1])+Math.abs(a[i+2]-b[i+2]);count+=3;}return total/count;}
+render();
+window.fixture={inspect,renderer,scene,camera,parts,pixels,region,meanDifference,
+check(id){inspect.clear();const base=pixels();inspect.select({partId:id});const selected=pixels();const mesh=parts.get(id).meshes[0];const delta=meanDifference(base,selected,region(mesh));const occlusion=region(occluder),j=(occlusion.y*600+occlusion.x)*4;
+const patchDelta=data=>{let worst=0;for(let y=occlusion.y-4;y<=occlusion.y+4;y++)for(let x=occlusion.x-4;x<=occlusion.x+4;x++)for(let k=0;k<3;k++)worst=Math.max(worst,Math.abs(base[(y*600+x)*4+k]-data[(y*600+x)*4+k]));return worst;};
+const depthDelta=patchDelta(selected),occluderDark=base[j]<60&&base[j+1]<60&&base[j+2]<60;
+let negativeDepthDetected=null;
+if(id==='shared'){const edge=a.children.find(x=>x.userData.inspectionOverlay);edge.material.depthTest=false;negativeDepthDetected=patchDelta(pixels())>8;edge.material.depthTest=true;render();}
+inspect.clear();const restored=pixels();let restoredDiff=0;for(let i=0;i<base.length;i++)if(base[i]!==restored[i])restoredDiff++;return{id,delta,depthDelta,occluderDark,negativeDepthDetected,restoredDiff};},
+move(){a.position.y=.2;scene.updateMatrixWorld(true);const e=a.children.find(x=>x.userData.inspectionOverlay);if(!e)return false;return e.getWorldPosition(new THREE.Vector3()).distanceTo(a.getWorldPosition(new THREE.Vector3()))<1e-10;},
+render};
+`;
+const result=await build({stdin:{contents:fixture,resolveDir:templates,sourcefile:'inspection-fixture.js'},bundle:true,write:false,format:'iife',platform:'browser',nodePaths:[path.join(project,'node_modules')]});
+const bundle=result.outputFiles[0].text;
+await writeFile(path.join(out,'fixture.html'),`<!doctype html><meta charset="utf-8"><title>Inspection regression fixture</title><style>body{background:#f7f7f5;font:14px system-ui}canvas{display:block;width:600px;height:400px}button,select{font:inherit;margin:8px}</style><canvas width="600" height="400"></canvas><label>Assembly<select id="part"><option>shared</option><option>basic</option><option>multi</option></select></label><label>Piece<select id="piece"></select></label><button id="clear">Clear</button><script>${bundle.replace(/<\/script/gi,'<\\/script')}</script>`);
+const report={command:'node templates/qa/inspection-browser.mjs',bundleSha256:createHash('sha256').update(bundle).digest('hex'),helperSha256:createHash('sha256').update(await readFile(path.join(templates,'inspection.js'))).digest('hex'),checks:[],screenshots:[],errors:[],limits:['Synthetic helper fixture only, not a complete educational UI or scene.','Rendered colour difference and depth assertions do not prove every subject-specific part readable; inspect the captures and repeat in the real scene.','No camera focus, orbit, mechanical contact, deformation or manufacturing certification.']};
+const executablePath=process.env.CHROME_PATH||'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
+const browser=await chromium.launch({executablePath,headless:true});
+try{
+ for(const preset of ['stroked-toon','pixel','pixel-stroke']){
+ const page=await browser.newPage({viewport:{width:640,height:530},deviceScaleFactor:1});
+ page.on('pageerror',e=>report.errors.push(e.stack));page.on('console',m=>{if(m.type()==='error')report.errors.push(m.text())});
+ await page.goto(pathToFileURL(path.join(out,'fixture.html')).href+'?preset='+preset);await page.waitForFunction(()=>window.fixture);
+ for(const id of ['shared','basic','multi']){
+ const check=await page.evaluate(id=>window.fixture.check(id),id);assert.ok(check.delta>8,`${preset}/${id} rendered emphasis invisible: ${check.delta}`);assert.ok(check.occluderDark,`${preset}: occluder fixture not sampled`);assert.ok(check.depthDelta<=1,`${preset}: opaque occluder lost`);if(id==='shared')assert.equal(check.negativeDepthDetected,true,`${preset}: injected depth override was not detected`);assert.equal(check.restoredDiff,0,`${preset}: restored render differs`);report.checks.push({preset,status:'PASS',...check});
+ await page.selectOption('#part',id);await page.screenshot({path:path.join(out,`${preset}-${id}.png`)});report.screenshots.push(`${preset}-${id}.png`);
+ }
+ await page.selectOption('#part','shared');await page.focus('#piece');await page.keyboard.press('End');
+ assert.equal(await page.evaluate(()=>window.fixture.inspect.selection.mesh?.name),'fixture-piece-1');
+ await page.selectOption('#piece',await page.locator('#piece option').nth(1).getAttribute('value'));
+ assert.equal(await page.evaluate(()=>window.fixture.move()),true);await page.focus('#clear');await page.keyboard.press('Enter');
+ assert.equal(await page.evaluate(()=>window.fixture.inspect.stats.overlays),0);await page.close();
+ }
+ assert.equal(report.checks.length,9,'all three fixtures in all three presets must run');
+ assert.deepEqual(report.errors,[]);report.status='PASS';console.log(JSON.stringify(report,null,2));
+}catch(error){report.status='FAIL';report.failure=error.stack;process.exitCode=1;console.error(error);}
+finally{await writeFile(path.join(out,'report.json'),JSON.stringify(report,null,2));await browser.close();}
diff --git a/templates/qa/inspection.test.mjs b/templates/qa/inspection.test.mjs
new file mode 100644
index 0000000..d3ccd3d
--- /dev/null
+++ b/templates/qa/inspection.test.mjs
@@ -0,0 +1,88 @@
+import assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { createInspection } from '../inspection.js';
+// Uses the consuming project's installed THREE; never installs or fetches one.
+const require = createRequire(path.resolve(process.env.DIORAMA_TEST_PROJECT || process.cwd(), 'package.json'));
+const THREE = await import(pathToFileURL(require.resolve('three')).href);
+const geometry = new THREE.BoxGeometry(1, 1, 1);
+const ramp = new THREE.DataTexture(new Uint8Array([68,122,184,246]),4,1,THREE.RedFormat);
+const shared = new THREE.MeshToonMaterial({ color: 0x997755, gradientMap: ramp });
+shared.userData.outlineParameters = { visible:true, alpha:.7, thickness:.003 };
+const basic = new THREE.MeshBasicMaterial({ color: 0x284d60 });
+const glass = new THREE.MeshPhysicalMaterial({ color: 0xbbccdd, transparent:true, opacity:.2, depthWrite:false });
+const a = new THREE.Mesh(geometry, shared), sibling = new THREE.Mesh(geometry, shared);
+a.name='shaft';sibling.name='seat';a.castShadow=true;sibling.receiveShadow=true;
+const b = new THREE.Mesh(geometry, basic), multi = new THREE.Mesh(geometry, [shared,basic]);
+const transparent = new THREE.Mesh(geometry, glass), decal = new THREE.Mesh(geometry, basic);
+decal.userData.inspectionEdge=false;
+const scene = new THREE.Scene();scene.add(a,sibling,b,multi,transparent,decal);
+const floor = new THREE.Mesh(geometry,basic); floor.castShadow=true; scene.add(floor);
+const parts = new Map([['mount',{ meshes:[a,sibling] }],['signal',{meshes:[b]}],['multi',{meshes:[multi]}],['glass',{meshes:[transparent],shell:true}],['decal',{meshes:[decal]}]]);
+const originals = new Map([...parts.values()].flatMap(p=>p.meshes).map(m=>[m,{material:m.material,visible:m.visible,castShadow:m.castShadow,receiveShadow:m.receiveShadow}]));
+const source = { shared:shared.color.getHex(),basic:basic.color.getHex(),outline:{...shared.userData.outlineParameters} };
+let inside=false,ghostMode=false;
+const inspect=createInspection(THREE,{parts,contextMeshes:[floor],resolveVisibility:()=>ghostMode?{ghostPartIds:['glass'],description:'Authored shell-only transparency'}:inside?{hiddenPartIds:['glass'],description:'Authored cover removal'}:{}});
+assert.throws(()=>inspect.select({partId:'missing'}),/unknown/);
+assert.throws(()=>inspect.select({partId:'mount',mesh:b}),/member/);
+inspect.select({partId:'mount',mesh:a});
+assert.notEqual(a.material,shared);assert.equal(a.material.gradientMap,ramp);
+assert.equal(floor.material,basic);assert.equal(floor.visible,true);assert.equal(floor.castShadow,true);
+assert.notEqual(a.material.userData.outlineParameters,shared.userData.outlineParameters);
+assert.equal(a.material.userData.outlineParameters.visible,false);
+assert(a.material.emissiveIntensity>.5);assert(sibling.material.color.r<shared.color.r);
+assert.equal(inspect.stats.overlays,1);assert.equal(a.children[0].material.depthTest,true);
+assert.equal(a.children[0].userData.inspectionOverlay,true);
+const before=new THREE.Vector3();a.children[0].getWorldPosition(before);a.position.x=2;scene.updateMatrixWorld(true);
+const after=new THREE.Vector3();a.children[0].getWorldPosition(after);assert.equal(after.x-before.x,2);
+inspect.select({partId:'mount'});assert.equal(inspect.stats.overlays,2);
+inspect.select({partId:'signal'});assert.equal(b.material.isMeshBasicMaterial,true);
+assert.equal('emissive' in b.material,false); // regression for uniform.value crashes
+inspect.select({partId:'multi'});assert(Array.isArray(multi.material));assert.equal('emissive' in multi.material[1],false);
+inspect.select({partId:'glass'});assert.equal(inspect.stats.overlays,0);assert.equal(transparent.material.opacity,.2);assert.equal(transparent.material.depthTest,true);
+inspect.select({partId:'decal'});assert.equal(inspect.stats.overlays,0);
+inside=true;inspect.refresh();assert.equal(transparent.visible,false);inside=false;inspect.clear();
+ghostMode=true;inspect.refresh();assert.equal(transparent.material.opacity,.105);assert.equal(transparent.material.depthTest,true);assert.equal(transparent.material.depthWrite,false);
+assert.throws(()=>inspect.select({partId:'glass'}),/solid/);assert.equal(inspect.selection,null);assert.equal(transparent.material,glass);
+ghostMode=false;inspect.clear();
+for(let i=0;i<80;i++){inspect.select({partId:i%2?'multi':'mount'});inspect.clear();}
+const warmed=inspect.stats.variants;
+for(let i=0;i<80;i++){inspect.select({partId:i%2?'multi':'mount'});inspect.clear();}
+assert.equal(inspect.stats.variants,warmed);assert.equal(inspect.stats.overlays,0);
+for(const [mesh,saved]of originals){assert.equal(mesh.material,saved.material);assert.equal(mesh.visible,saved.visible);assert.equal(mesh.castShadow,saved.castShadow);assert.equal(mesh.receiveShadow,saved.receiveShadow);}
+assert.equal(shared.color.getHex(),source.shared);assert.equal(basic.color.getHex(),source.basic);assert.deepEqual(shared.userData.outlineParameters,source.outline);
+assert.equal(inspect.piecePickerEntries('mount').length,2);a.visible=false;assert.equal(inspect.piecePickerEntries('mount',{visibleOnly:true}).length,1);inspect.clear();
+let sourceDisposed=false,rampDisposed=false;shared.addEventListener('dispose',()=>sourceDisposed=true);ramp.addEventListener('dispose',()=>rampDisposed=true);
+inspect.select({partId:'mount'});inspect.dispose();inspect.dispose();assert.equal(inspect.stats.variants,0);assert.equal(inspect.stats.overlays,0);assert.equal(sourceDisposed,false);assert.equal(rampDisposed,false);
+assert.equal(a.material,shared);assert.throws(()=>inspect.clear(),/disposed/);
+assert.throws(()=>createInspection(THREE,{parts:new Map()}),/nonempty/);
+assert.throws(()=>createInspection(THREE,{parts:{empty:{meshes:[]}}}),/nonempty/);
+assert.throws(()=>createInspection(THREE,{parts:{empty:{meshes:[new THREE.Mesh(new THREE.BufferGeometry(),basic)]}}}),/nonempty/);
+assert.throws(()=>createInspection(THREE,{parts:{a:{meshes:[a]},b:{meshes:[a]}}}),/twice/);
+assert.throws(()=>createInspection(THREE,{parts:{a:{meshes:[a]}},style:{dimFactor:NaN}}),/invalid/);
+assert.throws(()=>createInspection(THREE,{parts:{skin:{meshes:[new THREE.SkinnedMesh(geometry,shared)]}}}),/rigid/);
+assert.throws(()=>createInspection(THREE,{parts:{shader:{meshes:[new THREE.Mesh(geometry,new THREE.ShaderMaterial())]}}}),/adapter/);
+const badGhost=createInspection(THREE,{parts,resolveVisibility:()=>({ghostPartIds:['mount']})});
+assert.throws(()=>badGhost.select({partId:'signal'}),/manifest shell/);assert.equal(badGhost.selection,null);assert.equal(a.material,shared);badGhost.dispose();
+let plan={}; const guarded=createInspection(THREE,{parts,contextMeshes:[floor],resolveVisibility:()=>plan});
+for(const next of [{hiddenPartIds:['mount']},{hiddenMeshes:[b]},{hiddenMeshes:[floor]},{ghostMeshes:[floor]}]) {
+ plan=next;assert.throws(()=>guarded.select({partId:'signal'}),/hiding|context|shell/);
+ assert.equal(guarded.selection,null);assert.equal(a.material,shared);assert.equal(floor.material,basic);assert.equal(floor.visible,true);assert.equal(floor.castShadow,true);
+}
+parts.get('mount').inspectionOccluder=true;
+plan={hiddenMeshes:[a],description:'Authored upper bracket removal'};
+assert.throws(()=>guarded.select({partId:'mount'}),/selected/);
+plan={hiddenMeshes:[sibling],description:'Authored sibling removal for the shaft'};
+guarded.select({partId:'mount',mesh:a});assert.equal(sibling.visible,false);assert.equal(a.visible,true);assert.equal(floor.material,basic);
+plan={};guarded.clear();assert.equal(sibling.visible,true);guarded.dispose();delete parts.get('mount').inspectionOccluder;
+const { RoundedBoxGeometry }=await import(pathToFileURL(require.resolve('three/addons/geometries/RoundedBoxGeometry.js')).href);
+const { assertCoverage }=await import('../mechanism-contract.mjs');
+const rounded=new RoundedBoxGeometry(1,1,1,2,.1);assert.equal(rounded.type,'BoxGeometry');
+const fixture=[{id:'north',geometry:rounded},{id:'south',geometry:rounded}];
+const wrongFilter=fixture.filter(m=>m.geometry.type==='RoundedBoxGeometry');
+assert.throws(()=>assertCoverage({id:'runtime-magnets',expectedIds:['north','south'],observedIds:wrongFilter.map(m=>m.id),expectedSamples:2,actualSamples:wrongFilter.length}),/coverage/);
+assert.equal(assertCoverage({id:'runtime-magnets',expectedIds:['north','south'],observedIds:fixture.map(m=>m.id),expectedSamples:2,actualSamples:2}).subjects,2);
+rounded.dispose();geometry.dispose();shared.dispose();basic.dispose();glass.dispose();ramp.dispose();
+console.log('PASS: real THREE basic/toon/physical/multi-slot selection; exact identity/flags; live edges; no decal edges; bounded caches; shell-only ghost/fail-closed restoration; disposal; invalid/empty/unsupported fixtures and actual RoundedBox runtime-type false-pass rejected.');
+console.log('LIMIT: unit state checks do not prove rendered visibility, contrast, camera focus, a scene UI or mechanical clearance. Run inspection-browser.mjs and per-scene QA.');
diff --git a/templates/qa/mechanism-contract.test.mjs b/templates/qa/mechanism-contract.test.mjs
new file mode 100644
index 0000000..eeb8f6b
--- /dev/null
+++ b/templates/qa/mechanism-contract.test.mjs
@@ -0,0 +1,49 @@
+import assert from 'node:assert/strict';
+import { checkInterface, anchorResidual, checkAxes, checkPair, createMountAnchors,
+ checkRepeatedInterfaces, assertCoverage, checkEndPlanes } from '../mechanism-contract.mjs';
+const fit = { id: 'bearing', shaftRadius: 1, boreRadius: 1.08, inwardBevel: .02,
+ requiredRadial: .04, laneWidth: .5, memberWidth: .3, axialIntrusion: .02, requiredAxial: .1 };
+assert(checkInterface(fit).radial > .04);
+assert.throws(() => checkInterface({ ...fit, inwardBevel: .1 }));
+assert.throws(() => checkInterface({ ...fit, memberWidth: .45 }));
+assert.throws(() => checkInterface({ ...fit, shaftRadius: NaN }));
+assert.equal(anchorResidual([0, 1, 2], [0, 1, 2]), 0);
+assert(anchorResidual([0, 1, 2], [0, 1, 2.1]) > .09);
+assert.equal(checkAxes([0, 0, 1], [0, 0, -2]), 1);
+assert.throws(() => checkAxes([0, 0, 1], [0, 1, 0]), /misaligned/);
+assert.throws(() => checkAxes([0, 0, 0], [0, 0, 1]));
+const pair = { a: 'eye.inner', b: 'journal.outer', phase: 1, gap: 0,
+ requiredClearance: .01, contacts: [{ a: 'eye.inner', b: 'journal.outer', from: 0, to: 2,
+ maxPenetration: .001, maxGap: .003, reason: 'sliding bearing interface' }] };
+assert.equal(checkPair(pair).intendedContact, true);
+assert.throws(() => checkPair({ ...pair, phase: 3 }));
+assert.throws(() => checkPair({ ...pair, a: 'beam.face', gap: -.1 }));
+assert.throws(() => checkPair({ ...pair, gap: -.002 }));
+assert.throws(() => checkPair({ ...pair, contacts: [pair.contacts[0], pair.contacts[0]] }));
+assert.throws(() => checkPair({ ...pair, contacts: [{ ...pair.contacts[0], reason: '' }] }));
+assert.equal(checkPair({ ...pair, phase: 3, gap: .02 }).intendedContact, false);
+const anchors = createMountAnchors({ frameId: 'board-local', count: 4, radius: 13 });
+assert.equal(anchors.length, 4); assert(Object.isFrozen(anchors[0].position));
+const pairs = anchors.map(a => ({ anchorId: a.id,
+ shaft: { position: [...a.position], axis: [...a.axis] },
+ bore: { position: [...a.position], axis: [...a.axis] } }));
+const repeated = { id: 'four-mounts', expectedIds: anchors.map(a => a.id), pairs };
+assert.equal(checkRepeatedInterfaces(repeated).worstResidual, 0);
+const offset = structuredClone(pairs); offset[2].bore.position[0] += .4;
+assert.throws(() => checkRepeatedInterfaces({ ...repeated, pairs: offset }), /residual/);
+const wrongAxis = structuredClone(pairs); wrongAxis[1].shaft.axis = [1, 0, 0];
+assert.throws(() => checkRepeatedInterfaces({ ...repeated, pairs: wrongAxis }), /misaligned/);
+assert.throws(() => checkRepeatedInterfaces({ ...repeated, pairs: pairs.slice(0, 3) }), /coverage/);
+assert.throws(() => checkRepeatedInterfaces({ ...repeated, pairs: [pairs[0], pairs[0], pairs[2], pairs[3]] }), /coverage/);
+const coverage = { id: 'magnet-sweep', expectedIds: ['north', 'south'], observedIds: ['south', 'north'], expectedSamples: 144, actualSamples: 144 };
+assert.equal(assertCoverage(coverage).samples, 144);
+assert.throws(() => assertCoverage({ ...coverage, observedIds: [] }), /coverage/);
+assert.throws(() => assertCoverage({ ...coverage, actualSamples: 0 }), /coverage/);
+assert.throws(() => assertCoverage({ ...coverage, expectedIds: [], observedIds: [], actualSamples: 0 }), /coverage/);
+const ends = { id: 'support-cap', shaftEnd: 11.2, capInnerFace: 11.14, capOuterFace: 11.44, minimumSeparation: .1 };
+assert(checkEndPlanes(ends).separation > .2);
+assert.throws(() => checkEndPlanes({ ...ends, shaftEnd: 11.44 }), /coplanar/);
+assert.throws(() => checkEndPlanes({ ...ends, shaftEnd: 11 }), /unsupported/);
+assert.throws(() => createMountAnchors({ frameId: 'local', count: 0, radius: 13 }));
+console.log('PASS: original budgets/contact policy plus shared four-mount anchors, wrong-axis/offset/missing-mount injections, nonempty sample coverage and cap end-plane failures');
+console.log('LIMIT: scalar/frame coverage checks are not mesh bore, rendering or continuous collision certification.');
diff --git a/templates/scene-contract.js b/templates/scene-contract.js
new file mode 100644
index 0000000..070704c
--- /dev/null
+++ b/templates/scene-contract.js
@@ -0,0 +1,257 @@
+/* Dependency-injected scene checks; no imports, clocks, rendering, or geometry metadata.
+ * Rigid triangle meshes only; bounds use indexed/nonindexed active drawRange vertices.
+ * Each mesh needs a noncollapsed transform and a nondegenerate world triangle.
+ * Bounds/contact are coarse AABB evidence, NOT surface/solid collision certification.
+ * API: mesh(id, object), assembly(id, {meshes:[ids], anchors:{name:{mesh,local}}}),
+ * contact({id,upper,lower,axis:'y',tolerance,minOverlap}),
+ * exclude({meshes:[id,id],reason,maxDepth:[x,y,z],active?}), evaluate(state), sample(states, apply).
+ * Every root mesh must be registered and owned exactly once. Exemptions remove
+ * only one exact cross-assembly mesh pair, never an assembly or wildcard.
+ */
+export function createSceneContract(THREE, options = {}) {
+ const fail = message => { throw new Error(`Scene contract: ${message}`); };
+ const finite = (n, label) => {
+ if (typeof n !== 'number' || !Number.isFinite(n)) fail(`${label} must be finite`);
+ return n;
+ };
+ const nonnegative = (n, label) => {
+ if (finite(n, label) < 0) fail(`${label} must be nonnegative`);
+ return n;
+ };
+ const count = (n, label) => {
+ if (!Number.isSafeInteger(n) || n < 1) fail(`${label} must be a positive integer`);
+ return n;
+ };
+ const name = (s, label) => {
+ if (typeof s !== 'string' || !s.trim() || s.includes('*')) fail(`invalid ${label}`);
+ return s;
+ };
+ const keys = (object, allowed, label) => {
+ if (!object || typeof object !== 'object' || Array.isArray(object)) fail(`invalid ${label}`);
+ for (const key of Object.keys(object)) if (!allowed.includes(key)) fail(`unknown ${label} field ${key}`);
+ };
+ keys(options, ['root', 'expectedAssemblies', 'expectedMeshes', 'tolerance'], 'options');
+ if (!THREE?.Vector3 || !THREE?.Box3) fail('inject THREE with Vector3 and Box3');
+ const { root } = options;
+ if (!root?.isObject3D) fail('root must be an Object3D');
+ const expectedAssemblies = count(options.expectedAssemblies, 'expectedAssemblies');
+ const expectedMeshes = count(options.expectedMeshes, 'expectedMeshes');
+ const tolerance = nonnegative(options.tolerance ?? 1e-6, 'tolerance');
+ const meshes = new Map(), assemblies = new Map(), contacts = new Map();
+ const exemptions = new Map();
+ const pairKey = (a, b) => JSON.stringify([a, b].sort());
+ const ref = (map, id, label) => {
+ if (!map.has(id)) fail(`missing ${label} ${String(id)}`);
+ return map.get(id);
+ };
+ const vector = (value, label) => {
+ if (!Array.isArray(value) || value.length !== 3) fail(`${label} must be [x,y,z]`);
+ value.forEach(n => finite(n, label));
+ return new THREE.Vector3(...value);
+ };
+ const checkedBox = (box, label) => {
+ for (const axis of ['x', 'y', 'z']) {
+ finite(box.min[axis], `${label}.min.${axis}`);
+ finite(box.max[axis], `${label}.max.${axis}`);
+ if (box.min[axis] > box.max[axis]) fail(`reversed bounds for ${label}`);
+ }
+ return box;
+ };
+ const boxData = box => ({ min: box.min.toArray(), max: box.max.toArray() });
+ let sealed = false;
+ const editable = () => { if (sealed) fail('registry is sealed after evaluation'); };
+ const api = {
+ mesh(id, object) {
+ editable(); name(id, 'mesh id');
+ if (meshes.has(id)) fail(`duplicate mesh ${id}`);
+ if (!object?.isMesh) fail(`mesh ${id} must be a Mesh`);
+ if ([...meshes.values()].includes(object)) fail('mesh object registered twice');
+ meshes.set(id, object);
+ return api;
+ },
+ assembly(id, declaration) {
+ editable(); name(id, 'assembly id');
+ if (assemblies.has(id)) fail(`duplicate assembly ${id}`);
+ keys(declaration, ['meshes', 'anchors'], 'assembly');
+ const ids = declaration.meshes;
+ if (!Array.isArray(ids) || !ids.length || new Set(ids).size !== ids.length)
+ fail(`assembly ${id} needs nonempty unique mesh ids`);
+ ids.forEach(mesh => ref(meshes, mesh, 'mesh'));
+ const anchors = declaration.anchors ?? {};
+ if (!anchors || typeof anchors !== 'object' || Array.isArray(anchors)) fail('invalid anchors');
+ const copied = {};
+ for (const [anchor, spec] of Object.entries(anchors)) {
+ name(anchor, 'anchor name'); keys(spec, ['mesh', 'local'], 'anchor');
+ if (!ids.includes(spec.mesh)) fail(`anchor ${anchor} must use an owned mesh`);
+ if (typeof spec.local !== 'function') vector(spec.local, `anchor ${anchor}`);
+ copied[anchor] = { mesh: spec.mesh, local: typeof spec.local === 'function' ? spec.local : [...spec.local] };
+ }
+ assemblies.set(id, { meshes: [...ids], anchors: copied });
+ return api;
+ },
+ contact(spec) {
+ editable(); keys(spec, ['id', 'upper', 'lower', 'axis', 'tolerance', 'minOverlap'], 'contact');
+ name(spec.id, 'contact id');
+ if (contacts.has(spec.id)) fail(`duplicate contact ${spec.id}`);
+ ref(assemblies, spec.upper, 'assembly'); ref(assemblies, spec.lower, 'assembly');
+ if (spec.upper === spec.lower) fail('contact requires distinct assemblies');
+ const axis = spec.axis ?? 'y';
+ if (!['x', 'y', 'z'].includes(axis)) fail('contact axis must be x, y, or z');
+ contacts.set(spec.id, {
+ ...spec, axis, tolerance: nonnegative(spec.tolerance ?? tolerance, 'contact tolerance'),
+ minOverlap: nonnegative(spec.minOverlap ?? tolerance, 'minOverlap'),
+ });
+ return api;
+ },
+ exclude(spec) {
+ editable(); keys(spec, ['meshes', 'reason', 'maxDepth', 'active'], 'exclusion');
+ if (!Array.isArray(spec.meshes) || spec.meshes.length !== 2 || spec.meshes[0] === spec.meshes[1])
+ fail('exclusion needs exactly two distinct mesh ids');
+ spec.meshes.forEach(id => ref(meshes, id, 'mesh'));
+ name(spec.reason, 'exclusion reason');
+ const key = pairKey(...spec.meshes);
+ if (exemptions.has(key)) fail('duplicate exclusion');
+ vector(spec.maxDepth, 'exclusion maxDepth');
+ spec.maxDepth.forEach(n => nonnegative(n, 'exclusion maxDepth'));
+ if (spec.active !== undefined && typeof spec.active !== 'function') fail('active must be a function');
+ exemptions.set(key, {
+ meshes: [...spec.meshes], reason: spec.reason, maxDepth: [...spec.maxDepth], active: spec.active,
+ });
+ return api;
+ },
+ evaluate(state) {
+ if (assemblies.size !== expectedAssemblies) fail(`expected ${expectedAssemblies} assemblies, got ${assemblies.size}`);
+ if (meshes.size !== expectedMeshes) fail(`expected ${expectedMeshes} meshes, got ${meshes.size}`);
+ const owners = new Map();
+ for (const [id, assembly] of assemblies) for (const mesh of assembly.meshes) {
+ if (owners.has(mesh)) fail(`mesh ${mesh} has multiple owners`);
+ owners.set(mesh, id);
+ }
+ for (const id of meshes.keys()) if (!owners.has(id)) fail(`mesh ${id} has no assembly`);
+ const rootMeshes = new Set();
+ root.traverse(object => { if (object.isMesh) rootMeshes.add(object); });
+ for (const [id, mesh] of meshes) if (!rootMeshes.delete(mesh)) fail(`mesh ${id} is outside root`);
+ if (rootMeshes.size) fail('root contains unregistered meshes');
+ for (const exclusion of exemptions.values()) {
+ if (owners.get(exclusion.meshes[0]) === owners.get(exclusion.meshes[1]))
+ fail('exclusion must target different assemblies');
+ }
+ sealed = true;
+ root.updateWorldMatrix(true, true);
+ const meshBounds = new Map(), assemblyBounds = new Map(), anchors = {};
+ for (const [id, mesh] of meshes) {
+ if (mesh.isInstancedMesh || mesh.isSkinnedMesh || Object.keys(mesh.geometry?.morphAttributes ?? {}).length)
+ fail(`unsupported deformed mesh ${id}`);
+ mesh.matrixWorld.elements.forEach(n => finite(n, `matrix ${id}`));
+ const positions = mesh.geometry?.getAttribute('position');
+ if (!positions || positions.itemSize < 3 || !Number.isSafeInteger(positions.count) || positions.count < 1)
+ fail(`mesh ${id} needs nonempty position vertices`);
+ if (mesh.drawMode !== undefined && mesh.drawMode !== (THREE.TrianglesDrawMode ?? 0))
+ fail(`unsupported triangle draw mode ${id}`);
+ const determinant = finite(mesh.matrixWorld.determinant(), `transform determinant ${id}`);
+ if (determinant === 0) fail(`collapsed transform ${id}`);
+ const index = mesh.geometry.getIndex();
+ if (index && (index.itemSize !== 1 || !Number.isSafeInteger(index.count))) fail(`invalid index ${id}`);
+ const total = index ? index.count : positions.count;
+ const { start, count: requested } = mesh.geometry.drawRange;
+ if (!Number.isSafeInteger(start) || start < 0 || start > total) fail(`invalid drawRange start ${id}`);
+ const length = requested === Infinity ? total - start : requested;
+ if (!Number.isSafeInteger(length) || length < 3 || length % 3 || start + length > total)
+ fail(`invalid triangle drawRange count ${id}`);
+ const box = new THREE.Box3(), triangle = [];
+ let nondegenerate = false;
+ for (let cursor = start; cursor < start + length; cursor++) {
+ const i = index ? index.getX(cursor) : cursor;
+ if (!Number.isSafeInteger(i) || i < 0 || i >= positions.count) fail(`invalid vertex index ${id}`);
+ const point = new THREE.Vector3().fromBufferAttribute(positions, i);
+ point.toArray().forEach(n => finite(n, `vertex ${id}[${i}]`));
+ point.applyMatrix4(mesh.matrixWorld);
+ point.toArray().forEach(n => finite(n, `world vertex ${id}[${i}]`));
+ box.expandByPoint(point); triangle.push(point);
+ if (triangle.length === 3) {
+ const ab = triangle[1].clone().sub(triangle[0]);
+ const ac = triangle[2].clone().sub(triangle[0]);
+ const magnitude = Math.max(...ab.toArray().map(Math.abs), ...ac.toArray().map(Math.abs));
+ finite(magnitude, `triangle edges ${id}`);
+ if (magnitude > 0) {
+ const area = ab.divideScalar(magnitude).cross(ac.divideScalar(magnitude)).lengthSq();
+ if (finite(area, `triangle area ${id}`) > 0) nondegenerate = true;
+ }
+ triangle.length = 0;
+ }
+ }
+ if (!nondegenerate) fail(`no nondegenerate world triangle ${id}`);
+ meshBounds.set(id, checkedBox(box, id));
+ }
+ for (const [id, assembly] of assemblies) {
+ const box = new THREE.Box3();
+ assembly.meshes.forEach(mesh => box.union(meshBounds.get(mesh)));
+ assemblyBounds.set(id, checkedBox(box, id));
+ anchors[id] = {};
+ for (const [anchor, spec] of Object.entries(assembly.anchors)) {
+ const local = typeof spec.local === 'function' ? spec.local(state) : spec.local;
+ const point = vector(local, `anchor ${id}.${anchor}`)
+ .applyMatrix4(meshes.get(spec.mesh).matrixWorld);
+ point.toArray().forEach(n => finite(n, `world anchor ${id}.${anchor}`));
+ anchors[id][anchor] = point.toArray();
+ }
+ }
+ const errors = [], excluded = [], axes = ['x', 'y', 'z'];
+ const penetration = (a, b) => axes.map(axis =>
+ Math.min(a.max[axis], b.max[axis]) - Math.max(a.min[axis], b.min[axis]));
+ const entries = [...assemblies.entries()];
+ for (let i = 0; i < entries.length; i++) for (let j = i + 1; j < entries.length; j++) {
+ const [a, aa] = entries[i], [b, bb] = entries[j];
+ if (!penetration(assemblyBounds.get(a), assemblyBounds.get(b)).every(n => n > tolerance)) continue;
+ // Full assembly bounds are conservative: even empty-space union overlaps
+ // fail. Exact exemptions require actual intersecting owned mesh pairs.
+ let intersectingPairs = 0;
+ for (const ma of aa.meshes) for (const mb of bb.meshes) {
+ const depths = penetration(meshBounds.get(ma), meshBounds.get(mb));
+ if (!depths.every(n => n > tolerance)) continue;
+ intersectingPairs++;
+ const exemption = exemptions.get(pairKey(ma, mb));
+ const active = exemption?.active ? exemption.active(state) : true;
+ if (typeof active !== 'boolean') fail('exclusion active must return a synchronous boolean');
+ if (exemption && active && depths.every((depth, axis) => depth <= exemption.maxDepth[axis]))
+ excluded.push({ assemblies: [a, b], meshes: exemption.meshes, reason: exemption.reason,
+ maxDepth: exemption.maxDepth, depths, evidence: 'bounded AABB exemption only; not surface evidence' });
+ else errors.push({ type: 'keep-out', assemblies: [a, b], meshes: [ma, mb], depths });
+ }
+ if (!intersectingPairs) errors.push({
+ type: 'keep-out', assemblies: [a, b], meshes: [],
+ depths: penetration(assemblyBounds.get(a), assemblyBounds.get(b)),
+ evidence: 'assembly union bounds overlap; no mesh-pair exclusion applies',
+ });
+ }
+ const contactResults = [];
+ for (const spec of contacts.values()) {
+ const upper = assemblyBounds.get(spec.upper), lower = assemblyBounds.get(spec.lower);
+ const gap = upper.min[spec.axis] - lower.max[spec.axis];
+ const overlaps = axes.filter(axis => axis !== spec.axis).map(axis =>
+ Math.min(upper.max[axis], lower.max[axis]) - Math.max(upper.min[axis], lower.min[axis]));
+ const ok = Math.abs(gap) <= spec.tolerance && overlaps.every(n => n > spec.minOverlap);
+ const result = { id: spec.id, type: 'contact', ok, gap, overlaps };
+ contactResults.push(result);
+ if (!ok) errors.push(result);
+ }
+ return {
+ ok: errors.length === 0, errors, contacts: contactResults, excluded, anchors,
+ assemblyBounds: Object.fromEntries([...assemblyBounds].map(([id, box]) => [id, boxData(box)])),
+ meshBounds: Object.fromEntries([...meshBounds].map(([id, box]) => [id, boxData(box)])),
+ evidence: 'coarse world-vertex AABBs; not surface contact or solid collision certification',
+ };
+ },
+ sample(states, apply) {
+ if (!Array.isArray(states) || !states.length) fail('sample needs nonempty explicit states');
+ if (typeof apply !== 'function') fail('sample needs an apply(state, index) function');
+ const samples = states.map((state, index) => {
+ const applied = apply(state, index);
+ if (applied && typeof applied.then === 'function') fail('sample apply must be synchronous');
+ return { index, state, ...api.evaluate(state) };
+ });
+ return { ok: samples.every(sample => sample.ok), samples };
+ },
+ };
+ return api;
+}
diff --git a/templates/stroked-toon.js b/templates/stroked-toon.js
new file mode 100644
index 0000000..e1a0eda
--- /dev/null
+++ b/templates/stroked-toon.js
@@ -0,0 +1,80 @@
+// Optional stroked-toon / illustrated-miniature preset, Three.js r170.
+// Apply ONLY after the project's style-choice confirmation (see SKILL.md).
+// This replaces PixelPost; it does not supply scene geometry, lights, or UI.
+import * as THREE from 'three';
+import { OutlineEffect } from 'three/addons/effects/OutlineEffect.js';
+
+export const STROKED_TOON_DEFAULTS = Object.freeze({
+ bands: Object.freeze([68, 122, 184, 246]),
+ ink: 0x27231e,
+ thickness: 0.0032,
+ maxDpr: 2,
+ camera: Object.freeze({ fov: 26, azimuth: 38, elevation: 27.5 }),
+ // Calibrate against screenshots, not as a universal physical lighting rig.
+ lighting: Object.freeze({ key: 2.55, hemisphere: 1.55, fill: 0.72 }),
+});
+
+export function makeToonRamp(bands = STROKED_TOON_DEFAULTS.bands) {
+ if (bands.length !== 4 || !bands.every(v => Number.isInteger(v) && v >= 0 && v <= 255)) {
+ throw new Error('stroked-toon requires four byte-valued shade steps');
+ }
+ const ramp = new THREE.DataTexture(new Uint8Array(bands), 4, 1, THREE.RedFormat);
+ ramp.minFilter = ramp.magFilter = THREE.NearestFilter;
+ ramp.generateMipmaps = false;
+ ramp.needsUpdate = true;
+ return ramp;
+}
+
+export function setToonOutline(material, enabled = true, thickness = 0.0032) {
+ material.userData.outlineParameters = { visible: enabled, thickness };
+ return material;
+}
+
+export function createStrokedToon(renderer, {
+ bands = STROKED_TOON_DEFAULTS.bands,
+ ink = STROKED_TOON_DEFAULTS.ink,
+ thickness = STROKED_TOON_DEFAULTS.thickness,
+ maxDpr = STROKED_TOON_DEFAULTS.maxDpr,
+ dpr = globalThis.devicePixelRatio || 1,
+} = {}) {
+ const ramp = makeToonRamp(bands);
+ renderer.setPixelRatio(Math.min(Math.max(dpr, 1), maxDpr));
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.NoToneMapping;
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ // Requires alpha:true when creating WebGLRenderer; CSS supplies the paper.
+ renderer.setClearColor(0x000000, 0);
+ const inkColor = new THREE.Color(ink);
+ const effect = new OutlineEffect(renderer, {
+ defaultThickness: thickness,
+ defaultColor: inkColor.toArray(),
+ defaultAlpha: 1,
+ defaultKeepAlive: true,
+ });
+ const ownedMaterials = new Set();
+ function toon(color, { outline = true, stroke = thickness, ...options } = {}) {
+ const material = new THREE.MeshToonMaterial({ color, gradientMap: ramp, ...options });
+ setToonOutline(material, outline, stroke);
+ ownedMaterials.add(material);
+ return material;
+ }
+ function flat(color, options = {}) {
+ const material = new THREE.MeshBasicMaterial({ color, ...options });
+ setToonOutline(material, false);
+ ownedMaterials.add(material);
+ return material;
+ }
+ return {
+ preset: 'stroked-toon', effect, ramp, toon, flat,
+ // Use this instead of renderer.render / PixelPost.render, not after them.
+ render(scene, camera) { effect.render(scene, camera); },
+ // Re-create for a preset switch; restore previous renderer settings there.
+ // OutlineEffect r170 has no public dispose(); renderer lifetime owns its cache.
+ dispose() {
+ for (const material of ownedMaterials) material.dispose();
+ ownedMaterials.clear();
+ ramp.dispose();
+ },
+ };
+}
diff --git a/verify/action-clearance.test.mjs b/verify/action-clearance.test.mjs
new file mode 100644
index 0000000..5243489
--- /dev/null
+++ b/verify/action-clearance.test.mjs
@@ -0,0 +1,46 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { pathToFileURL } from 'node:url';
+import { createActionClearance } from '../templates/action-clearance.mjs';
+const THREE = await import(pathToFileURL(process.env.THREE_MODULE_PATH || '/Users/apple/Desktop/monstertruck/node_modules/three/build/three.module.js').href);
+const { sphere: S, capsule: C, obb: B, pairCheck: check, auditPose: pose, timesForInterval: grid, auditMotion: motion } = createActionClearance(THREE);
+const part = (id, s, owner = id) => ({ id, owner, getShape: typeof s === 'function' ? s : () => s });
+const box = B([0, 0, 0], [1, 1, 1]);
+const contact = { a: 'seat', b: 'hips', start: 0, end: 1, maxPenetration: .2, reason: 'support' };
+const support = () => [part('seat', box), part('hips', S([0, 1.05, 0], .1))];
+test('standing actor clear of building', () => assert.ok(pose({ parts: [part('actor', C([0, 0, 0], [0, 2, 0], .2)), part('building', B([4, 1, 0], [1, 2, 1]))] }).clear));
+test('walking actor sampled clear', () => { let t; assert.ok(motion({ source: { evaluate: x => t = x }, times: [0, .5, 1], parts: [part('actor', () => S([t, 0, 0], .2)), part('wall', S([5, 0, 0], .2))] }).clear); });
+test('moved arm caught', () => { let x = 3; const parts = [part('arm', () => C([x, 0, 0], [x, 1, 0], .1)), part('wall', box)]; assert.ok(pose({ parts }).clear); x = 0; assert.equal(pose({ parts }).clear, false); });
+test('animal tail caught', () => assert.equal(pose({ parts: [part('tail', C([-2, 0, 0], [2, 0, 0], .1), 'animal'), part('rock', box)] }).clear, false));
+test('bounded seat support allowed', () => assert.ok(pose({ parts: support(), contacts: [contact], time: .5 }).clear));
+test('contact does not mask knee', () => { const r = pose({ parts: [...support(), part('knee', S([0, 0, 0], .1), 'actor')], contacts: [contact] }); assert.ok(r.collisions.some(c => c.a === 'knee' || c.b === 'knee')); });
+test('contact does not mask chair back', () => assert.equal(pose({ parts: [...support(), part('back', B([0, 1, 0], [.5, 1, .5]))], contacts: [contact] }).clear, false));
+test('contact outside window forbidden', () => assert.equal(pose({ parts: support(), contacts: [contact], time: 2 }).clear, false));
+test('deep intended contact forbidden', () => assert.equal(pose({ parts: [part('seat', box), part('hips', S([0, 0, 0], .1))], contacts: [contact] }).clear, false));
+test('inside capsule retains deepest negative sdf', () => assert.ok(Math.abs(check(C([-.5, 0, 0], [.5, 0, 0], .2), box).separation + 1.2) < 1e-12));
+test('segment outside box exact distance', () => assert.ok(Math.abs(check(C([-2, 2, 2], [2, 2, 2], .2), box).separation - (Math.sqrt(2) - .2)) < 1e-12));
+test('rotated OBB', () => { const q = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 0, 1), Math.PI / 2); assert.ok(check(S([0, 1.5, 0], .1), B([0, 0, 0], [2, .2, .2], q)).separation < 0); });
+test('crossed capsules', () => assert.equal(check(C([-1, 0, 0], [1, 0, 0], .2), C([0, -1, 0], [0, 1, 0], .3)).separation, -.5));
+test('degenerate capsule is sphere', () => assert.equal(check(C([0, 0, 0], [0, 0, 0], 1), S([3, 0, 0], 1)).separation, 1));
+test('world units nonuniform extents', () => assert.ok(check(S([99, 0, 0], .1), B([0, 0, 0], [100, .01, 2])).separation < 0));
+test('touching allowed at zero margin', () => assert.ok(pose({ parts: [part('a', S([0, 0, 0], 1)), part('b', S([2, 0, 0], 1))] }).clear));
+test('positive margin flags proximity accurately', () => { const r = pose({ parts: [part('a', S([0, 0, 0], 1)), part('b', S([2.1, 0, 0], 1))], clearance: .2 }); assert.equal(r.collisions[0].kind, 'clearance-violation'); });
+test('same owner arm through body checked', () => assert.equal(pose({ parts: [part('arm', S([0, 0, 0], 1), 'actor'), part('body', S([0, 0, 0], 1), 'actor')] }).clear, false));
+test('SAT diagonal distance explicitly axis bound', () => { const r = check(box, B([3, 3, 0], [1, 1, 1])); assert.equal(r.separation, 1); assert.match(r.method, /axis-bound/); });
+test('broadphase removes separated bounds', () => assert.equal(pose({ parts: [part('a', box), part('b', B([30, 30, 0], [1, 1, 1]))] }).testedPairs, 0));
+test('endpoints pass midpoint fails', () => { let t; const options = { source: { evaluate: x => t = x }, parts: [part('actor', () => S([4 * Math.abs(t - .5), 0, 0], .2)), part('obstacle', S([0, 0, 0], .2))] }; assert.ok(motion({ ...options, times: [0, 1] }).clear); const r = motion({ ...options, times: grid(0, 1, { maxStep: .5 }) }); assert.equal(r.clear, false); assert.equal(r.worstCases[0].time, .5); assert.equal(r.sampledOnly, true); });
+test('grid endpoints exact events distinct deterministic', () => assert.deepEqual(grid(0, 1, { maxStep: .5, eventTimes: [.123, .5, .123] }), [0, .123, .5, 1]));
+test('motion evaluates exactly requested increasing times', () => { const seen = []; motion({ source: { evaluate: t => seen.push(t) }, times: [0, .123, 1], parts: [part('a', box)] }); assert.deepEqual(seen, [0, .123, 1]); });
+test('missing empty singleton duplicate and reversed motion coverage rejected before evaluation', () => { for (const times of [undefined, [], [0], [0, 0], [1, 0], [0, 1, .5], [0, NaN], [0, Infinity], new Array(2)]) { let calls = 0; assert.throws(() => motion({ source: { evaluate() { calls++; } }, times, parts: [part('a', box)] })); assert.equal(calls, 0); } });
+test('async and thenable evaluation cannot silently audit stale snapshots', () => { for (const evaluate of [async () => {}, () => ({ then() {} })]) { let snapshots = 0; assert.throws(() => motion({ source: { evaluate }, times: [0, 1], parts: [part('a', () => { snapshots++; return box; })] }), /synchronous/); assert.equal(snapshots, 0); } });
+test('empty duplicate missing unsupported NaN rejected', () => { for (const parts of [[], [part('a', box), part('a', box)], [{ id: 'a' }], [part('a', { type: 'mesh' })], [part('a', { type: 'sphere', center: [NaN, 0, 0], radius: 1 })], [part('', box)]]) assert.throws(() => pose({ parts })); });
+test('bad dimensions quaternion rejected safely normalized', () => { assert.throws(() => S([0, 0, 0], 0)); assert.throws(() => B([0, 0, 0], [1, -1, 1])); assert.throws(() => B([0, 0, 0], [1, 1, 1], [0, 0, 0, 0])); assert.equal(B([0, 0, 0], [1, 1, 1], [0, 0, 0, 1e300]).quaternion.w, 1); });
+test('missing contact proxy and malformed contacts rejected', () => { for (const rule of [{ ...contact, a: 'actor' }, { ...contact, maxPenetration: Infinity }, { ...contact, maxPenetration: -1 }, { ...contact, reason: '' }]) assert.throws(() => pose({ parts: support(), contacts: [rule] })); });
+test('hidden material unused', () => assert.equal(pose({ parts: [{ ...part('a', box), material: { visible: false }, visible: false }, part('b', S([0, 0, 0], .1))] }).clear, false));
+test('callback follows parent world positions every evaluation', () => { const parent = new THREE.Object3D(), child = new THREE.Object3D(); parent.add(child); child.position.x = 2; const parts = [part('child', () => { parent.updateMatrixWorld(true); return S(child.getWorldPosition(new THREE.Vector3()), .1); }), part('wall', box)]; assert.ok(pose({ parts }).clear); parent.position.x = -2; assert.equal(pose({ parts }).clear, false); });
+test('independent required inventory verifies exact coverage regardless order', () => { const parts = [part('actor', box), part('wall', S([5, 0, 0], 1))]; assert.equal(pose({ parts, requiredIds: ['wall', 'actor'] }).coverageVerified, true); const r = motion({ source: { evaluate() {} }, times: [0, 1], parts, requiredIds: ['actor', 'wall'] }); assert.equal(r.coverageVerified, true); assert.ok(r.samples.every(s => s.coverageVerified)); });
+test('omitted inventory explicitly reports unknown coverage in pose and motion', () => { const parts = [part('wall', box)]; assert.equal(pose({ parts }).coverageVerified, false); assert.equal(motion({ source: { evaluate() {} }, times: [0, 1], parts }).coverageVerified, false); });
+test('missing whole actor extra and duplicate expected ids reject before snapshots', () => { for (const requiredIds of [['wall', 'wholeactor'], ['other'], [], ['wall', 'wall'], [''], null, 'wall', new Array(1)]) { let calls = 0; assert.throws(() => pose({ parts: [part('wall', () => { calls++; return box; })], requiredIds })); assert.equal(calls, 0); } });
+test('unexpected extra proxy rejects before snapshots', () => { let calls = 0; assert.throws(() => pose({ parts: [part('actor', () => { calls++; return box; }), part('extra', box)], requiredIds: ['actor'] })); assert.equal(calls, 0); });
+test('canonical ids no coordinate inferred owner', () => { const r = pose({ parts: [part('z', box), part('a', box)] }); assert.deepEqual([r.collisions[0].a, r.collisions[0].b], ['a', 'z']); });
+test('invalid grid and motion fail closed', () => { assert.throws(() => grid(0, 1, { maxStep: 0 })); assert.throws(() => grid(0, 1, { maxStep: .1, eventTimes: [NaN] })); assert.throws(() => motion({ source: { evaluate() {} }, times: [], parts: [part('a', box)] })); });
diff --git a/verify/construction-kit.mjs b/verify/construction-kit.mjs
new file mode 100644
index 0000000..6c781c6
--- /dev/null
+++ b/verify/construction-kit.mjs
@@ -0,0 +1,74 @@
+import assert from 'node:assert/strict';
+import { pathToFileURL } from 'node:url';
+import { readFile } from 'node:fs/promises';
+const modulePath = process.env.THREE_MODULE;
+if (!modulePath) throw new Error('Set THREE_MODULE to an existing Three.js ESM module path or URL');
+const THREE = await import(modulePath.startsWith('/') ? pathToFileURL(modulePath).href : modulePath);
+// Load as ESM even when the surrounding workspace has no package.json type.
+const source = await readFile(new URL('../templates/construction-kit.js', import.meta.url), 'utf8');
+const { createConstructionKit } = await import(`data:text/javascript;base64,${Buffer.from(source).toString('base64')}`);
+const kit = createConstructionKit(THREE), root = new THREE.Group();
+const mat = new THREE.MeshBasicMaterial({ side: THREE.DoubleSide });
+const v = a => new THREE.Vector3(...a);
+const close = (a, b, epsilon = 1e-5) => assert.ok(Math.abs(a - b) < epsilon, `${a} != ${b}`);
+const box = kit.boxAtBase(root, mat, { size: [2, 6, 4], base: [8, 9, -3] });
+box.updateMatrixWorld(true);
+const bounds = new THREE.Box3().setFromObject(box);
+close(bounds.min.y, 9); close(bounds.max.y, 15); close(bounds.getCenter(v([0,0,0])).x, 8);
+for (const [a, b] of [[[1,2,3],[7,-5,9]], [[0,0,0],[0,-8,0]], [[-2,1,3],[4,1,3]], [[1,2,3],[1,2,9]]]) {
+ const cylinder = kit.between(root, mat, { a, b, radius: 0.3 }); cylinder.updateMatrixWorld(true);
+ const length = v(a).distanceTo(v(b));
+ assert.ok(v([0,-length/2,0]).applyMatrix4(cylinder.matrixWorld).distanceTo(v(a)) < 1e-6);
+ assert.ok(v([0,length/2,0]).applyMatrix4(cylinder.matrixWorld).distanceTo(v(b)) < 1e-6);
+ // Actual generated cap-center vertices must coincide with both endpoints.
+ const vertices = kit.collectWorldPoints(cylinder);
+ for (const endpoint of [a,b]) assert.ok(vertices.some(p => p.distanceTo(v(endpoint)) < 1e-5));
+}
+const plate = kit.plateWithHoles(root, mat, { width: 10, depth: 8, thickness: 0.75, holes: [{ x: 2, z: -1, radius: 0.7 }, { x: -2, z: 2, radius: 0.5 }], base: [11,5,17] });
+plate.updateMatrixWorld(true);
+const plateBounds = new THREE.Box3().setFromObject(plate);
+close(plateBounds.min.x, 6); close(plateBounds.max.x, 16); close(plateBounds.min.y, 5); close(plateBounds.max.y, 5.75);
+close(plateBounds.min.z, 13); close(plateBounds.max.z, 21);
+function ray(origin, direction) { return new THREE.Raycaster(v(origin), v(direction), 0, 100).intersectObject(plate); }
+for (const [x,z] of [[13,16],[9,19]]) {
+ assert.equal(ray([x,10,z],[0,-1,0]).length, 0); assert.equal(ray([x,0,z],[0,1,0]).length, 0);
+}
+close(ray([11,10,17],[0,-1,0])[0].point.y, 5.75);
+close(ray([11,0,17],[0,1,0])[0].point.y, 5);
+assert.ok(ray([13,5.4,16],[1,0,0]).length > 0, 'bore must have a real inner wall');
+for (const offset of [[0,0,0],[123,-47,89]]) for (const aspect of [0.4,2]) for (const direction of [[1,2,3],[0,1,0],[0,-1,0],[-3,0.1,1]]) for (const fov of [7,50]) {
+ const points = [[-80,-2,-4],[100,3,5],[0,6,-7],[-70,1,9]].map(p => v(p).add(v(offset)));
+ const camera = new THREE.PerspectiveCamera(fov, 1, 4, 5);
+ const pose = kit.fitPerspective(camera, { points, direction: v(direction), aspect, margin: 0.2 });
+ assert.ok(pose.distance > 0); assert.ok(pose.position.distanceTo(camera.position) < 1e-9);
+ for (const point of points) {
+ const ndc = point.clone().project(camera);
+ assert.ok(Math.abs(ndc.x) <= 0.800001 && Math.abs(ndc.y) <= 0.800001, JSON.stringify(ndc));
+ assert.ok(ndc.z > -1 && ndc.z < 1, 'near/far clipping');
+ }
+}
+const transformed = new THREE.Group(); transformed.position.set(4,5,6); transformed.rotation.set(0.2,0.8,-0.4); transformed.scale.set(2,3,4);
+const child = kit.boxAtBase(transformed, mat, { size:[1,2,3], base:[0,0,0] });
+const actual = kit.collectWorldPoints(transformed); assert.equal(actual.length, child.geometry.index.count);
+assert.ok(actual[0].distanceTo(new THREE.Vector3().fromBufferAttribute(child.geometry.attributes.position, child.geometry.index.getX(0)).applyMatrix4(child.matrixWorld)) < 1e-9);
+child.visible = false; assert.equal(kit.collectWorldPoints(transformed).length, 0); child.visible = true;
+child.geometry.morphAttributes.position = [child.geometry.attributes.position]; assert.throws(() => kit.collectWorldPoints(transformed));
+for (const invalid of [0,-1,NaN,Infinity]) {
+ assert.throws(() => kit.boxAtBase(root,mat,{size:[1,invalid,1],base:[0,0,0]}));
+ assert.throws(() => kit.between(root,mat,{a:[0,0,0],b:[1,2,3],radius:invalid}));
+}
+assert.throws(() => kit.between(root,mat,{a:[1,2,3],b:[1,2,3],radius:1}));
+assert.throws(() => kit.plateWithHoles(root,mat,{width:4,depth:4,thickness:1,base:[0,0,0],holes:[{x:2,z:0,radius:1}]}));
+const camera = new THREE.PerspectiveCamera();
+for (const patch of [{direction:v([0,0,0])},{aspect:0},{margin:0.5},{points:[]},{points:[v([NaN,0,0])]}]) assert.throws(() => kit.fitPerspective(camera,{points:[v([0,0,0])],direction:v([1,1,1]),...patch}));
+const grid = kit.gridFrames({columns:2,rows:2,spacing:[4,6],center:[10,3,20]});
+assert.equal(grid.length,4); assert.equal(new Set(grid.map(f=>f.position.toArray().join(','))).size,4);
+assert.deepEqual(grid.map(f=>f.position.toArray()),[[8,3,17],[12,3,17],[8,3,23],[12,3,23]]);
+const radial = kit.radialFrames({count:8,radius:7,center:[2,5,-3],phase:.2});
+assert.equal(radial.length,8); assert.equal(new Set(radial.map(f=>f.position.toArray().join(','))).size,8);
+for(const f of radial){close(f.position.distanceTo(v([2,5,-3])),7);const ray=v([1,0,0]).applyQuaternion(f.quaternion);assert.ok(ray.distanceTo(f.position.clone().sub(v([2,5,-3])).normalize())<1e-8);}
+assert.throws(()=>kit.gridFrames({columns:0,rows:2,spacing:[1,1],center:[0,0,0]}));
+assert.throws(()=>kit.gridFrames({columns:2,rows:2,spacing:[0,1],center:[0,0,0]}));
+assert.throws(()=>kit.radialFrames({count:1.5,radius:7,center:[0,0,0]}));
+assert.throws(()=>kit.radialFrames({count:8,radius:-1,center:[0,0,0]}));
+console.log('construction-kit: base contacts, real bores, endpoints, transformed vertices, 32 camera-fit cases, unique grid/radial frames, and invalid inputs passed');
diff --git a/verify/educational-asset-gate.test.mjs b/verify/educational-asset-gate.test.mjs
new file mode 100644
index 0000000..9d03647
--- /dev/null
+++ b/verify/educational-asset-gate.test.mjs
@@ -0,0 +1,117 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { evaluateEducationalAsset as gate } from '../templates/educational-asset-gate.mjs';
+
+function fixture(spdx = 'CC0-1.0') {
+ const official = spdx === 'CC0-1.0' ? 'https://creativecommons.org/publicdomain/zero/1.0/' : 'https://creativecommons.org/licenses/by/4.0/';
+ return {
+ sourceURL: 'https://example.org/asset', downloadURL: 'http://example.org/model.glb',
+ title: 'Recorded model', creator: 'Model creator', retrievedAt: '2026-10-31',
+ license: { spdx, url: official, evidenceURL: 'https://example.org/license-evidence', reviewed: true, costUSD: 0, commercial: true, modify: true, redistribute: true, embed: true, restrictions: [] },
+ attribution: { text: 'Recorded model — Model creator — CC BY 4.0', licenseURL: official, changes: [], retainedNotices: true },
+ files: [{ name: 'model.glb', sha256: 'a'.repeat(64), licenseReviewed: true }], dependencies: [],
+ accuracy: { referenceURL: 'https://example.org/reference', identityMatches: true, dimensionsChecked: true, unitsAndScaleChecked: true, criticalGeometryChecked: true },
+ structure: { partsMapped: true, pivotsValidated: true, interfacesValidated: true },
+ import: { tested: true, finiteGeometry: true, complete: true, styleMatched: true },
+ role: 'teaching', distribution: { dependenciesEmbedded: true },
+ };
+}
+
+for (const spdx of ['CC0-1.0', 'CC-BY-4.0']) test(`${spdx} positive recorded evidence`, () => {
+ assert.deepEqual(gate(fixture(spdx)), { status: 'accepted', rightsAllowed: true, ready: true, reasons: [] });
+});
+
+const cases = [
+ ['license official mismatch', r => r.license.url = 'https://example.org/license', 'needs-review'],
+ ['attribution official mismatch', r => r.attribution.licenseURL += '?fake=true', 'needs-review'],
+ ['NC incompatible with policy', r => r.license.spdx = 'CC-BY-NC-4.0', 'rejected'],
+ ['ND incompatible with modification', r => r.license.spdx = 'CC-BY-ND-4.0', 'rejected'],
+ ['SA manual review not inherently illegal', r => r.license.spdx = 'CC-BY-SA-4.0', 'needs-review'],
+ ['unknown license', r => r.license.spdx = 'unknown', 'needs-review'],
+ ['arbitrary custom approval string', r => r.license.spdx = 'custom-approved-commercial', 'needs-review'],
+ ['free only label', r => r.license = { spdx: 'free' }, 'needs-review'],
+ ['editorial restriction', r => r.license.spdx = 'Editorial-only', 'rejected'],
+ ['unknown cost', r => delete r.license.costUSD, 'needs-review'],
+ ['string zero not evidence', r => r.license.costUSD = '0', 'needs-review'],
+ ['paid asset', r => r.license.costUSD = 1, 'rejected'],
+ ['commercial false', r => r.license.commercial = false, 'rejected'],
+ ['modify false', r => r.license.modify = false, 'rejected'],
+ ['redistribute false', r => r.license.redistribute = false, 'rejected'],
+ ['offline embed false', r => r.license.embed = false, 'rejected'],
+ ['truthy reviewed not true', r => r.license.reviewed = 'true', 'needs-review'],
+ ['unreviewed evidence', r => r.license.reviewed = false, 'rejected'],
+ ['additional restrictive terms', r => r.license.restrictions = ['No commercial use'], 'rejected'],
+ ['omitted restrictions', r => delete r.license.restrictions, 'needs-review'],
+ ['missing attribution credit', r => r.attribution.text = ' ', 'needs-review'],
+ ['changes undeclared', r => delete r.attribution.changes, 'needs-review'],
+ ['invalid change element', r => r.attribution.changes = [false], 'needs-review'],
+ ['notices lost', r => r.attribution.retainedNotices = false, 'rejected'],
+ ['missing source', r => delete r.sourceURL, 'needs-review'],
+ ['credentialed remote download', r => r.downloadURL = 'https://user:[email protected]/model', 'needs-review'],
+ ['credentialed source', r => r.sourceURL = 'http://[email protected]/', 'needs-review'],
+ ['non HTTP URL', r => r.downloadURL = 'file:///tmp/model.glb', 'needs-review'],
+ ['blank title', r => r.title = '', 'needs-review'],
+ ['invalid calendar date', r => r.retrievedAt = '2026-02-30', 'needs-review'],
+ ['missing hash', r => delete r.files[0].sha256, 'needs-review'],
+ ['invalid hash character', r => r.files[0].sha256 = 'z'.repeat(64), 'needs-review'],
+ ['partial second file review', r => r.files.push({ name: 'texture.png', sha256: 'b'.repeat(64), licenseReviewed: false }), 'rejected'],
+ ['empty file inventory', r => r.files = [], 'needs-review'],
+ ['missing dependency declaration', r => delete r.dependencies, 'needs-review'],
+ ['external dependencies offline', r => r.distribution.dependenciesEmbedded = false, 'rejected'],
+ ['transitive licensing failure', r => { const dep = fixture(); dep.license.modify = false; const middle = fixture(); middle.dependencies = [dep]; r.dependencies = [middle]; }, 'rejected'],
+];
+for (const [name, mutate, expected] of cases) test(name, () => {
+ const record = fixture('CC-BY-4.0'); mutate(record);
+ const result = gate(record);
+ assert.equal(result.status, expected);
+ assert.equal(result.rightsAllowed, false);
+ assert.ok(result.reasons.length);
+ assert.ok(result.reasons.every(reason => reason.code && reason.path && reason.message));
+});
+
+test('flattened scan retains rights but is not teaching ready', () => {
+ const r = fixture(); r.structure = { partsMapped: false, pivotsValidated: false, interfacesValidated: false };
+ const result = gate(r);
+ assert.equal(result.rightsAllowed, true); assert.equal(result.ready, false); assert.equal(result.status, 'needs-review');
+});
+test('missing introspection cannot establish teaching structure', () => {
+ const r = fixture(); delete r.structure;
+ assert.equal(gate(r).rightsAllowed, true); assert.equal(gate(r).ready, false);
+});
+for (const role of ['exterior', 'context']) test(`${role} does not inherit mechanics`, () => {
+ const r = fixture(); r.role = role; delete r.structure; delete r.accuracy.criticalGeometryChecked;
+ assert.equal(gate(r).status, 'accepted');
+ r.accuracy.dimensionsChecked = false;
+ assert.equal(gate(r).ready, false);
+});
+for (const key of ['tested', 'finiteGeometry', 'complete', 'styleMatched']) test(`import ${key} required`, () => {
+ const r = fixture(); r.import[key] = false;
+ assert.equal(gate(r).status, 'needs-review'); assert.equal(gate(r).rightsAllowed, true);
+});
+test('online result does not imply offline license pass', () => {
+ const r = fixture(); r.license.embed = false; r.distribution.dependenciesEmbedded = false;
+ assert.equal(gate(r, { delivery: 'online' }).status, 'accepted');
+ assert.equal(gate(r).status, 'rejected');
+});
+test('CC0 permits empty credit text and explicit no modifications', () => {
+ const r = fixture(); r.attribution.text = ''; assert.equal(gate(r).status, 'accepted');
+});
+test('valid dependency records accepted without teaching readiness', () => {
+ const r = fixture(); const dep = fixture('CC-BY-4.0'); delete dep.accuracy; delete dep.structure; delete dep.import; delete dep.role;
+ r.dependencies = [dep]; assert.equal(gate(r).status, 'accepted');
+});
+test('cycles hold rather than recurse forever', () => {
+ const r = fixture(); r.dependencies = [r]; assert.equal(gate(r).status, 'needs-review');
+});
+test('invalid delivery cannot silently approve', () => assert.equal(gate(fixture(), { delivery: 'remote' }).status, 'needs-review'));
+test('invalid role cannot silently approve', () => { const r = fixture(); r.role = 'anything'; assert.equal(gate(r).status, 'needs-review'); });
+test('malformed root fails closed', () => { for (const r of [null, undefined, [], 'free']) assert.equal(gate(r).rightsAllowed, false); });
+for (const field of ['files', 'dependencies']) test(`sparse ${field} cannot hide omissions`, () => {
+ const r = fixture(); r[field] = new Array(1); assert.equal(gate(r).rightsAllowed, false);
+});
+test('sparse changes cannot hide undeclared modifications', () => {
+ const r = fixture(); r.attribution.changes = new Array(1); assert.equal(gate(r).rightsAllowed, false);
+});
+test('pure evaluation does not mutate evidence', () => {
+ const r = fixture(); const before = structuredClone(r); gate(r); assert.deepEqual(r, before);
+});
diff --git a/verify/interface-checks.mjs b/verify/interface-checks.mjs
new file mode 100644
index 0000000..f2f9277
--- /dev/null
+++ b/verify/interface-checks.mjs
@@ -0,0 +1,106 @@
+import assert from 'node:assert/strict';
+import { readFile } from 'node:fs/promises';
+import { pathToFileURL } from 'node:url';
+const source = process.env.THREE_MODULE || '/Users/apple/Desktop/monstertruck/node_modules/three/build/three.module.js';
+const THREE = await import(source.startsWith('file:') ? source : pathToFileURL(source).href);
+const helper = await readFile(new URL('../templates/interface-checks.js', import.meta.url), 'utf8');
+const { createInterfaceChecks } = await import(`data:text/javascript;base64,${Buffer.from(helper).toString('base64')}`);
+const c = createInterfaceChecks(THREE);
+let count = 0;
+function test(name, fn) { fn(); count++; console.log(`PASS ${name}`); }
+const box = (x = 2, y = 1, z = 2) => new THREE.Mesh(new THREE.BoxGeometry(x, y, z), new THREE.MeshBasicMaterial());
+const root = new THREE.Group(), frame = new THREE.Group(); root.add(frame);
+const lower = box(), upper = box(); frame.add(lower, upper); upper.position.y = 1;
+test('same seated function: baseline passes, lifted fails', () => {
+ assert.equal(c.seated(upper, lower, { frame }).pass, true);
+ upper.position.y = 1.1;
+ assert.equal(c.seated(upper, lower, { frame }).pass, false);
+ assert.ok(c.seated(upper, lower, { frame }).gap > 0);
+ upper.position.y = 1;
+});
+test('working pocket is candidate; short support is clear', () => {
+ const pocket = new THREE.Box3(new THREE.Vector3(-0.5, -0.5, -0.5), new THREE.Vector3(0.5, 0.5, 0.5));
+ assert.equal(c.outsideBox(lower, { frame, box: pocket }).status, 'candidate');
+ const short = box(0.2, 0.2, 0.2); frame.add(short); short.position.x = 1;
+ assert.equal(c.outsideBox(short, { frame, box: pocket, clearance: 0.1 }).status, 'clear');
+});
+test('nested rotated parent leaves local mating invariant', () => {
+ root.position.set(10, 3, -7); root.rotation.set(0.4, 0.6, 0.2);
+ frame.rotation.set(0.2, -0.3, 0.1); frame.position.set(2, 1, 3);
+ assert.equal(c.seated(upper, lower, { frame }).pass, true);
+ assert.throws(() => c.seated(upper, lower), /axis-aligned/);
+});
+test('hidden transparent physical geometry remains included', () => {
+ lower.visible = false; lower.material.transparent = true; lower.material.opacity = 0;
+ assert.ok(Math.abs(c.bounds(lower, { frame }).max.x - 1) < 1e-7);
+ assert.equal(c.seated(upper, lower, { frame }).pass, true);
+});
+test('indexed unused outliers ignored; nonindexed active range respected', () => {
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute([0,0,0, 1,0,0, 0,1,0, 999,999,999], 3));
+ g.setIndex([0,1,2]);
+ assert.equal(c.bounds(new THREE.Mesh(g)).max.x, 1);
+ const n = g.toNonIndexed(); n.setDrawRange(0, 3);
+ assert.equal(c.bounds(new THREE.Mesh(n)).max.y, 1);
+});
+test('missing/empty/range/malformed/NaN/deformed rejected', () => {
+ assert.throws(() => c.bounds(new THREE.Mesh(new THREE.BufferGeometry())));
+ const m = box(); m.geometry.drawRange = undefined; assert.throws(() => c.bounds(m));
+ m.geometry.drawRange = { start: 0, count: 0 }; assert.throws(() => c.bounds(m));
+ m.geometry.setDrawRange(1, 3); assert.throws(() => c.bounds(m));
+ m.geometry.setDrawRange(0, Infinity); m.geometry.attributes.position.setX(0, NaN); assert.throws(() => c.bounds(m));
+ const morph = box(); morph.geometry.morphAttributes.position = [morph.geometry.attributes.position.clone()];
+ assert.throws(() => c.bounds(morph));
+ assert.throws(() => c.bounds(new THREE.InstancedMesh(new THREE.BoxGeometry(), new THREE.MeshBasicMaterial(), 1)));
+ const bad = new THREE.BufferGeometry(); bad.setAttribute('position', new THREE.Float32BufferAttribute([0,0,0, 1,0,0, 0,1,0], 3)); bad.setIndex([0,1,12]);
+ assert.throws(() => c.bounds(new THREE.Mesh(bad)));
+});
+test('selected glazed scope detects omission/extra/duplicate', () => {
+ const glass = box(), extra = box(); glass.material.transparent = true; glass.visible = false;
+ assert.deepEqual(c.scopedMeshes({ required: [lower, glass], registered: [lower] }).missing, [glass]);
+ assert.deepEqual(c.scopedMeshes({ required: [lower], registered: [lower, extra] }).extra, [extra]);
+ assert.throws(() => c.scopedMeshes({ required: [lower], registered: [lower, lower] }));
+ assert.throws(() => c.scopedMeshes({ required: [], registered: [lower] }));
+ assert.equal(c.scopedMeshes({ required: [glass], registered: [glass] }).pass, true);
+});
+test('anchors follow transform/new geometry; detached root fails', () => {
+ const mesh = box(); root.add(mesh);
+ const local = geometry => [geometry.parameters.width / 2, 0, 0];
+ const a = c.worldAnchor({ mesh, local, root });
+ mesh.position.set(2, 3, 4); mesh.rotation.z = Math.PI / 2;
+ const b = c.worldAnchor({ mesh, local, root }); assert.ok(a.distanceTo(b) > 1);
+ mesh.geometry = new THREE.BoxGeometry(6, 1, 1);
+ const d = c.worldAnchor({ mesh, callback: local, root });
+ assert.ok(Math.abs(b.distanceTo(d) - 2) < 1e-7);
+ assert.ok(d.distanceTo(mesh.localToWorld(new THREE.Vector3(3, 0, 0))) < 1e-7);
+ root.remove(mesh); assert.throws(() => c.worldAnchor({ mesh, local, root }), /detached/);
+});
+test('projected clipping fails; valid points pass; invalid input rejected', () => {
+ const camera = new THREE.PerspectiveCamera(60, 1, 0.1, 100);
+ assert.equal(c.projectPoints([[0,0,-2], [0.1,0.1,-2]], camera, { margin: 0.1 }).pass, true);
+ for (const p of [[100,0,-2], [0,0,2], [0,0,-101], [0,0,-0.01]]) assert.equal(c.projectPoints([p], camera).pass, false);
+ assert.throws(() => c.projectPoints([], camera));
+ assert.throws(() => c.projectPoints([[NaN,0,-2]], camera));
+});
+test('same production scope rejects missing, empty, collapsed and nonfinite geometry', () => {
+ const empty = new THREE.Mesh(new THREE.BufferGeometry());
+ const collapsedGeometry = new THREE.BufferGeometry();
+ collapsedGeometry.setAttribute('position', new THREE.Float32BufferAttribute(Array(9).fill(0), 3));
+ const collapsed = new THREE.Mesh(collapsedGeometry), missing = box(), nonfinite = box();
+ missing.geometry = null; nonfinite.geometry.attributes.position.setX(0, NaN);
+ assert.equal(c.scopedMeshes({ required: [lower], registered: [lower] }).pass, true);
+ for (const broken of [missing, empty, collapsed, nonfinite])
+ assert.throws(() => c.scopedMeshes({ required: [broken], registered: [broken] }));
+ assert.throws(() => c.outsideBox(collapsed, { box: new THREE.Box3(new THREE.Vector3(-1,-1,-1), new THREE.Vector3(1,1,1)) }), /nondegenerate/);
+ root.add(empty);
+ assert.throws(() => c.worldAnchor({ mesh: empty, local: [0,0,0], root }), /geometry/);
+});
+test('singular and nonfinite camera transforms/projections rejected', () => {
+ const camera = new THREE.PerspectiveCamera(60, 1, 0.1, 100);
+ camera.scale.set(0, 1, 1); assert.throws(() => c.projectPoints([[0,0,-2]], camera), /camera/);
+ camera.scale.set(1, 1, 1); camera.projectionMatrix.makeScale(0, 1, 1);
+ assert.throws(() => c.projectPoints([[0,0,-2]], camera), /camera/);
+ camera.projectionMatrix.elements[0] = NaN;
+ assert.throws(() => c.projectPoints([[0,0,-2]], camera), /camera/);
+});
+console.log(`SUMMARY ${count} regression groups passed; AABB overlap reports candidate, never collision.`);
diff --git a/verify/pose-bounds.test.mjs b/verify/pose-bounds.test.mjs
new file mode 100644
index 0000000..859b848
--- /dev/null
+++ b/verify/pose-bounds.test.mjs
@@ -0,0 +1,20 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import {pathToFileURL} from 'node:url';
+import {createPoseBounds} from '../templates/pose-bounds.mjs';
+const T=await import(pathToFileURL(process.env.THREE_MODULE_PATH||'/Users/apple/Desktop/monstertruck/node_modules/three/build/three.module.js'));
+const q=createPoseBounds(T),near=(a,b)=>assert(Math.abs(a-b)<1e-6,`${a} != ${b}`);
+const make=()=>new T.Mesh(new T.BoxGeometry(1,1,1),new T.MeshBasicMaterial());
+test('actual transformed vertices, not copied constructor dimensions',()=>{const m=make();m.geometry.translate(3,0,0);m.position.x=4;near(q.measure(m).bounds.getCenter(new T.Vector3()).x,7);});
+test('hidden and transparent occupied geometry is retained',()=>{const m=make();m.visible=false;m.material.transparent=true;m.material.opacity=0;assert(q.measure(m).vertexCount>0);});
+test('parent translation/rotation cancels in its own local frame',()=>{const root=new T.Group(),m=make();root.add(m);root.position.set(7,4,-2);root.rotation.y=.8;const b=q.measure(m,{frame:root}).bounds;near(b.min.x,-.5);near(b.max.z,.5);});
+test('morph deformation changes live bounds despite stale geometry boundingBox',()=>{const g=new T.BoxGeometry(1,1,1),morph=g.attributes.position.clone();for(let i=0;i<morph.count;i++)morph.setX(i,morph.getX(i)+2);g.morphAttributes.position=[morph];g.computeBoundingBox();const m=new T.Mesh(g,new T.MeshBasicMaterial());m.morphTargetInfluences[0]=0;near(q.measure(m).bounds.min.x,-.5);m.morphTargetInfluences[0]=1;near(q.measure(m).bounds.min.x,1.5);assert.equal(q.measure(m).method,'cpu-morphed-active-vertices');});
+function rig(){const g=new T.BoxGeometry(1,1,1),n=g.attributes.position.count;g.setAttribute('skinIndex',new T.Uint16BufferAttribute(new Uint16Array(n*4),4));const weights=new Float32Array(n*4);for(let i=0;i<n;i++)weights[i*4]=1;g.setAttribute('skinWeight',new T.Float32BufferAttribute(weights,4));const mesh=new T.SkinnedMesh(g,new T.MeshBasicMaterial()),bone=new T.Bone();mesh.add(bone);mesh.updateMatrixWorld(true);mesh.bind(new T.Skeleton([bone]));return {mesh,bone};}
+test('actual imported-style skin follows the current bone, not bind pose',()=>{const {mesh,bone}=rig();near(q.measure(mesh).bounds.min.y,-.5);bone.position.y=2;const result=q.measure(mesh);near(result.bounds.min.y,1.5);assert.equal(result.method,'cpu-skinned-active-vertices');});
+test('skinned attached bind inverse refreshes after parent relocation',()=>{const {mesh,bone}=rig(),root=new T.Group();root.add(mesh);root.position.x=7;bone.position.x=2;near(q.measure(mesh).bounds.getCenter(new T.Vector3()).x,9);near(q.measure(mesh,{frame:root}).bounds.getCenter(new T.Vector3()).x,2);});
+test('rigid instancing requires exact instance and measures its real transform',()=>{const m=new T.InstancedMesh(new T.BoxGeometry(1,1,1),new T.MeshBasicMaterial(),2);m.setMatrixAt(0,new T.Matrix4());m.setMatrixAt(1,new T.Matrix4().makeTranslation(5,0,0));assert.throws(()=>q.measure(m),/instance/);near(q.measure(m,{instanceId:1}).bounds.min.x,4.5);assert.throws(()=>q.measure(m,{instanceId:2}),/instance/);});
+test('unreferenced geometry outliers do not inflate active indexed range',()=>{const g=new T.BufferGeometry();g.setAttribute('position',new T.Float32BufferAttribute([0,0,0,1,0,0,0,1,0,900,900,900],3));g.setIndex([0,1,2]);const r=q.measure(new T.Mesh(g,new T.MeshBasicMaterial()),{includePoints:true});near(r.bounds.max.x,1);assert.equal(r.points.length,3);});
+test('empty, collapsed and malformed ranges fail closed',()=>{const m=make();m.geometry.setDrawRange(0,0);assert.throws(()=>q.measure(m),/empty/);m.geometry.setDrawRange(1,3);assert.throws(()=>q.measure(m),/malformed/);const g=new T.BufferGeometry();g.setAttribute('position',new T.Float32BufferAttribute(new Float32Array(9),3));assert.throws(()=>q.measure(new T.Mesh(g,new T.MeshBasicMaterial())),/collapsed/);});
+test('NaN geometry and invalid transforms fail closed',()=>{const m=make();m.geometry.attributes.position.setX(0,NaN);assert.throws(()=>q.measure(m),/nonfinite/);const n=make();n.scale.x=0;assert.throws(()=>q.measure(n),/transform/);});
+test('unsupported GPU displacement is unknown/error, not excluded',()=>{const m=make();m.material=new T.ShaderMaterial();assert.throws(()=>q.measure(m),/shader/);m.material=new T.MeshStandardMaterial({displacementMap:new T.Texture()});assert.throws(()=>q.measure(m),/displacement/);});
+test('invalid index and missing skeleton fail closed',()=>{const m=make();m.geometry.index.setX(0,9999);assert.throws(()=>q.measure(m),/index/);const {mesh}=rig();mesh.skeleton=undefined;assert.throws(()=>q.measure(mesh),/skeleton/);});
diff --git a/verify/scene-contract.mjs b/verify/scene-contract.mjs
new file mode 100644
index 0000000..f4f8e33
--- /dev/null
+++ b/verify/scene-contract.mjs
@@ -0,0 +1,253 @@
+import assert from 'node:assert/strict';
+import { pathToFileURL } from 'node:url';
+import { resolve } from 'node:path';
+// Use the host project's Three installation; do not download dependencies.
+const THREE = await import(process.env.THREE_MODULE
+ ? pathToFileURL(resolve(process.env.THREE_MODULE)).href : 'three');
+import { createSceneContract } from '../templates/scene-contract.js';
+
+let passed = 0;
+function test(label, run) {
+ run(); passed++; console.log(`ok ${passed} - ${label}`);
+}
+function fixture(offset = 1) {
+ const root = new THREE.Group();
+ const floor = new THREE.Mesh(new THREE.BoxGeometry(2, 1, 2));
+ const load = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1));
+ load.position.y = offset;
+ root.add(floor, load);
+ const c = createSceneContract(THREE, { root, expectedAssemblies: 2, expectedMeshes: 2 });
+ c.mesh('floor', floor).mesh('load', load)
+ .assembly('support', { meshes: ['floor'] })
+ .assembly('payload', { meshes: ['load'], anchors: { tip: { mesh: 'load', local: [0, 0.5, 0] } } });
+ return { root, floor, load, c };
+}
+function contact(c, extra = {}) {
+ return c.contact({ id: 'rests', upper: 'payload', lower: 'support', ...extra });
+}
+
+test('valid support contact and complete ownership pass', () => {
+ const { c } = fixture();
+ const result = contact(c).evaluate();
+ assert.equal(result.ok, true);
+ assert.deepEqual(result.anchors.payload.tip, [0, 1.5, 0]);
+});
+test('overlap is detected', () => {
+ const { c } = fixture(0.75);
+ assert.equal(c.evaluate().errors[0].type, 'keep-out');
+});
+test('floating contact fails', () => {
+ const { c } = fixture(1.1);
+ assert.equal(contact(c).evaluate().contacts[0].ok, false);
+});
+test('reversed support bounds/roles cannot certify contact', () => {
+ const { c } = fixture();
+ assert.equal(contact(c, { upper: 'support', lower: 'payload' }).evaluate().ok, false);
+});
+test('missing assembly reference throws', () => {
+ const { c } = fixture();
+ assert.throws(() => contact(c, { upper: 'absent' }), /missing assembly/);
+});
+test('missing mesh reference throws', () => {
+ const { c } = fixture();
+ assert.throws(() => c.assembly('bad', { meshes: ['absent'] }), /missing mesh/);
+});
+test('NaN position vertex throws, even with cached geometry bounds', () => {
+ const { c, load } = fixture();
+ load.geometry.computeBoundingBox();
+ load.geometry.attributes.position.setX(0, NaN);
+ assert.throws(() => c.evaluate(), /vertex/);
+});
+test('moving parent and dynamic local anchors are evaluated at explicit states', () => {
+ const root = new THREE.Group(), parent = new THREE.Group();
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry());
+ root.add(parent); parent.add(mesh);
+ const c = createSceneContract(THREE, { root, expectedAssemblies: 1, expectedMeshes: 1 });
+ c.mesh('m', mesh).assembly('moving', { meshes: ['m'], anchors: {
+ tip: { mesh: 'm', local: state => [state.local, 0, 0] },
+ } });
+ const result = c.sample([{ x: 0, local: 1 }, { x: 3, local: 2 }], state => {
+ parent.position.x = state.x; parent.rotation.z = Math.PI / 2;
+ });
+ assert.equal(result.ok, true);
+ assert.ok(Math.abs(result.samples[0].anchors.moving.tip[1] - 1) < 1e-9);
+ assert.ok(Math.abs(result.samples[1].anchors.moving.tip[0] - 3) < 1e-9);
+ assert.ok(Math.abs(result.samples[1].anchors.moving.tip[1] - 2) < 1e-9);
+});
+test('off-axis rotated cylinder uses all transformed vertices', () => {
+ const root = new THREE.Group();
+ const mesh = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.6, 3, 13));
+ mesh.rotation.set(0.6, 0.2, 0.9); mesh.scale.set(1.1, 0.8, 1.2);
+ root.add(mesh);
+ const c = createSceneContract(THREE, { root, expectedAssemblies: 1, expectedMeshes: 1 });
+ c.mesh('c', mesh).assembly('cylinder', { meshes: ['c'] });
+ const actual = c.evaluate().meshBounds.c;
+ const points = Array.from({ length: mesh.geometry.attributes.position.count }, (_, i) =>
+ new THREE.Vector3().fromBufferAttribute(mesh.geometry.attributes.position, i).applyMatrix4(mesh.matrixWorld));
+ for (let axis = 0; axis < 3; axis++) {
+ assert.equal(actual.min[axis], Math.min(...points.map(p => p.getComponent(axis))));
+ assert.equal(actual.max[axis], Math.max(...points.map(p => p.getComponent(axis))));
+ }
+});
+test('inherited BoxGeometry metadata and reversed stale boundingBox are ignored', () => {
+ const { c, load } = fixture(5);
+ load.geometry.scale(4, 2, 3);
+ assert.equal(load.geometry.parameters.width, 1);
+ load.geometry.boundingBox = new THREE.Box3(new THREE.Vector3(100, 100, 100), new THREE.Vector3(-100, -100, -100));
+ const bounds = c.evaluate().meshBounds.load;
+ assert.deepEqual(bounds, { min: [-2, 4, -1.5], max: [2, 6, 1.5] });
+});
+test('negative, infinite, NaN tolerances and empty expected counts fail closed', () => {
+ for (const tolerance of [-1, NaN, Infinity, '0']) {
+ assert.throws(() => createSceneContract(THREE, {
+ root: new THREE.Group(), expectedAssemblies: 1, expectedMeshes: 1, tolerance,
+ }), /tolerance/);
+ assert.throws(() => contact(fixture().c, { tolerance }), /tolerance/);
+ }
+ assert.throws(() => createSceneContract(THREE, {
+ root: new THREE.Group(), expectedAssemblies: 0, expectedMeshes: 0,
+ }), /positive integer/);
+});
+test('expected counts and unregistered root meshes are enforced', () => {
+ const { root, c } = fixture();
+ root.add(new THREE.Mesh(new THREE.BoxGeometry()));
+ assert.throws(() => c.evaluate(), /unregistered/);
+ const incomplete = createSceneContract(THREE, { root, expectedAssemblies: 1, expectedMeshes: 1 });
+ assert.throws(() => incomplete.evaluate(), /expected/);
+});
+test('blanket, wildcard, missing and broad exemptions are invalid', () => {
+ const { c } = fixture();
+ for (const spec of [
+ { assemblies: ['payload', 'support'], reason: 'broad' },
+ { meshes: ['*', 'load'], reason: 'all' },
+ { meshes: ['floor', 'load', 'other'], reason: 'broad' },
+ { meshes: ['floor', 'load'], reason: '' },
+ ]) assert.throws(() => c.exclude(spec));
+});
+test('targeted exemption does not hide another owned mesh collision', () => {
+ const root = new THREE.Group();
+ const a = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2));
+ const b = new THREE.Mesh(new THREE.BoxGeometry());
+ const cMesh = new THREE.Mesh(new THREE.BoxGeometry());
+ root.add(a, b, cMesh);
+ const c = createSceneContract(THREE, { root, expectedAssemblies: 2, expectedMeshes: 3 });
+ c.mesh('a', a).mesh('b', b).mesh('c', cMesh)
+ .assembly('A', { meshes: ['a'] }).assembly('B', { meshes: ['b', 'c'] })
+ .exclude({ meshes: ['a', 'b'], reason: 'intentional socket', maxDepth: [1, 1, 1] });
+ const result = c.evaluate();
+ assert.equal(result.excluded.length, 1);
+ assert.equal(result.errors.length, 1);
+ assert.deepEqual(result.errors[0].meshes, ['a', 'c']);
+});
+test('animation sampling catches a collision at the provided middle state', () => {
+ const { c, load } = fixture();
+ const result = c.sample([2, 0.5, 2], y => { load.position.y = y; });
+ assert.equal(result.ok, false);
+ assert.deepEqual(result.samples.map(s => s.ok), [true, false, true]);
+ assert.throws(() => c.sample([], () => {}), /nonempty/);
+});
+test('nonfinite transforms and dynamic anchors fail closed', () => {
+ const f = fixture(); f.load.position.x = NaN;
+ assert.throws(() => f.c.evaluate(), /matrix/);
+ const root = new THREE.Group(), mesh = new THREE.Mesh(new THREE.BoxGeometry()); root.add(mesh);
+ const c = createSceneContract(THREE, { root, expectedAssemblies: 1, expectedMeshes: 1 });
+ c.mesh('m', mesh).assembly('a', { meshes: ['m'], anchors: { bad: { mesh: 'm', local: () => [NaN, 0, 0] } } });
+ assert.throws(() => c.evaluate(), /finite/);
+});
+test('full assembly union keep-out is conservative across empty interior gaps', () => {
+ const root = new THREE.Group();
+ const left = new THREE.Mesh(new THREE.BoxGeometry()); left.position.x = -2;
+ const right = new THREE.Mesh(new THREE.BoxGeometry()); right.position.x = 2;
+ const middle = new THREE.Mesh(new THREE.BoxGeometry()); root.add(left, right, middle);
+ const c = createSceneContract(THREE, { root, expectedAssemblies: 2, expectedMeshes: 3 });
+ c.mesh('left', left).mesh('right', right).mesh('middle', middle)
+ .assembly('span', { meshes: ['left', 'right'] }).assembly('middle', { meshes: ['middle'] });
+ const result = c.evaluate();
+ assert.equal(result.ok, false);
+ assert.match(result.errors[0].evidence, /union bounds/);
+});
+test('reversed computed bounds fail closed', () => {
+ class ReversedBox extends THREE.Box3 {
+ union(box) { super.union(box); [this.min.x, this.max.x] = [this.max.x, this.min.x]; return this; }
+ }
+ const root = new THREE.Group(), mesh = new THREE.Mesh(new THREE.BoxGeometry()); root.add(mesh);
+ const c = createSceneContract({ ...THREE, Box3: ReversedBox }, {
+ root, expectedAssemblies: 1, expectedMeshes: 1,
+ });
+ c.mesh('m', mesh).assembly('a', { meshes: ['m'] });
+ assert.throws(() => c.evaluate(), /reversed bounds/);
+});
+test('bounded exemptions reject oversize depth and inactive windows', () => {
+ const { c, load } = fixture(0.9);
+ c.exclude({ meshes: ['floor', 'load'], reason: 'limited contact', maxDepth: [1, 0.2, 1],
+ active: state => state.enabled });
+ assert.equal(c.evaluate({ enabled: true }).ok, true);
+ assert.equal(c.evaluate({ enabled: false }).ok, false);
+ load.position.y = 0.5;
+ assert.equal(c.evaluate({ enabled: true }).ok, false);
+});
+test('exemption budgets are required, finite, nonnegative triples', () => {
+ for (const maxDepth of [undefined, [1, 1], [-1, 0, 0], [NaN, 1, 1], [Infinity, 1, 1]]) {
+ assert.throws(() => fixture().c.exclude({ meshes: ['floor', 'load'], reason: 'test', maxDepth }));
+ }
+});
+test('morph attributes are rejected for rigid contracts', () => {
+ const { c, load } = fixture();
+ load.geometry.morphAttributes.position = [load.geometry.attributes.position.clone()];
+ assert.throws(() => c.evaluate(), /unsupported deformed/);
+});
+test('async apply and async active callbacks fail closed', () => {
+ assert.throws(() => fixture().c.sample([1], async () => {}), /synchronous/);
+ assert.throws(() => fixture().c.sample([1], () => ({ then() {} })), /synchronous/);
+ const { c } = fixture(0.9);
+ c.exclude({ meshes: ['floor', 'load'], reason: 'test', maxDepth: [1, 1, 1], active: async () => true });
+ assert.throws(() => c.evaluate(), /synchronous boolean/);
+});
+function triangleFixture() {
+ const root = new THREE.Group(), geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.Float32BufferAttribute([
+ 0, 0, 0, 1, 0, 0, 0, 1, 0, 100, 100, 100, 101, 100, 100, 100, 101, 100,
+ ], 3));
+ const mesh = new THREE.Mesh(geometry); root.add(mesh);
+ const c = createSceneContract(THREE, { root, expectedAssemblies: 1, expectedMeshes: 1 });
+ c.mesh('m', mesh).assembly('a', { meshes: ['m'] });
+ return { geometry, mesh, c };
+}
+test('unused indexed vertex outliers do not enlarge physical bounds', () => {
+ const { geometry, c } = triangleFixture(); geometry.setIndex([0, 1, 2]);
+ assert.deepEqual(c.evaluate().meshBounds.m, { min: [0, 0, 0], max: [1, 1, 0] });
+});
+test('indexed and nonindexed partial draw ranges use only active triangles', () => {
+ for (const indexed of [false, true]) {
+ const { geometry, c } = triangleFixture();
+ if (indexed) geometry.setIndex([0, 1, 2, 3, 4, 5]);
+ geometry.setDrawRange(3, 3);
+ assert.deepEqual(c.evaluate().meshBounds.m, { min: [100, 100, 100], max: [101, 101, 100] });
+ }
+});
+test('no triangles, malformed indices and invalid draw ranges fail closed', () => {
+ for (const indices of [[0], [0, 1], [0, 1, 6], [0, 0, 0], [0, 1, -1]]) {
+ const { geometry, c } = triangleFixture(); geometry.setIndex(indices);
+ assert.throws(() => c.evaluate(), /triangle|index/);
+ }
+ const fractional = triangleFixture();
+ fractional.geometry.setIndex(new THREE.BufferAttribute(new Float32Array([0, 1, 1.5]), 1));
+ assert.throws(() => fractional.c.evaluate(), /index/);
+ for (const [start, count] of [[-1, 3], [0.5, 3], [0, 0], [0, 4], [0, 9], [0, NaN]]) {
+ const { geometry, c } = triangleFixture(); geometry.setDrawRange(start, count);
+ assert.throws(() => c.evaluate(), /drawRange/);
+ }
+});
+test('collapsed geometry and zero scale cannot count as physical meshes', () => {
+ const collapsed = triangleFixture();
+ collapsed.geometry.attributes.position.array.fill(0);
+ assert.throws(() => collapsed.c.evaluate(), /nondegenerate/);
+ const scaled = fixture(); scaled.load.scale.y = 0;
+ assert.throws(() => scaled.c.evaluate(), /collapsed transform/);
+ const lone = triangleFixture();
+ lone.geometry.setAttribute('position', new THREE.Float32BufferAttribute([0, 0, 0], 3));
+ assert.throws(() => lone.c.evaluate(), /triangle/);
+ const mode = triangleFixture(); mode.mesh.drawMode = 1;
+ assert.throws(() => mode.c.evaluate(), /draw mode/);
+});
+console.log(`Passed ${passed} scene contract tests.`);
diff --git a/verify/stroked-toon/README.md b/verify/stroked-toon/README.md
new file mode 100644
index 0000000..940a651
--- /dev/null
+++ b/verify/stroked-toon/README.md
@@ -0,0 +1,71 @@
+# Optional stroked-toon verification
+
+This directory tests the optional renderer helper, not scene content or approval
+in a live conversation. Read the confirmation gate in SKILL.md before applying
+this look. Never change an existing project just to run these tests.
+
+## Automated checks
+
+With `three` r170 resolvable from this checkout:
+
+```sh
+node --test verify/stroked-toon/check.mjs verify/stroked-toon/inspection.mjs
+```
+
+If the kit itself has no node_modules, bundle check.mjs with a build project's
+esbuild and set esbuild's `nodePaths` to that project's node_modules. Run the
+resulting ESM bundle using `node --test`. Do not silently install packages or
+rewrite an unrelated scene's materials to make verification work.
+
+The four tests check:
+
+1. Four-byte RedFormat ramp, nearest sampling, invalid input rejection.
+2. Per-material contour opt-out and thickness.
+3. sRGB / NoToneMapping / PCFSoft settings, DPR cap, material cleanup.
+4. Separate contour pass, skipped cavity outlines, restored material/scene state.
+
+`inspection.mjs` adds two tests: explicit hybrid target size + nearest filtering,
+exactly two scene passes (solid + outline) followed by one upscale, render-target
+restoration even on failure; and orbit click/drag/multitouch/cancel discrimination,
+keyboard movement, no auto-spin and deterministic hero reset.
+
+3.12.0 validation: all SIX tests still pass by bundling both files using the existing
+four-stroke-engine project's Three.js/esbuild node_modules via esbuild `nodePaths`.
+No engine project files were changed. Browser/GPU and per-scene visual QA remain
+UNVERIFIED by this CPU-only suite. Motion-graphics primitives are covered
+separately by the engine project's `qa/flow-arrows.test.mjs` (eight tests: forward
+axis, depth/outline honesty, per-stroke visibility and zero leakage, a 720-degree
+vertex containment sweep against crown/bore/head/valve discs/stems/plug, an
+adjacent-degree no-teleport bound, flame kernel and crown bounds, the
+hide-instead-of-shrink rule, and the full-extent band fitter).
+
+Validated against the coffee-rig project's Three.js r170 / esbuild dependencies.
+These CPU-only tests use a fake renderer: they DO NOT establish actual WebGL
+shader compilation, performance, line appearance or visual quality. Every scene
+still needs actual browser screenshots and motion checks.
+
+## Cross-subject dry-run
+
+Use a subject unrelated to machinery, such as a forest river rescue:
+
+- Pending style answer: ask the documented question; do not apply toon yet.
+ No answer or decline means preserve current/pixel presentation.
+- Approved: authored forest greens, blue-green water and a small rescue accent;
+ fine contours on bank/roots/boat/people, no outline on water films or spray;
+ meaningful roots, tied rope, seated oarlocks and cargo, not coffee accessories.
+- Enable free user orbit by default with deterministic reset, never auto-spin. Require the
+ existing action/contact/consequence bar; the style does not replace the story.
+- Proof: desktop/phone frame, rope/hand/boat contact crop, riverbank hollow crop
+ if present, action strip. Pixel/dither assertions are explicitly replaced,
+ unrelated scene failures remain failures.
+
+## Visual reference
+
+The included coffee-rig captures calibrate contour hierarchy, bevels and detail,
+not mandatory setting, hue or scene mechanics:
+
+- ../../media/stroked-toon-reference.jpg
+- ../../media/stroked-toon-service-reference.jpg
+
+The agent must review new subject renders rather than claiming the existing
+coffee-rig captures prove the helper renders every possible scene correctly.
diff --git a/verify/stroked-toon/check.mjs b/verify/stroked-toon/check.mjs
new file mode 100644
index 0000000..6891a28
--- /dev/null
+++ b/verify/stroked-toon/check.mjs
@@ -0,0 +1,82 @@
+// Run with node --test when three is resolvable, or bundle using a project's
+// esbuild + nodePaths to its node_modules. No browser/GPU is needed here.
+// This tests configuration and material restoration, NOT visual appearance.
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import * as THREE from 'three';
+import { makeToonRamp, setToonOutline, createStrokedToon } from '../../templates/stroked-toon.js';
+
+test('four-step ramp uses nearest filtering without mipmaps', () => {
+ const t = makeToonRamp();
+ assert.deepEqual([...t.image.data], [68, 122, 184, 246]);
+ assert.equal(t.image.width, 4);
+ assert.equal(t.image.height, 1);
+ assert.equal(t.format, THREE.RedFormat);
+ assert.equal(t.minFilter, THREE.NearestFilter);
+ assert.equal(t.magFilter, THREE.NearestFilter);
+ assert.equal(t.generateMipmaps, false);
+ assert.throws(() => makeToonRamp([0, 1, 2]));
+ assert.throws(() => makeToonRamp([0, 1, 2, 256]));
+ t.dispose();
+});
+
+test('cavities and flat surfaces can opt out of contours', () => {
+ const m = new THREE.MeshToonMaterial();
+ assert.equal(setToonOutline(m, false), m);
+ assert.equal(m.userData.outlineParameters.visible, false);
+ setToonOutline(m, true, 0.0024);
+ assert.equal(m.userData.outlineParameters.thickness, 0.0024);
+ m.dispose();
+});
+
+function fakeRenderer() {
+ return {
+ shadowMap: {}, domElement: {}, autoClear: true, passes: [],
+ setPixelRatio(v) { this.dpr = v; },
+ setClearColor(c, a) { this.clearColor = c; this.clearAlpha = a; },
+ render(s) {
+ const visible = [];
+ s.traverse(o => { if (o.isMesh) visible.push(o.material.visible); });
+ this.passes.push(visible);
+ },
+ };
+}
+
+test('renderer preset caps DPR and uses a separate no-outline flat material', () => {
+ const r = fakeRenderer();
+ const look = createStrokedToon(r, { dpr: 3 });
+ assert.equal(r.dpr, 2);
+ assert.equal(r.outputColorSpace, THREE.SRGBColorSpace);
+ assert.equal(r.toneMapping, THREE.NoToneMapping);
+ assert.equal(r.shadowMap.type, THREE.PCFSoftShadowMap);
+ assert.equal(r.clearAlpha, 0);
+ const surface = look.toon(0x6688aa);
+ const inner = look.toon(0x557799, { outline: false, side: THREE.FrontSide });
+ const film = look.flat(0xabcdef, { transparent: true, opacity: 0.3 });
+ assert.equal(surface.gradientMap, look.ramp);
+ assert.equal(inner.userData.outlineParameters.visible, false);
+ assert.equal(film.userData.outlineParameters.visible, false);
+ let disposed = 0;
+ for (const x of [surface, inner, film, look.ramp]) x.addEventListener('dispose', () => disposed++);
+ look.dispose();
+ assert.equal(disposed, 4);
+});
+
+test('outline pass restores scene/material state and skips cavity outlines', () => {
+ const r = fakeRenderer();
+ const look = createStrokedToon(r);
+ const s = new THREE.Scene();
+ const camera = new THREE.PerspectiveCamera();
+ const outer = new THREE.Mesh(new THREE.BoxGeometry(), look.toon(0x6688aa));
+ const inner = new THREE.Mesh(new THREE.BoxGeometry(), look.toon(0x557799, { outline: false }));
+ s.add(outer, inner);
+ const material = outer.material;
+ look.render(s, camera);
+ assert.equal(r.passes.length, 2);
+ assert.deepEqual(r.passes[1], [true, false]);
+ assert.equal(outer.material, material);
+ assert.equal(r.autoClear, true);
+ assert.equal(r.shadowMap.enabled, true);
+ assert.equal(s.matrixWorldAutoUpdate, true);
+ outer.geometry.dispose(); inner.geometry.dispose(); look.dispose();
+});
diff --git a/verify/stroked-toon/inspection.mjs b/verify/stroked-toon/inspection.mjs
new file mode 100644
index 0000000..84d5ed2
--- /dev/null
+++ b/verify/stroked-toon/inspection.mjs
@@ -0,0 +1,53 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import * as THREE from 'three';
+import { createPixelStroke } from '../../templates/pixel-stroke.js';
+import { createDioramaOrbit } from '../../templates/orbit.js';
+
+test('hybrid low-resolution nearest target, single outline path and restore', () => {
+ const previous = {}; let active = previous; const passes = [];
+ const renderer = { shadowMap: {}, domElement: {}, autoClear: true,
+ setPixelRatio(v) { this.dpr = v; }, setClearColor() {}, clear() {},
+ getRenderTarget() { return active; }, setRenderTarget(t) { active = t; },
+ render(scene) { passes.push(active); },
+ };
+ const look = createPixelStroke(renderer, { width: 320, height: 180 });
+ assert.equal(look.target.width, 320); assert.equal(look.target.height, 180);
+ assert.equal(look.target.texture.magFilter, THREE.NearestFilter);
+ assert.equal(renderer.dpr, 1);
+ const scene = new THREE.Scene(); scene.add(new THREE.Mesh(new THREE.BoxGeometry(), look.toon(0xabcdef)));
+ look.render(scene, new THREE.PerspectiveCamera());
+ assert.deepEqual(passes, [look.target, look.target, previous]);
+ assert.equal(active, previous);
+ assert.throws(() => look.setSize(0, 1)); look.setSize(160, 90);
+ assert.equal(look.target.width, 160);
+ renderer.render = () => { throw new Error('GPU failure'); };
+ assert.throws(() => look.render(scene, new THREE.PerspectiveCamera()));
+ assert.equal(active, previous); look.dispose();
+});
+
+function canvasStub() {
+ const listeners = new Map(), attributes = new Map();
+ return { style: {}, clientWidth: 800, clientHeight: 600,
+ getRootNode() { return { addEventListener() {}, removeEventListener() {} }; },
+ addEventListener(name, fn, capture) { if (capture) listeners.set(name, fn); },
+ removeEventListener() {}, getAttribute(k) { return attributes.get(k) ?? null; },
+ removeAttribute(k) { attributes.delete(k); }, setPointerCapture() {}, releasePointerCapture() {},
+ fire(name, data) { listeners.get(name)?.({ pointerId: 1, clientX: 10, clientY: 10, button: 0, ...data }); },
+ };
+}
+test('orbit separates click, drag, multi-touch and cancellation; deterministic reset', () => {
+ const camera = new THREE.PerspectiveCamera(); camera.position.set(4, 3, 5);
+ const canvas = canvasStub(); let selected = 0;
+ const orbit = createDioramaOrbit(camera, canvas, { onSelect() { selected++; } });
+ assert.equal(orbit.controls.autoRotate, false); assert.equal(orbit.controls.enablePan, false);
+ canvas.fire('pointerdown'); canvas.fire('pointerup'); assert.equal(selected, 1);
+ canvas.fire('pointerdown'); canvas.fire('pointermove', { clientX: 40 }); canvas.fire('pointerup'); assert.equal(selected, 1);
+ canvas.fire('pointerdown'); canvas.fire('pointerdown', { pointerId: 2 });
+ canvas.fire('pointerup', { pointerId: 2 }); canvas.fire('pointerup'); assert.equal(selected, 1);
+ canvas.fire('pointerdown'); canvas.fire('pointercancel'); canvas.fire('pointerup'); assert.equal(selected, 1);
+ canvas.fire('keydown', { target: canvas, key: 'ArrowLeft', preventDefault() {} });
+ assert.notDeepEqual(camera.position.toArray(), [4, 3, 5]);
+ orbit.reset(); assert.deepEqual(camera.position.toArray().map(n => +n.toFixed(8)), [4, 3, 5]);
+ orbit.dispose();
+});