Skip to content

Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.

1.5.2: animation pipeline (#117)

Hoài Nhớd6815db757c1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fc43033..b4fd0e9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,119 @@ All notable changes to **img2threejs** are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+**Theme: rigging may only ADD.** The 1.5.2 modules existed and nothing ever ran them; animation
+broke meshes because no step in the workflow forbade it and no gate could tell a rigged mesh from a
+damaged one. This closes the loop between the gates and the pipeline that is supposed to enforce them.
+
+### Added
+
+- **`animated-character` workflow profile** (`forge/_shared/workflow_state.py` `RIG_STEPS`,
+ `forge/state.py`). Nine Stage R steps join the checklist: read the contract, read the rig from the
+ GLB, repair the mesh, freeze it, validate the payload, bind, verify parity, measure the clips, run
+ the gates. Every `forge/stage5_rig/` module was callable before this and nothing in the workflow
+ ever told anyone to call one — `next.py` walks the checklist, so a gate absent from the checklist
+ never runs, and a gate that never runs reports a clean verdict forever.
+- The Stage R order is enforced by `forge/tests/test_rig_workflow_steps.py`, not by convention.
+ Repair precedes the freeze; the freeze precedes every rig step; parity is verified after the bind.
+ Moving the freeze later would let a bind rewrite vertices and then certify the rewritten buffer,
+ so the manifest would attest to the damage instead of catching it.
+- **`forge/stage5_rig/mesh_parity.py`** — freeze the geometry, then prove it survived. Hashes are
+ taken over packed bytes rather than JSON text, so a formatter changing its mind is not a reported
+ change while a changed number cannot be formatted into a collision. `position`, `normal`, `uv` and
+ `index` are frozen; `skinIndex` and `skinWeight` are deliberately not, because adding them is the
+ entire legal purpose of rigging — freezing them would fail every successful rig and the gate would
+ be switched off within a day. A single nudged float is caught and located to the mesh, the
+ attribute, the element and both values.
+- **`forge/stage5_rig/glb_rig_reference.py`** — read the skeleton, the skin's joint ordering, the
+ inverse bind matrices and the clips FROM the GLB, and sample its own animation channels into the
+ payload `clip_features` consumes. Joint correspondence to a procedural skeleton is matched by
+ measured position, never by name, and reports `usable: false` when any joint on either side is
+ unmatched. A GLB's channels target its node indices and its `skinIndex` values address its joint
+ array; fed to a procedurally authored skeleton they index a different rig entirely.
+- **`runtime/scripts/export_mesh_buffers.mjs`** — raw geometry buffers, no `matrixWorld`.
+ `export_mesh_geometry.mjs` emits world space, which is correct for self-intersection and wrong for
+ parity in both directions: posing changes `matrixWorld` without touching a byte of the buffer, and
+ a real buffer edit cancelled by a compensating transform would read as unchanged.
+- **`docs/GLB_ANIMATED_CHARACTER_PROMPT.md`** — one copy-paste prompt carrying a subject from a GLB
+ to a rigged, animated, gate-cleared character in a single pass.
+
+### Fixed
+
+- `forge/stage5_rig/emit_rig.py` constructed `THREE.Skeleton` before `updateMatrixWorld`, so
+ `calculateInverses()` captured identity matrices, the rest pose never cancelled, and every vertex
+ sat displaced by its bone's offset. That failure compiles, binds, reports `bound: true` and
+ renders a corpse. The main factory emitter already ordered this correctly; only the Milestone-0
+ emitter did not.
+- `forge/stage3_build/generate_threejs_factory.py` now refuses to bake a geometry twice.
+ `applyMatrix4` mutates in place and is not idempotent, so a second pass applies the world matrix
+ squared and scatters the parts. It throws rather than skipping, because a silent skip would leave
+ a mesh in the wrong space and resurface later as a subtler misplacement.
+
+### Changed
+
+- `docs/pipelines/character-rigging-animation-1.5.2.md` §R0.1 carried a claim that did not
+ reproduce. It cited the Lee Sin rig for "clips target technical nodes that are not joints";
+ re-measured on that asset, **all 1,353 channels across all 11 clips target deform joints and zero
+ target technical nodes.** The rule stands — it is what keeps the skin's index space intact — but
+ it is now stated as the risk it guards against rather than as an observation, and
+ `deformVsTechnical` reports the real count per asset.
+
+## [1.5.2] — 2026-08-25
+
+**Theme: a clip that exists is not a clip that plays.** Rigging failures in 1.5.1 were not "the
+animation looks slightly wrong" — they were total and silent: eleven clips held actions, the mixer
+held state, buttons dispatched, nothing moved. Two separate bugs each produced a plausible scene
+with zero motion, and neither was visible in code review. This release turns the pipeline distilled
+from that build into executable modules and gates.
+
+### Added
+
+**The animation pipeline — `forge/stage5_rig/`**
+- `clip_features.py`: the §1 measurement vocabulary (duration, travel, rise, speed, handRange,
+ footRange, headRise, scaleDelta, poseReturn) sampled at N = 25, the §2 classifier, §3 naming with
+ the `inferred` honesty flag, and the §4 loop rule. `scaleDelta` is a tripwire, not a descriptor:
+ a non-zero value means the source rig scales joints, which changes what R2 may legally do to skin
+ weights, and it is surfaced before anything else proceeds.
+- **The loop rule is corrected, and the old one is pinned as a regression test.** 1.5.1 used "a clip
+ that neither travels nor rises can repeat seamlessly", which contradicted its own data —
+ `idle-gesture` travels 0.121H, six times the idle threshold, and is correctly loopable. Loop is
+ now `poseReturn ≤ 0.5°` **and** `‖hip(T) − hip(0)‖ ≤ 0.01H`. A host that cannot measure
+ `poseReturn` gets `loop = None`, never a defaulted `false` — "measured, does not loop" and
+ "nobody looked" are different answers.
+- `skin_conditioning.py`: proximity weight blending for characters built from overlapping parts.
+ Dense accumulation before mixing, buffered writes so the result is order-independent, a uniform
+ grid hash at one cell per radius (≤ 27 buckets per query), and interior vertices left
+ bit-identical. Coincidence-welding is kept as an executed negative result: it closes one crack and
+ leaves 28 frames cracked, because adjacent parts overlap rather than share a rim.
+- The R2 trade is stated wherever it runs rather than buried: blending closes holes (974 px in 30
+ blobs → 287 px in 15) and makes creases ~16% worse (31,316 px → 36,470 px). A hole shows the
+ background, a crease shows skin. A later stage must not "fix" the crease count by disabling it.
+- `action_design.py`: §R4 target bands, topology-driven chain resolution (arms, legs and spine
+ resolved without reading a single joint name), the medial/lateral gate that catches a mirrored
+ rig, gait as a phase machine with real stance/swing intervals, and `foot_slide` — the gate that
+ catches a gait reading as "floaty" or "skating" while being hard to name by eye.
+- `rig_gates.py`: the G1–G10 runner. **A gate whose input is absent reports `unevaluated`, never a
+ pass**, and any unevaluated gate makes the whole report not-ok.
+- `emit_animation_runtime.py`: emits the R1/R5 runtime as TypeScript — identity bind in attached
+ mode, display offset from mesh bounds alone, `refreshTickers()` for lazily-built characters, the
+ explode-offset order around the tick loop, and the controller contract. A clip whose loop was
+ never measured emits `LoopOnce` with a comment saying so, never a silent `LoopRepeat`.
+- `docs/pipelines/character-rigging-animation-1.5.2.md` (the derivation and the failure log),
+ `forge/stage5_rig/CONTRACT_1.5.2.md` (module map and payload shape) and
+ `grimoire/readiness/animation_contract.md` (the routing file read at Stage R).
+
+### Fixed
+
+- **§R4's limb bands were unsatisfiable as written, and the implementation proved it.** §1 defines
+ `handRange`/`footRange` as world-space ranges; under that definition a forward-travelling gait
+ gives `footRange ≈ travel` and `handRange ≈ travel + swing`, so no speed lands in the stated
+ `0.15H–0.25H` / `≈ travel/2` bands. The limb bands are hip-relative and now say so; the global
+ features stay world-space, the only frame the §2 classifier is meaningful in.
+- `footRange ≈ travel / 2` compared two different quantities: `travel / 2` is the step length
+ between alternating footfalls, `footRange` is a positional range. The `≈` is read as ±30%.
+
## [1.5.1] — 2026-08-22
### Added
diff --git a/README.md b/README.md
index d299067..ea4e446 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@
Quality-gated, animation-ready, and deliberately token-efficient — reconstruction-by-code, not photogrammetry, mesh extraction, or downloaded art packs.
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
-[![Version](https://img.shields.io/badge/version-1.5.1-green.svg)](CHANGELOG.md)
+[![Version](https://img.shields.io/badge/version-1.5.2-green.svg)](CHANGELOG.md)
[![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](CONTRIBUTING.md)
[![Runtime](https://img.shields.io/badge/runtime-Three.js-000000.svg)](https://threejs.org)
[![Tooling](https://img.shields.io/badge/tooling-Python%203.10%2B%20stdlib-3776ab.svg)](forge)
diff --git a/ROADMAP.md b/ROADMAP.md
index 226e93d..d9afa6c 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -17,6 +17,7 @@ can plan around.
| v1.3 | Quality & efficiency (Divine Eye) | 2026-07-22 | Deterministic multi-signal review harness, input-integrity and geometry-truth gates, reference-grounded texture/material analysis, CIEDE2000 colour math |
| v1.4 | Weapon Pipeline | 2026-07-25–26 | CS2 image-matched reconstruction, provenance-aware intake and local search, projection-first finishes, family-specific adapters, structural review and component-coverage gates |
| v1.5 | The Character Update | 2026-08-12 | Skeleton derived from the component tree and bound to `SkinnedMesh` geometry, geodesic skinning, hair as a five-stage subsystem with a hard scalp-exposure gate, chirality gates, interior-difference review, `tapered-sweep`, material pipeline with a blocking acceptance gate, resumable workflow state |
+| v1.5.2 | Character rigging & animation | 2026-08-25 | Clip measurement vocabulary and classifier, corrected loop rule (poseReturn, not travel), proximity weight blending, topology-driven chain resolution, foot-contact gate, and the G1-G10 gate suite where an unmeasured gate reports `unevaluated` rather than a pass |
### v1.2 — Humanoid character generator
diff --git a/SKILL.md b/SKILL.md
index 55aa909..42f5366 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -2,7 +2,7 @@
name: img2threejs
description: Turn an object or character reference image into a quality-gated, animation-ready procedural Three.js model built in code. Use for image-to-3D reconstruction, detail-accurate object rebuilds, stylized/likeness-maximized human characters, sculpt specs, and staged code generation.
license: Apache-2.0
-version: 1.5.1
+version: 1.5.2
---
# img2threejs — Image to procedural Three.js
@@ -58,7 +58,7 @@ Conversation context is disposable; `.img2threejs/state.json` is the local check
Initialize once per reconstruction, then gate every step through it:
```bash
-python3 forge/state.py init --state .img2threejs/state.json --reference <img> --profile <generic|cs2|character> --spec object-sculpt-spec.json
+python3 forge/state.py init --state .img2threejs/state.json --reference <img> --profile <generic|cs2|character|animated-character> --spec object-sculpt-spec.json
python3 forge/next.py --state .img2threejs/state.json [object-sculpt-spec.json]
python3 forge/state.py mark <step-id> --state .img2threejs/state.json --evidence <path>
```
@@ -71,7 +71,11 @@ python3 forge/state.py mark <step-id> --state .img2threejs/state.json --evidence
(`refine-spec`/`refine-code`), not agent memory. Defaults: 3 corrections per pass, 6 total.
- Profiles add mandatory gates without changing the core order: `cs2` requires classification,
manifest, and a machine-readable CS2 review before AI review; `character` requires the character
- contracts and landmark evidence. Every profile records suitability, projection applicability, and
+ contracts and landmark evidence; `animated-character` adds all of `character` plus the nine Stage R
+ steps (`grimoire/readiness/animation_contract.md`). Pick it whenever the rig must MOVE — on
+ `character` the Stage R gates are absent and the build completes without ever running them, which
+ is how animation used to ship broken. Its order is load-bearing: repair the mesh, freeze it, bind
+ additively, then verify parity. Every profile records suitability, projection applicability, and
material-evidence applicability. The state file is a resumability index, not visual evidence:
renders, specs, review history, and deterministic gates remain the authoritative artifacts.
@@ -285,6 +289,11 @@ attachment, material, detail inventory, rig payload, character track). In short:
passes a straight cone occupying roughly the right cells.
- Character builds validate the rig payload (`stage5_rig/validate_rig_payload.py`) before binding a
`THREE.Skeleton`; it proves payload integrity only, never pose stress or likeness.
+- A rig that must MOVE runs the animation gates too (`grimoire/readiness/animation_contract.md`,
+ `stage5_rig/rig_gates.py`). A clip that exists is not a clip that plays: only G1
+ (`maxSampledBindingDelta <= 2^-23`) separates the two, and a gate whose input is missing reports
+ `unevaluated`, never a pass. Bind at IDENTITY in attached mode and take the display offset from
+ the mesh bounds alone; loop is decided by `poseReturn`, never by travel.
- CS2 builds also run `cs2_review.py` against the versioned scene fixture.
- Local state enforces 3 corrections per pass and 6 total by default; reaching either limit is a
hard stop. `correction_loop.py` may stop earlier on repeated defects, oscillation, or plateau.
diff --git a/docs/GLB_ANIMATED_CHARACTER_PROMPT.md b/docs/GLB_ANIMATED_CHARACTER_PROMPT.md
new file mode 100644
index 0000000..814c3ed
--- /dev/null
+++ b/docs/GLB_ANIMATED_CHARACTER_PROMPT.md
@@ -0,0 +1,224 @@
+# GLB animated-character prompt
+
+One copy-paste prompt that carries a subject from a GLB reference to a **rigged, animated,
+gate-cleared** procedural Three.js character, for img2threejs 1.5.2 and later.
+
+It is the animated sibling of [`prompts/build.md`](standard-prompts/build.md). That one stops
+at a static reconstruction; this one continues through Stage R — rigging, animation, and the G1–G10
+gates — under one rule the static route never needed:
+
+> **Repair the mesh before you freeze it. After the freeze, rigging may only ADD.**
+
+## Why this prompt exists
+
+Animation used to break meshes, and the reason was structural rather than accidental.
+
+1. **The gates were unreachable.** Every module under `forge/stage5_rig/` was callable and nothing
+ in the workflow ever told anyone to call one. `next.py` walks the checklist, so a gate absent
+ from the checklist never runs — and a gate that never runs reports a clean verdict forever. The
+ `animated-character` profile puts Stage R on the checklist, so the gates are now unskippable
+ rather than merely available.
+2. **The rig was authored beside the GLB instead of read from it.** A GLB carries a real skin and
+ real clips; its animation channels target ITS node indices and its `skinIndex` values address
+ ITS joint array. Feeding either into a procedurally authored skeleton indexes a different
+ skeleton entirely, which shreds the mesh. Hence: read the rig FROM the GLB, and where a
+ procedural skeleton must coexist, build an explicit measured correspondence rather than assuming
+ the indices line up.
+3. **Nothing proved the mesh survived.** `validate_rig_payload.py` proves structural payload
+ integrity only — by its own scope note, never pose stress or likeness. A green payload was being
+ read as "animation is safe". `mesh_parity.py` closes that: hash the geometry before rigging,
+ re-hash after, and a single changed float names the mesh, the attribute and the vertex.
+
+Two distinct symptoms have two distinct causes, and it is worth knowing which one you are looking
+at before hunting:
+
+| What you see | What it is |
+|---|---|
+| Nothing moves; the scene renders fine | Binding never reaches the node, or inverse binds cancel the wrong pose — **G1** |
+| Parts fly apart / the figure is shredded | Geometry rewritten during rigging, or joint indices addressing a different skeleton — **mesh parity** and **correspondence** |
+
+## How to use it
+
+1. Replace every `<PLACEHOLDER>`.
+2. Paste the whole thing as one prompt. It is written to complete in a single pass.
+3. A hard stop is the prompt working. Answer the question it asks rather than telling it to continue.
+
+## The prompt
+
+````text
+Build a rigged, animated procedural Three.js character from a GLB reference using img2threejs 1.5.2.
+
+## Inputs
+- GLB reference: <ABSOLUTE_PATH_TO_GLB>
+- Reference photo (optional): <PATH_OR_NONE>
+- Subject name: <SubjectName>
+- Demo id: <subject-id>
+- Showcase root: <PATH_TO_img2threejs-showcase>
+- Real longest dimension: <e.g. 1.70 m> # sanity-checks scale; never used to scale
+
+## Hard contract — do not violate these
+
+1. **The GLB is a measurement instrument, never an asset.** Symlink it into `public/mesh/`
+ (gitignored). No `.glb`/`.bin` may be fetched by the running demo. Its topology and textures are
+ measured, never copied into the factory.
+2. **Rigging and animation are REFERENCED FROM THE GLB.** Skeleton, skin joint order, inverse bind
+ matrices and clips come from `forge/stage5_rig/glb_rig_reference.py`, not from invention. The
+ skin's joint ordering is the authority — never traversal order, never node names.
+3. **Repair before the freeze; after the freeze, only ADD.** If meshes are broken, fix them in the
+ `mesh-repair` step and say what you fixed. Then freeze. From that moment vertex positions,
+ normals, uvs and indices are evidence: rigging may add `skeleton`, `skinIndex` and `skinWeight`
+ and nothing else. `mesh_parity.py verify` must pass. If it fails, the rigging is wrong — never
+ re-freeze to make it pass.
+4. **State gate on every step.** `python3 forge/next.py --state .img2threejs/state.json` at start,
+ at resume, and before every correction. Exit 3 / `status=stopped` is a hard stop: report and ask,
+ never continue from memory.
+5. **Never label a node from its name.** Baseline assets name nodes `root.0..root.N` and rigs name
+ joints `node_17`. Labels come from measured world-space bounds; joint correspondence comes from
+ measured position. Treat every label as `hypothesis-requires-render-confirmation`.
+6. **An unevaluated gate is not a pass.** If a gate's input is missing, produce the input or report
+ the gate as unevaluated with the reason. Never record a gate as green because it did not run.
+7. **Never claim "done" when it is "improved."** Name what still does not match.
+
+## Procedure
+
+### Stage 0 — Intake, on the animated profile
+```
+python3 forge/state.py init --state .img2threejs/state.json --reference <glb> \
+ --profile animated-character --spec object-sculpt-spec.json
+python3 forge/stage1_intake/probe_glb.py <glb> --out glb-probe.json
+python3 forge/stage1_intake/label_glb_nodes.py <glb> --out nodes.json --min-confidence 0.6
+```
+`--profile animated-character` is what puts Stage R on the checklist. On `character` the rig gates
+are absent and the build will complete without ever running them.
+
+Read `glb-probe.json` for `skinCount` and `animationCount` before anything else. `skinCount > 1`
+means you must choose a skin explicitly and say why. `animationCount: 0` means Stage R4 authoring,
+not R3 identification — a different route with different gates.
+
+### Stages 1–3 — Reconstruction
+Follow `docs/standard-prompts/build.md` for the geometry route (cross-section loft, implicit surface
+only where the loft cannot reach, TypeScript encoding, `verify_cells.mjs` before any encode). None
+of it changes here. Come back when the static model renders and its gates are green.
+
+### Stage R — rigging and animation
+
+Read `grimoire/readiness/animation_contract.md` and
+`docs/pipelines/character-rigging-animation-1.5.2.md` completely first. Both are short and every
+rule in them traces to a measured failure.
+
+**R-1. Read the rig from the GLB.**
+```
+python3 forge/stage5_rig/glb_rig_reference.py <glb> --out glb-rig.json
+```
+Report `deformVsTechnical`: clips routinely target technical nodes that are not joints, and
+building those as bones corrupts the skeleton's index space. If a procedural skeleton must coexist
+with the GLB's, build the correspondence and read `usable` — an unmatched joint on either side
+means it is not usable for retargeting, and inventing the mapping is what shreds a mesh.
+
+**R-2. Repair, then freeze.**
+Inspect the meshes and repair what is broken NOW. Then:
+```
+node runtime/scripts/export_mesh_buffers.mjs --url <preview> --out meshes.json
+python3 forge/stage5_rig/mesh_parity.py freeze meshes.json --out mesh-manifest.json
+```
+Everything after this point is measured against that manifest.
+
+**R-3. Bind — additively.**
+```
+python3 forge/stage5_rig/validate_rig_payload.py <spec>
+```
+Then bind. Three rules, each of which produced a real failure:
+- `mesh.bind(skeleton, new THREE.Matrix4())` — identity, always, in attached bind mode. Attached
+ mode recomputes `bindMatrixInverse` from `matrixWorld` every frame, so `matrixWorld` cancels out
+ entirely. Binding with the armature's matrix rendered a blank frame; adding the armature
+ translation to the display offset moved the figure by exactly that translation.
+- The display offset comes from the **mesh bounds alone**: `(−centre.x, −min.y, −centre.z)`.
+- `updateMatrixWorld(true)` BEFORE `new THREE.Skeleton(...)`. `calculateInverses()` reads each
+ bone's current world matrix; constructed first it captures identity, the rest pose never cancels,
+ and every vertex is displaced by its bone's offset. That failure compiles, binds, reports
+ `bound: true`, and renders a corpse.
+
+**R-4. Prove the mesh survived.**
+```
+node runtime/scripts/export_mesh_buffers.mjs --url <preview> --out meshes-after.json
+python3 forge/stage5_rig/mesh_parity.py verify mesh-manifest.json meshes-after.json
+```
+`skinIndex`/`skinWeight` appearing is expected and reported as legally added. A changed position,
+normal, uv or index is a failure naming the mesh and the first differing vertex.
+
+Use `export_mesh_buffers.mjs`, not `export_mesh_geometry.mjs`. The latter multiplies every vertex by
+`matrixWorld` — correct for self-intersection, wrong here in both directions: posing changes
+`matrixWorld` without touching the buffer, so a correctly rigged mesh would report as changed; and a
+real buffer edit cancelled by a compensating transform would report as unchanged.
+
+**R-5. Measure the clips; never name them by guess.**
+```
+python3 forge/stage5_rig/glb_rig_reference.py <glb> --sample-clips --landmarks landmarks.json \
+ --out sampled-clips.json
+python3 forge/stage5_rig/clip_features.py sampled-clips.json
+```
+Source clips arrive as `NlaTrack.001` and carry no information. Rename from measurement and record
+which measurement the name rests on. A name that describes motion is provable; a name that implies
+intent is not — no kinematic feature distinguishes a strike from a stumble, so that carries
+`inferred: true`. Loop comes from `poseReturn`, never from travel: a clip that wanders and returns
+loops, and one that ends mid-stride a centimetre away does not.
+
+`scaleDelta ≠ 0` is a tripwire, not a descriptor. Surface it before anything else proceeds.
+
+**R-6. Gates.**
+```
+python3 forge/stage5_rig/rig_gates.py rig-gate-payload.json
+```
+G1 is the one that catches silent death: seek each clip to five times and compare each node's actual
+transform against `track.createInterpolant().evaluate(t)`, requiring `maxSampledBindingDelta ≤ 2⁻²³`.
+It is the only check that distinguishes a clip that plays from one that exists, loads, holds an
+action, reports a duration and drives nothing. Under-coverage is a failure, not a pass: a harness
+that sampled one clip once is not evidence.
+
+G10 is visual and needs a real sweep. Five poses is not coverage — the sweep that found the actual
+defects was 11 clips × 4 times × 2 sides × 2 azimuths = 176 frames. Report holes and creases as two
+numbers; a single combined score hides the fact that Stage R2 trades one against the other.
+
+### Stage 8 — Prove nothing is fetched, then look at it
+Move the binary directory aside, rebuild, re-render. Renders that still appear are the proof.
+```
+npx tsc --noEmit && npx vite build
+```
+Then actually watch the animation, at 0°, 40° and a grazing angle. Metrics hide structural failure.
+If the render and the metric disagree, the render is right.
+
+## Report format
+Per stage: what was **measured** (the number and the command that printed it), what was **decided**
+from it, what remains **unverified**. Close with:
+- every gate and its status, with `unevaluated` listed as unevaluated and never as a pass;
+- the mesh-parity verdict, and what was repaired before the freeze;
+- which clips were named by measurement and which carry `inferred: true`;
+- per-region confidence, and what still does not match the reference.
+
+"This rig cannot be animated from this reference without breaking the mesh" is a valid result. Say
+it rather than shipping a shredded figure.
+````
+
+## Where each rule comes from
+
+| Rule in the prompt | What it prevents |
+|---|---|
+| `--profile animated-character` | Stage R gates existed but nothing invoked them; a gate that never runs reports clean forever |
+| Rig read from the GLB | GLB clips target GLB node indices; fed to a procedural skeleton they index a different rig and shred the mesh |
+| Correspondence by measured position | Joint names are `node_17`; a name-matched correspondence is confidently wrong |
+| Repair before freeze | Freezing a broken mesh certifies the breakage instead of catching it |
+| Freeze before bind | Binding first leaves nothing to compare against |
+| Parity verified after bind | Binding is the only moment "implementation did not touch the mesh" can be falsified |
+| Identity bind in attached mode | Binding with `armature.matrixWorld` rendered a blank frame; a `skinSpace` wrapper gave a half-height floating figure |
+| `updateMatrixWorld` before `Skeleton` | Inverse binds capture identity, the rest pose never cancels, and it renders a corpse while reporting `bound: true` |
+| Loop from `poseReturn` | The travel-based rule contradicted its own data: `idle-gesture` travels 0.121H and loops correctly |
+| G1 coverage counts | A harness reporting a tiny delta over one clip at one time is not evidence |
+| 176-frame sweep | Five poses missed defects that a real sweep found in 28 frames |
+
+## Related
+
+- [`docs/pipelines/character-rigging-animation-1.5.2.md`](pipelines/character-rigging-animation-1.5.2.md) — the derivation and the failure log.
+- [`grimoire/readiness/animation_contract.md`](../grimoire/readiness/animation_contract.md) — the routing file read at Stage R.
+- [`forge/stage5_rig/CONTRACT_1.5.2.md`](../forge/stage5_rig/CONTRACT_1.5.2.md) — module map and payload shapes.
+- [`docs/standard-prompts/build.md`](standard-prompts/build.md) — the static reconstruction route this one continues.
+- [`docs/standard-prompts/glb-force-measured.md`](standard-prompts/glb-force-measured.md) — when every parameter the GLB measures should be forced rather than approximated.
diff --git a/docs/STAGE_R_BACKLOG.md b/docs/STAGE_R_BACKLOG.md
new file mode 100644
index 0000000..38693c9
--- /dev/null
+++ b/docs/STAGE_R_BACKLOG.md
@@ -0,0 +1,412 @@
+# Stage R backlog — what is missing, in the order it should be closed
+
+Distilled from building the 1.5.2 rigging and animation pipeline. Every claim here was verified by
+running something, not by reading; where a claim could not be verified it says so.
+
+Companion documents: `STAGE_R_TEST_PLAN.md` (how to test), `GLB_ANIMATED_CHARACTER_PROMPT.md` (how to
+run), `pipelines/character-rigging-animation-1.5.2.md` (why each rule exists).
+
+---
+
+## Part 1 — The principles this work produced
+
+These govern everything below. Each one cost real time to learn.
+
+### A gate nothing invokes reports a clean verdict forever
+
+Every `forge/stage5_rig/` module was callable and nothing in the workflow ever told anyone to call
+one. `next.py` walks the checklist, so a gate absent from the checklist never runs — and a build
+completes green having checked nothing.
+
+**This was then reproduced while fixing it.** Nine rig steps were added to the checklist and
+`next_entry()` was never taught to dispatch scope `"rig"`; the steps sat pending forever while the
+build reported `complete`. Sixteen tests passed because they asserted the *contents* of the list.
+
+> **Presence in a list is not reachability. Assert the behaviour, not the data structure.**
+> Mutation-check it: break the dispatch on purpose and confirm a test goes red.
+
+### `unevaluated` is not `pass`
+
+A check whose input is absent must say so and must make the report not-ok. Four gates are in that
+state today, which is why `rig_gates.py` cannot return green yet. That is the system being honest,
+and the moment it is softened to "assume pass when unmeasured" the whole suite becomes decorative.
+
+### Two symptoms, two causes — decide which one you are looking at
+
+| What you see | Mechanism |
+|---|---|
+| Nothing moves; scene renders fine | Binding never reaches the node, or inverse binds cancel the wrong pose |
+| Parts fly apart; figure shredded | Geometry rewritten during rigging, or joint indices addressing a different skeleton |
+
+The 1.5.1 build had **both**, and each produced a plausible-looking scene.
+
+### State the frame, always
+
+Mesh parity must read the **raw local buffers**. The existing exporter emits world space — correct
+for self-intersection, wrong here in both directions: posing changes `matrixWorld` without touching
+a byte (false positive), and a buffer edit cancelled by a compensating transform reads as unchanged
+(false negative).
+
+The same class of error was found in the spec itself: §R4's `handRange`/`footRange` bands are
+unsatisfiable in world space for a travelling gait, because the limbs go where the body goes. They
+are hip-relative; the global features stay world-space.
+
+### Measure before recommending
+
+A guard was added against a double world-bake and then recommended for retention on the grounds that
+"there is no evidence sharing is legitimate" — without going to look. Investigation afterwards found
+**61 meshes, 61 distinct geometry variables, zero sharing, impossible by construction**. The
+recommendation was right by accident and the reasoning was wrong.
+
+> **"I found no evidence against it" is not evidence for it. Go and measure.**
+
+### Claims are not measurements — including other people's
+
+`kimodo`'s reported metrics all **exclude** its post-processing stage "to ensure a fair comparison
+between methods", so the correction module's benefit is asserted and never measured. Read other
+projects' numbers for what they actually measured.
+
+---
+
+## Part 2 — The backlog
+
+Priority reflects what unblocks the next honest answer, not what is cheapest.
+
+### V — Verification (highest value: nothing below is grounded until these are done)
+
+Everything built so far is machinery to catch a bug **nobody has seen**. The three mesh-damage
+mechanisms were inferred by reading code. Building more gates before observing the failure repeats
+that mistake at higher cost.
+
+---
+
+**V-1 · Reproduce the mesh damage on a real character**
+
+*Why* — "fixed" is currently unfalsifiable. No render has ever been produced by this work.
+
+*Done when* — a dated recording exists of a real demo (`warrior`, `girl-character` or
+`low-poly-humanoid`) showing the failure at three angles (0°, 40°, grazing), plus a frozen
+`baseline-broken.json` manifest of its geometry, and the symptom is classified as *corpse* or
+*shredded* per the table above.
+
+*Cost* — ~1h. Blocked by nothing. CloakBrowser is installed and all three demos carry a rig.
+
+---
+
+**V-2 · Run one character end to end through `animated-character`**
+
+*Why* — the decisive test of the whole pipeline. Three outcomes, all valuable: the gate catches it
+(machinery works), the gate misses it (names the missing gate — the most valuable result), or nothing
+breaks (the bug is elsewhere; stop guessing).
+
+*Done when* — the run reaches `rig-gates` with a `mesh_parity verify` verdict recorded, and Phase 4
+of the test plan is answered in writing.
+
+*Cost* — ~half a day. Depends on V-1 for a baseline. `rig-payload-validate` will need skipping with
+`--reason` until **P-2** lands; that is expected, not a blocker.
+
+---
+
+### P — Producers (four gates can never pass without them)
+
+**P-1 · CLI for `emit_animation_runtime.py` → unblocks G1**
+
+*Why* — G1 is the only check that distinguishes a clip that plays from one that exists, loads, holds
+an action, reports a duration and drives nothing. The `runGateR1()` harness that produces
+`bindingSamples` is **already written inside the emitter**; nothing exposes it to a shell. Cheapest
+possible path to the most important gate.
+
+*Done when* — `python3 forge/stage5_rig/emit_animation_runtime.py <clips.json> --out runtime.ts`
+works, the emitted harness runs in a browser and writes a `bindingSamples` block that `rig_gates.py`
+accepts, and G1 reports `pass` or `fail` — never `unevaluated` — on a real rig.
+
+*Cost* — small. 6 of 8 stage5 modules already have a `__main__`; this follows the same idiom.
+
+---
+
+**P-2 · Converter producing `rig-payload.json`**
+
+*Why* — the `rig-payload-validate` step calls `validate_rig_payload.py --payload rig-payload.json`
+and **nothing writes that file**. `new_sculpt_spec.py:derive_character_rig` produces a differently
+shaped `spec["rig"]`. Verified: the filename appears only in `workflow_state.py`.
+
+*Done when* — a converter turns a sculpt spec's `rig` block into the payload schema the validator
+reads, the Stage R step runs without `--reason`, and a round-trip test proves the two schemas agree
+field for field.
+
+*Cost* — small-to-medium. Needs both schemas read side by side; the mismatch may be substantive
+rather than cosmetic.
+
+---
+
+**P-3 · Producers for G3 (`bindRestore`) and G6 (`meshVisibility`)**
+
+*Why* — verified: **zero files** produce either key outside the gate and its tests. G3 catches pose
+bleed between clips; G6 catches a part left behind in bind pose.
+
+*Done when* — both keys are emitted by a browser harness in the shape `rig_gates.py` parses, and
+both gates report a real verdict on a real rig.
+
+*Cost* — medium. Same harness shape as `export_mesh_buffers.mjs`; reuse its CloakBrowser scaffolding.
+
+---
+
+**P-4 · G10 skin-integrity sweep harness**
+
+*Why* — the visual gate, and the most expensive. Five poses is not coverage: the sweep that found the
+real defects was 11 clips × 4 times × 2 sides × 2 azimuths = **176 frames**. Must report holes and
+creases as **two** numbers, because Stage R2 trades one against the other and a combined score hides
+it. Also needs a **measured blend-off baseline** — an absent baseline leaves G10 `unevaluated` rather
+than borrowing someone else's threshold.
+
+*Done when* — the sweep runs, both numbers are reported, and a control run with blending disabled
+supplies the baseline.
+
+*Cost* — large. Do last, and only if V-2 shows tearing that the cheaper gates miss.
+
+---
+
+### H — Hardening and plumbing
+
+**H-1 · Decide `runtime/` tracking**
+
+*Why* — `runtime/` is gitignored with **zero files tracked**, so `export_mesh_buffers.mjs` (the
+producer for G4/G5/G11) does not ship. This is pre-existing, not new: `export_mesh_geometry.mjs`,
+which `SKILL.md` instructs agents to run, is equally absent from the repository.
+
+*Done when* — either `runtime/scripts/` is un-ignored and both scripts are tracked, or the docs stop
+referencing scripts a clean checkout does not contain. **A user decision, not an implementation one.**
+
+*Cost* — trivial once decided.
+
+---
+
+**H-2 · Give Stage R its own correction budget**
+
+*Why* — verified: loop caps are global (`maxPerPass`, `maxTotal`; `perPass` keyed by build pass).
+Corrections spent in the pass loop can hard-stop a run before any rig step executes, and Stage R
+inherits a budget that may already be exhausted.
+
+*Done when* — Stage R carries its own allowance, and a test proves a run that exhausted the pass
+budget can still reach `rig-gates`.
+
+*Cost* — small.
+
+---
+
+**H-3 · `mesh-repair` and `rig-bind` produce verifiable artifacts**
+
+*Why* — both are prose steps with no script. `rig-bind` is the step that actually creates the
+skeleton; its only downstream check is `mesh-parity-verify`, which proves the buffers were untouched
+— **not that the bind is correct**.
+
+*Done when* — each emits an artifact a gate can read: for `mesh-repair`, what was repaired and the
+before/after measurement; for `rig-bind`, enough to confirm identity bind, bounds-derived display
+offset, and `updateMatrixWorld` ordering.
+
+*Cost* — medium.
+
+---
+
+**H-4 · Put the orphaned gates on the checklist**
+
+*Why* — verified: `turntable_gate`, `self_intersection`, `attachment_anchor`, `interior_difference`,
+`scalp_exposure`, `divine_eye`, `vlm_gate` and `correction_loop` are all mandated by `SKILL.md` and
+**none has a checklist step id**, so `next.py` never asks for them. Same defect class as Stage R
+before it was wired.
+
+*Done when* — each has a step id in the appropriate scope, and a dispatch test (not a contents test)
+proves `next_entry()` reaches it.
+
+*Cost* — medium. Do it in one pass and reuse `test_rig_workflow_steps.py`'s dispatch-test shape.
+
+---
+
+**H-5 · `ARCHITECTURE.md` covers all of `stage5_rig/`**
+
+*Why* — verified: it lists **4 of 12** files. Anyone reading it to build a driver misses the entire
+1.5.2 stack.
+
+*Cost* — trivial.
+
+---
+
+**H-6 · Second subject for the `single-subject` thresholds**
+
+*Why* — the blend radius `R = 0.006H` and every §2 classifier boundary come from **one rig**. The
+walk/run gap (0.400 → 0.799 H/s) and run/dash gap (0.799 → 2.250) are both wide, but wide on one
+subject only.
+
+*Done when* — the gaps are confirmed to survive on a second rig, or the thresholds are re-derived.
+Until then they stay documented as starting values, never constants.
+
+*Cost* — medium, and gated on having a second rigged asset.
+
+---
+
+**H-7 · Rebase the GLB fast lane onto 1.5.2**
+
+*Why* — verified: the fastlane worktree is `version: 1.5.1` and its `stage5_rig/` holds only the four
+pre-1.5.2 files. The two branches are **mutually exclusive**; `--profile glb` and
+`--profile animated-character` cannot currently be combined.
+
+*Done when* — one branch offers both profiles and the combined suite is green.
+
+*Cost* — medium. **Do not start before V-2** — merging two branches before knowing whether one of
+them is correct doubles the surface to debug.
+
+---
+
+### K — From `kimodo` (NVIDIA Toronto AI Lab)
+
+Researched because it was suggested as a rigging reference. **It is not** — it is a kinematic motion
+diffusion model over a hardcoded skeleton that never touches a mesh: no skeleton derivation, no
+skinning weights, one trained model per skeleton. It is orthogonal to both of our hard problems.
+
+Three ideas are worth taking, all implementable in stdlib with no checkpoint, no PyTorch and no
+NVIDIA Open Model License dependency.
+
+---
+
+**K-1 · `retarget_tag` — semantic role tags instead of position matching**
+
+*Why* — kimodo stamps each joint with an anatomical role (`LeftHand`, `RightFoot`, …) and **asserts
+exactly one joint matches each tag**, failing otherwise. Our `correspondence()` currently matches by
+measured position, which is better than names but still fuzzy. Because our generator **authors** the
+skeleton, it can stamp the tag at emit time — correspondence becomes a join, not an inference. The
+exactly-one assertion is a free structural gate.
+
+*Done when* — emitted skeletons carry `retargetTag`, `correspondence()` prefers a tag join and falls
+back to position, and the exactly-one assertion is a gate.
+
+*Cost* — small. **But do it after V-2** — correspondence has not yet been shown to be a cause of any
+observed damage.
+
+---
+
+**K-2 · Foot contact as an emitted channel**
+
+*Why* — kimodo ships `foot_contacts [T,4]` alongside the motion rather than re-deriving it
+downstream. A parallel contact track on our clips makes foot-lock trivial in JS and makes the
+contact claim checkable instead of implicit.
+
+*Cost* — small.
+
+---
+
+**K-3 · Two-detector contact-consistency gate**
+
+*Why* — compare **declared** contacts against an **independent geometric detector**. Catches
+"animation looks fine but the contact metadata lies" — a class our current `footSlide` gate cannot
+see. Computable from joint positions alone: pure stdlib, no new dependency.
+
+*Liftable constants, quoted from kimodo*: `contact_threshold = 0.5`, `vel_thresh = 0.15 m/s` and
+`height_thresh = 0.10 m` for the consistency detector; `vel_thresh = 0.2 m/s` and
+`height_thresh = 0.05 m` for foot-skate; `above_ground_offset = 0.007`; `root_margin = 0.04`.
+These are **their** measurements on **their** skeletons — treat as starting values and re-derive,
+exactly as with our own `single-subject` numbers.
+
+*Cost* — small-to-medium.
+
+---
+
+**Explicitly not adopted from kimodo:** the checkpoint (282M params, ~17GB VRAM, PyTorch +
+LLM2Vec, weights under NVIDIA Open Model License — the Apache 2.0 covers **code only**); the
+MotionCorrection C++ library (needs a C++17 toolchain, undocumented algorithm, **benefit never
+measured**); one-model-per-skeleton (incompatible with a per-image skeleton); BVH as interchange
+(SOMA-only, reintroduces an opaque asset plus a metres→cm scale trap).
+
+---
+
+### S — Seam continuity under animation
+
+The requirement that meshes stay **continuous while animating** is currently listed under *what this
+pipeline does not solve*, and the gate that would measure it has no producer. These three close that.
+
+Full design: `PLAN_1.6_ANIMATION_STAGE.md` §3.
+
+---
+
+**S-1 · Shared-boundary welding with a unified weight zone**
+
+*Why* — proximity blending is a **mitigation, not a fix**, and says so: holes fell 974 px/30 blobs →
+287 px/15 blobs while creases rose 16% (31,316 → 36,470 px). Its own residual note states the
+complete fix is *"one continuous mesh with a unified weight field, which changes the part structure
+and breaks per-part UI"* — and per-part UI is a shipping gate.
+
+The third path was already **declared** in the showcase IR and never built:
+`topologyBridge: "shared-boundary"` + `deformationBridge: "shared-weight-zone"`. `validateContinuity()`
+only checks the constraint objects are well-formed; it never touches geometry. A declaration with
+nothing implementing or verifying it — the same defect class as a gate nothing invokes.
+
+*Done when* — vertices on a welded seam share **one bit-identical binding**, so no pose can separate
+them; parts remain separately addressable so explode/click still passes `check_part_coverage.py`; and
+the 176-frame sweep reports **zero background pixels** through every welded seam.
+
+*Cost* — large. Touches topology. **Do not start before V-1** measures the real gap first.
+
+---
+
+**S-2 · G10 producer — promoted from P-4**
+
+*Why* — without it S-1 is unverifiable, and the current hole/crease numbers are inherited from an
+earlier build rather than measured on today's code. Originally ranked last on cost; the continuity
+requirement makes it essential rather than a luxury.
+
+*Done when* — as P-4, plus a re-measured baseline for the current pipeline.
+
+---
+
+**S-3 · A `rig` group in the correction loop**
+
+*Why* — verified: `correction_loop.py` mentions `rig`, `skin` and `weight` **zero times**. Its groups
+are camera → silhouette → face → clothing → accessory → materials → lighting. Visual feedback can
+therefore never drive a rig or weighting fix, only a material or lighting one.
+
+*Done when* — a `rig` correction group exists, and a defect visible only under animation routes to it.
+
+*Cost* — medium.
+
+---
+
+## Part 3 — Suggested order
+
+```
+V-1 reproduce the damage ← start here; everything else is speculation until this
+V-2 run one character end to end
+ │
+ ├── the run names what actually matters, then:
+ │
+P-1 G1 producer ← cheapest gate with the highest value
+P-2 rig-payload converter ← removes the one hard stop in Stage R
+H-1 runtime/ decision ← trivial, user's call, unblocks shipping the producer
+H-2 Stage R correction budget
+H-5 ARCHITECTURE.md
+ │
+S-2 G10 producer ← was P-4; the continuity requirement makes it essential
+K-1 retarget_tag ← the standardisation Stage 6 clips are authored against
+ │
+S-1 shared-boundary welding ← the seam fix; needs S-2 to be verifiable at all
+ │
+P-3 G3 + G6 producers
+S-3 rig group in the correction loop
+H-3 mesh-repair / rig-bind artifacts
+H-4 orphaned gates onto the checklist
+K-2 contact channel
+K-3 contact-consistency gate
+H-6 second subject
+H-7 fastlane rebase ← last: do not merge branches before one is known correct
+```
+
+`P-4` is superseded by `S-2`, which is the same harness at a higher priority.
+
+## Standing rules for every task above
+
+1. **Write the falsifying test first.** A test that asserts the data structure instead of the
+ behaviour will pass while the feature is dead.
+2. **Mutation-check the test.** Break the thing on purpose; if nothing goes red, the test is
+ decorative.
+3. **A new gate ships with its producer**, or it ships reporting `unevaluated` and says so.
+4. **State the frame and the units.** Local or world; absolute or a fraction of figure height H.
+5. **Mark every threshold that came from one subject** `single-subject`, including borrowed ones.
+6. **Never claim "done" when it is "improved."** Name what still does not match.
diff --git a/docs/STAGE_R_TEST_PLAN.md b/docs/STAGE_R_TEST_PLAN.md
new file mode 100644
index 0000000..68881b9
--- /dev/null
+++ b/docs/STAGE_R_TEST_PLAN.md
@@ -0,0 +1,331 @@
+# Stage R test plan — does the animation pipeline still break meshes?
+
+A runbook for img2threejs 1.5.2, written to **falsify** the fix rather than confirm it.
+
+**Status of what it tests:** the Stage R modules are unit-tested (1343 tests, `OK (skipped=30)`) and
+several were exercised on real data — `glb_rig_reference.py` on a real GLB, `mesh_parity` through a
+live browser round-trip. But **the pipeline has never been run end-to-end on a real character, and
+nothing has been rendered.** The three mesh-damage mechanisms behind this work were inferred by
+reading code, not by reproducing the failure.
+
+That is why Phase 0 exists, and why it is not optional.
+
+---
+
+## The one rule
+
+> **Phase 0 is the phase that makes every other phase mean something.**
+
+Nobody has yet seen the broken mesh, and nobody has seen it fixed. If you skip to Phase 3 and
+everything passes, that result is unfalsifiable — a green run proves the gates agree with each
+other, not that your mesh stopped tearing. Capture the damage first.
+
+---
+
+## How to read a result
+
+| Status | Meaning |
+|---|---|
+| `pass` | The check ran, on real data, and the value was inside tolerance. |
+| `fail` | The check ran and the value was outside tolerance. A real defect, or a real change in the input. |
+| `unevaluated` | **Nothing measured it. This is not a pass.** It makes the whole report not-ok by design. |
+
+---
+
+## Before you start — four gates have no producer
+
+`rig_gates.py` **will report not-ok on any run today.** That is the system telling the truth, not a
+test failure. Judge the run on the other eight gates plus the mesh-parity verdict.
+
+| Gate | Catches | Input producer |
+|---|---|---|
+| `G1` | clips that play silently | **none yet** — needs `runGateR1()` exposed via a CLI |
+| `G2` | bad indices, NaN weights | host harness |
+| `G3` | pose bleed between clips | **none yet** |
+| `G4` `G5` | weight sums, index range | `export_mesh_buffers.mjs` |
+| `G6` | a part left in bind pose | **none yet** |
+| `G7` | mirrored rig | computed in Python |
+| `G8` `G9` | skating gait, joint scale | `glb_rig_reference.py --sample-clips` |
+| `G10` | tearing under motion | **none yet** — needs a 176-frame sweep |
+| `G11` | **rigging that rewrites geometry** | `export_mesh_buffers.mjs` |
+| `G12` | clips addressing a different skeleton | `glb_rig_reference.py` |
+
+Set `I=~/Documents/personal/img2threejs` and run everything from that directory. **Keep every JSON
+and every recording** — the artifacts are the result, not the terminal output.
+
+---
+
+## Phase 0 — Reproduce the damage
+
+**~30 min. The phase everyone skips. Do not skip it.**
+
+**Goal:** a saved, dated record of a mesh actually breaking. Without it, "fixed" cannot be tested,
+only asserted.
+
+### 0.1 — Name the broken subject
+
+Pick the demo where you saw the tearing. Write down which one, and what you saw.
+
+> **Two opposite symptoms, two different causes.** "Nothing moves" is a binding failure (`G1`:
+> the clip exists, holds an action, reports a duration, and drives nothing). "Parts fly apart" is
+> geometry being rewritten (`G11`). If you saw both, say so — the 1.5.1 build had two separate bugs
+> and each produced a plausible-looking scene.
+
+### 0.2 — Capture it on video, at three angles
+
+Play the clip that breaks it. Record front, 40°, and a grazing angle.
+
+Metrics hide structural failure: a surface can score 2.49 mm median accuracy and still read as a
+lumpy, hole-riddled shell. **If the render and the metric disagree, the render is right.**
+
+### 0.3 — Freeze the broken geometry as evidence
+
+```bash
+node $I/runtime/scripts/export_mesh_buffers.mjs \
+ --url <preview-url> --out baseline-broken.json
+
+python3 $I/forge/stage5_rig/mesh_parity.py freeze baseline-broken.json \
+ --out baseline-manifest.json
+```
+
+**Keep:** `baseline-broken.json`, `baseline-manifest.json`, the three recordings. This is the
+"before" that everything else is measured against.
+
+---
+
+## Phase 1 — Smoke the modules alone
+
+**~10 min. No browser. Catches wiring errors before they cost you an hour.**
+
+**Goal:** prove each module runs on real input *in your environment*. All of these were run during
+development; re-running them proves your checkout matches.
+
+### 1.1 — The suite
+
+```bash
+cd $I && python3 -m unittest discover -s forge/tests -p 'test_*.py'
+```
+
+- **Expect:** `Ran 1343 tests` · `OK (skipped=30)`
+- **If not:** stop. Something in the checkout differs from what was verified. Report the failure
+ names before going further.
+
+### 1.2 — The honesty rule, on an empty payload
+
+```bash
+echo '{"figureHeight":1.0}' > empty.json
+python3 $I/forge/stage5_rig/rig_gates.py empty.json; echo "exit=$?"
+```
+
+- **Expect:** 12 gates, every one `unevaluated`, `ok: false`, `exit=1`.
+- No gate may say `pass` — nothing was measured.
+
+### 1.3 — Read a real rig out of a real GLB
+
+```bash
+python3 $I/forge/stage5_rig/glb_rig_reference.py \
+ ~/Documents/personal/img2threejs-showcase/public/mesh/tripo.glb \
+ --out glb-rig.json
+```
+
+- **Expect:** `skinCount: 1`, `clipCount: 11`, 42 joints, and `joints[0]` pointing at
+ `nodeIndex 40` — **not** 0. That gap is the whole point: the ordering is the skin's, never the
+ traversal's.
+- **Check `deformVsTechnical.channelsTargetingTechnicalNodes`.** On this asset it is 0. A non-zero
+ number on *your* asset means clips drive nodes that are not joints — read it before binding
+ anything, because building those as bones corrupts the skeleton's index space.
+
+### 1.4 — The mesh-parity gate, all three outcomes
+
+This is the gate that answers the original complaint. Prove it can say yes **and** prove it can say
+no — a gate that only ever passes is worthless.
+
+```bash
+# a: unchanged → pass
+python3 $I/forge/stage5_rig/mesh_parity.py verify m.json before.json; echo "exit=$?"
+
+# b: skinIndex/skinWeight added by rigging → must ALSO pass
+python3 $I/forge/stage5_rig/mesh_parity.py verify m.json after-rig.json; echo "exit=$?"
+
+# c: one vertex nudged by hand → must fail, and say where
+python3 $I/forge/stage5_rig/mesh_parity.py verify m.json damaged.json; echo "exit=$?"
+```
+
+- **Expect:** a → `exit=0` · b → `exit=0` with skin attributes listed as *added (legal)* ·
+ c → `exit=1` naming the mesh, the attribute and the first differing element.
+- **If b fails:** that is a design bug, not a data problem. The gate would fail every successful rig
+ and be switched off within a day. Report it immediately.
+
+---
+
+## Phase 2 — Does the workflow actually drive to Stage R?
+
+**~5 min. This exact wiring was broken once and shipped green.**
+
+**Goal:** confirm `next.py` asks for the rig steps. The first version of this work put nine steps on
+the checklist that no dispatcher ever returned — the build reported `complete` with all nine still
+`pending`, and the tests passed because they asserted the *list* rather than the *behaviour*.
+
+### 2.1 — Initialise on the animated profile
+
+```bash
+python3 $I/forge/state.py init --state .img2threejs/state.json \
+ --reference <your>.glb --profile animated-character \
+ --spec object-sculpt-spec.json
+```
+
+- **Expect:** 32 checklist steps, 9 of them scope `rig`.
+- On `--profile character` you get 0 rig steps and the gates never run. That is the difference the
+ profile makes, and picking the wrong one is how animation used to ship broken.
+
+### 2.2 — Walk it
+
+```bash
+python3 $I/forge/next.py --state .img2threejs/state.json
+```
+
+- **Expect:** the nine rig steps appear in `pending`. Once the static build finishes, `currentStep`
+ becomes `rig-contract-read` and status stays `active`.
+- **Red flag:** if status goes `complete` while any rig step is `pending`, the dispatch regression is
+ back. This is the single most important thing this phase looks for.
+
+---
+
+## Phase 3 — Run the real character through
+
+**The long one. Order is load-bearing.**
+
+**Goal:** take the Phase 0 subject through the full flow. Follow `next.py` at every step; a hard stop
+(exit 3) is the system working — answer it rather than pushing past it.
+
+Use `docs/GLB_ANIMATED_CHARACTER_PROMPT.md` as the driver. The order below cannot be rearranged:
+**repair before freeze, freeze before bind, verify after bind.**
+
+### 3.1 — Repair, then freeze
+
+Fix whatever is broken in the mesh **now**, and write down what you fixed. Then freeze. Freezing a
+broken mesh certifies the breakage instead of catching it.
+
+```bash
+node $I/runtime/scripts/export_mesh_buffers.mjs \
+ --url <preview> --out meshes.json
+
+python3 $I/forge/stage5_rig/mesh_parity.py freeze meshes.json \
+ --out mesh-manifest.json
+```
+
+> Use `export_mesh_buffers.mjs`, **not** `export_mesh_geometry.mjs`. The latter multiplies every
+> vertex by `matrixWorld` — correct for self-intersection, wrong here in both directions: posing
+> changes `matrixWorld` without touching the buffer (false positive), and a real buffer edit
+> cancelled by a compensating transform reads as unchanged (false negative).
+
+### 3.2 — Bind, additively only
+
+Rigging may add `skeleton`, `skinIndex` and `skinWeight`. Positions, normals, uvs and indices are
+evidence from here on. Three rules, each of which caused a real failure:
+
+- `mesh.bind(skeleton, new THREE.Matrix4())` — identity, always, in attached bind mode. Attached
+ mode recomputes `bindMatrixInverse` from `matrixWorld` every frame, so `matrixWorld` cancels out
+ entirely. Binding with the armature's matrix rendered a blank frame.
+- Display offset comes from the **mesh bounds alone**: `(−centre.x, −min.y, −centre.z)`. Adding the
+ armature translation double-counts it — the figure lands offset by exactly that translation.
+- `updateMatrixWorld(true)` **before** `new THREE.Skeleton(...)`. `calculateInverses()` reads each
+ bone's current world matrix; constructed first it captures identity, the rest pose never cancels,
+ and every vertex sits displaced by its bone's offset. That failure compiles, binds, reports
+ `bound: true`, and renders a corpse.
+
+### 3.3 — The verdict on the original complaint
+
+```bash
+node $I/runtime/scripts/export_mesh_buffers.mjs \
+ --url <preview> --out meshes-after.json
+
+python3 $I/forge/stage5_rig/mesh_parity.py verify \
+ mesh-manifest.json meshes-after.json; echo "exit=$?"
+```
+
+- **Pass:** rigging touched no geometry. Skin attributes appear as *added (legal)*.
+- **Fail: the rigging is wrong.** **Never re-freeze to make it pass** — that would certify the
+ damage instead of catching it. The failure block names the mesh, the attribute and the vertex;
+ keep it verbatim.
+
+### 3.4 — Measure the clips, then run the gates
+
+```bash
+python3 $I/forge/stage5_rig/glb_rig_reference.py <glb> \
+ --sample-clips --landmarks landmarks.json --out sampled-clips.json
+
+python3 $I/forge/stage5_rig/clip_features.py sampled-clips.json
+
+python3 $I/forge/stage5_rig/rig_gates.py rig-gate-payload.json
+```
+
+- **Expect:** not-ok, with `G1 G3 G6 G10` unevaluated. Judge the run on the other eight. **If any of
+ those eight *fails*, that is a real finding.**
+- **Watch:** `scaleDelta ≠ 0` on any clip is a tripwire, not a descriptor — the source rig scales
+ joints, which changes what skin conditioning may legally do. Surface it before anything else
+ proceeds.
+- Clip names: a name that describes motion is provable; one that implies intent is not. Anything
+ carrying `inferred: true` is a guess, and marking it that way is the honest answer rather than a
+ placeholder for a better classifier.
+
+---
+
+## Phase 4 — Compare against Phase 0 and decide
+
+**The only phase that answers the question you actually asked.**
+
+Record the same three angles as Phase 0, playing the same clip. Then answer three questions **in
+writing**:
+
+1. **Does the mesh still tear?** Yes / no / differently — and if differently, how.
+2. **Did a gate catch it before you saw it?** If your eyes found something no gate flagged, that is
+ the most valuable result in the whole run: it names a missing gate.
+3. **Did a gate flag something your eyes cannot see?** Equally valuable in the other direction —
+ either a real defect below the visual threshold, or a gate that is too strict.
+
+> **"Improved" is not "fixed."** If it tears less, say it tears less. Naming what still does not
+> match is worth more than a clean verdict.
+
+---
+
+## What to send back
+
+These make the result actionable rather than a guess:
+
+- Phase 0 and Phase 4 recordings — same clip, same three angles.
+- `glb-rig.json`, especially `deformVsTechnical` and the joint ordering.
+- The `mesh_parity verify` output, pass or fail, verbatim.
+- The full `rig_gates` report — the unevaluated gates matter as much as the failures.
+- Whatever you repaired in the `mesh-repair` step, one line each.
+- The point where you had to deviate from this plan, and why.
+
+---
+
+## Known gaps, so they don't read as bugs
+
+- **Four gates have no producer** (`G1` `G3` `G6` `G10`). They report `unevaluated`, which makes the
+ report not-ok by design.
+- **Nothing writes `rig-payload.json`** in the shape `validate_rig_payload.py` expects.
+ `new_sculpt_spec.py` produces a differently-shaped `spec["rig"]`; no converter exists.
+- **`mesh-repair` and `rig-bind` are prose steps** with no script and no verifiable artifact.
+ `rig-bind` creates the skeleton; its only downstream check is `mesh-parity-verify`, which proves
+ buffers were untouched, **not** that the bind is correct.
+- **The GLB fast lane worktree is still on 1.5.1** and has none of the 1.5.2 animation stack. The two
+ branches cannot be combined until it is rebased.
+- **`single-subject` thresholds** (blend radius `R = 0.006H`, the §2 classifier boundaries) still
+ come from one rig. Treat them as starting values, not constants.
+
+**Cheapest next fix** if you want `G1` — the gate that catches clips playing silently, and the only
+check that distinguishes a clip that plays from one that exists, loads, holds an action and reports a
+duration while driving nothing — is a CLI on `emit_animation_runtime.py`. It already contains the
+`runGateR1()` harness that produces the input; nothing exposes it to a shell.
+
+---
+
+## Related
+
+- `docs/GLB_ANIMATED_CHARACTER_PROMPT.md` — the one-pass prompt this plan tests.
+- `docs/pipelines/character-rigging-animation-1.5.2.md` — the derivation and the failure log.
+- `grimoire/readiness/animation_contract.md` — the routing file read at Stage R.
+- `forge/stage5_rig/CONTRACT_1.5.2.md` — module map and payload shapes.
diff --git a/docs/pipelines/character-rigging-animation-1.5.2.md b/docs/pipelines/character-rigging-animation-1.5.2.md
new file mode 100644
index 0000000..376033c
--- /dev/null
+++ b/docs/pipelines/character-rigging-animation-1.5.2.md
@@ -0,0 +1,488 @@
+# img2threejs 1.5.2 — Character Rigging & Animation Pipeline
+
+**Status:** implemented in img2threejs 1.5.2 (`forge/stage5_rig/`; module map in
+`forge/stage5_rig/CONTRACT_1.5.2.md`, routing in `grimoire/readiness/animation_contract.md`).
+**Scope:** computing and designing animation for character rigs.
+**Provenance:** distilled from the Lee Sin showcase build (1.5.1). That demo is read-only evidence
+here; nothing in this document is specific to it.
+
+Every threshold below is expressed as a fraction of **figure height H**, never in absolute units.
+Lee Sin was normalised to H = 1.0, so its measured numbers read directly as fractions; a rig at a
+different scale must convert. Where a number came from one subject only, it is marked
+`single-subject` and should be treated as a starting value, not a constant.
+
+---
+
+## 0. Why this pipeline exists
+
+Rigging failures in 1.5.1 were not "the animation looks slightly wrong". They were **total and
+silent**: eleven clips held actions, the mixer held state, buttons dispatched, and nothing moved.
+Two separate bugs each produced a plausible-looking scene with zero motion. Neither was visible in
+code review; both were found only by measuring.
+
+The pipeline is therefore built around one rule:
+
+> **Nothing about a rig is believed until it has been evaluated at a sampled time and compared
+> against the value the track says it should have.** A clip that exists is not a clip that plays.
+
+---
+
+## 1. The measurement vocabulary
+
+One feature vector underpins the whole pipeline. It is what identifies an unknown clip (Stage R3)
+**and** what specifies a clip you are about to author (Stage R4). Same code, both directions.
+
+Sample the clip at `N = 25` evenly spaced times. At each time, record the **world** position of six
+landmark joints: `hip`, `head`, `hand.l`, `hand.r`, `foot.l`, `foot.r`.
+
+| Feature | Definition |
+|---|---|
+| `duration` | clip length, seconds |
+| `travel` | `max_t ‖hip_xz(t) − hip_xz(0)‖` — planar displacement of the root |
+| `rise` | `max_t hip_y − min_t hip_y` — vertical excursion of the root |
+| `speed` | `travel / duration`, in H per second |
+| `handRange` | largest per-axis range over both hands |
+| `footRange` | largest per-axis range over both feet |
+| `headRise` | vertical range of the head |
+| `scaleDelta` | `max_t max_j |scale_j(t) − 1|` |
+| `poseReturn` | max per-joint transform delta between `t = 0` and `t = duration` |
+
+`scaleDelta` is a tripwire, not a descriptor. Lee Sin measured `0.000` on all eleven clips; a
+non-zero value means the source rig scales joints, which changes what Stage R2 may legally do to
+skin weights and must be surfaced before anything else proceeds.
+
+---
+
+## 2. Classification thresholds
+
+Derived from eleven measured clips on one subject. Boundaries sit in the empty gaps between
+observed clusters, not at round numbers.
+
+```
+idle travel < 0.02H and rise < 0.02H
+in-place travel < 0.30H
+walk 0.30H/s ≤ speed < 0.60H/s
+run 0.60H/s ≤ speed < 1.50H/s
+dash speed ≥ 1.50H/s
+jump rise ≥ 0.15H and travel < 0.50H
+leap rise ≥ 0.15H and travel ≥ 0.50H
+planted footRange < 0.10H (feet do not participate)
+gesture handRange ≥ 0.40H while in-place
+```
+
+Validation against the source clips these came from:
+
+| clip | travel | rise | speed | lands as |
+|---|---|---|---|---|
+| walk-forward | 1.133 | 0.019 | **0.400** | walk ✓ |
+| run-forward | 1.465 | 0.021 | **0.799** | run ✓ |
+| dash-forward | 2.906 | — | **2.250** | dash ✓ |
+| jump-in-place | 0.272 | **0.248** | — | jump ✓ |
+| leap-forward | 2.826 | **0.517** | — | leap ✓ |
+| idle-still | 0.013 | 0.0001 | — | idle ✓ |
+| arms-only | — | 0.008 | — | planted + gesture ✓ |
+
+The walk/run gap (0.400 → 0.799) and run/dash gap (0.799 → 2.250) are both wide. `single-subject`:
+confirm the gaps survive on a second rig before hardening these.
+
+---
+
+## 3. Naming and the honesty flag
+
+Source clips arrive named `NlaTrack`, `NlaTrack.001`, … — Blender NLA strip names carrying no
+information. Rename from measurement, and record **which measurement the name rests on**.
+
+Names that describe motion (`run-forward`, `arms-only-feet-planted`) are provable. Names that imply
+intent (`strike`, `guard`, `taunt`) are **not** — no kinematic feature distinguishes a strike from a
+stumble. Those carry `inferred: true`.
+
+```ts
+interface ClipName {
+ sourceName: string; // never discarded — keep the accessor-parity chain intact
+ id: string;
+ label: string;
+ measured: string; // the numbers the name rests on
+ inferred: boolean; // true when wording implies intent measurement cannot prove
+ loop: boolean;
+}
+```
+
+Two of eleven source clips could only be named by inference. Marking them cost nothing and keeps the
+distinction between "measured" and "guessed" visible to whoever reads it next.
+
+---
+
+## 4. The loop rule — corrected
+
+glTF carries no loop flag, so it must be decided.
+
+1.5.1 used *"a clip that neither travels nor rises can repeat seamlessly."* **That rule does not
+match its own data**: `idle-gesture` has `travel = 0.121` — six times the idle threshold — and is
+correctly marked loopable, because what makes a clip loop is not that the root stays put but that
+**the last pose returns to the first**.
+
+**Use instead:**
+
+```
+loop ⟺ poseReturn ≤ 0.5° per rotation joint
+ AND ‖hip(T) − hip(0)‖ ≤ 0.01H
+```
+
+`poseReturn` is measured directly on the joint transforms, so it catches a clip that wanders and
+comes back (loopable) and rejects one that ends mid-stride a centimetre from where it started
+(not loopable). Travel and rise stay as descriptors; they stop being the loop criterion.
+
+---
+
+## Stage R0 — Rig intake
+
+**Input:** a joint hierarchy with local TRS, a skin (joint list + inverse bind matrices), clips.
+**Output:** a typed node graph, plus a classification of every node.
+
+1. **Deform vs technical.** A node is a `Bone` **iff it appears in `skin.joints`**; everything else
+ is a `Group`. Do not infer from names. Lee Sin's rig has 42 deform joints inside a 113-node
+ graph, so the graph is far larger than the skeleton and a traversal-order skeleton would be a
+ different skeleton — building non-joint nodes as bones corrupts the index space.
+
+ **Correction, measured 2026-08-25.** 1.5.2 originally said "clips target technical nodes that are
+ not joints" and cited this rig for it. Re-measured with `stage5_rig/glb_rig_reference.py` on the
+ asset the pipeline was distilled from: **all 1,353 animation channels across all 11 clips target
+ deform joints; zero target technical nodes.** The rule stands — it is what keeps the skin's index
+ space intact, and a rig that *does* animate technical nodes is entirely legal glTF — but the
+ evidence offered for it did not reproduce, so the claim is now stated as the risk it guards
+ against rather than as an observation. `deformVsTechnical` reports the real count per asset;
+ read it instead of assuming either way.
+2. **Link, then root.** Build all nodes first, then attach children, then attach scene roots to one
+ container. Any other order produces a graph whose world matrices are stale at skeleton time.
+3. **Skeleton.** `new THREE.Skeleton(bones, boneInverses)` where `bones[i]` is the node for
+ `skin.joints[i]` and `boneInverses[i]` is matrix `i` of the inverse-bind accessor. The ordering
+ is the skin's, never the traversal's.
+4. **Landmarks.** Resolve the six landmark joints (§1) once and cache them. Prefer topology over
+ names: the hip is the highest-degree node nearest the root; hands and feet are chain leaves;
+ left/right are separated by the sign of local X.
+
+**Gate R0:** `maxSkinIndex ≤ bones.length − 1`. A single out-of-range index silently reads a
+garbage matrix and deforms one vertex to infinity.
+
+---
+
+## Stage R1 — Bind space
+
+**This stage caused every rigging failure in 1.5.1. Read it before writing any binding code.**
+
+Three.js `SkinnedMesh` defaults to **attached** bind mode, in which `bindMatrixInverse` is
+recomputed from the mesh's `matrixWorld` on *every* `updateMatrixWorld`. The skinning evaluation is
+therefore:
+
+```
+v' = skinMatrix · bindMatrix · v // matrixWorld cancels out entirely
+```
+
+Three consequences, each of which was hit and measured:
+
+| What was tried | What rendered |
+|---|---|
+| `mesh.bind(skeleton, armature.matrixWorld)` | **blank frame** — bind applied twice |
+| identity bind + a `skinSpace` wrapper | figure 0.5 m high, floating |
+| identity bind + armature translation added to the display offset | figure offset by exactly the armature translation |
+
+**The rule:**
+
+```ts
+mesh.bind(skeleton, new THREE.Matrix4()); // identity, always, in attached mode
+group.position.copy(displayOffset); // presentation only
+```
+
+and the display offset must be computed **from the mesh bounds alone** — `(−centre.x, −min.y,
+−centre.z)` to seat the figure on Y = 0 — with **no armature translation added**. The armature's
+transform is already inside `skinMatrix`; adding it again double-counts.
+
+**Gate R1 (the one that catches silent death):** seek each clip to five times, then for every track
+compare the node's actual transform against `track.createInterpolant().evaluate(t)`:
+
+```
+maxSampledBindingDelta ≤ 2^-23 (float32 epsilon)
+```
+
+This proves the binding path *reaches the node*. A clip can exist, be loaded, hold an action and
+report a duration while driving nothing — this is the only check that distinguishes the two.
+
+---
+
+## Stage R2 — Skin conditioning
+
+Applies to any character built from **multiple overlapping parts**, which is most generated
+characters.
+
+### The failure
+
+Two vertices sitting on top of each other in bind pose but bound to *different* joints **must**
+separate the moment those joints diverge. That is not a bug in the weights; it is what the weights
+say. It appears as the skin tearing open mid-clip.
+
+### What did not work
+
+Welding only exactly-coincident vertices (within 1e-4 H). It closed the neck-to-collarbone crack
+but a sweep of 11 clips × 4 times × 3 azimuths = 132 frames still found cracks in **28 frames,
+1,410 px** of background showing through. Adjacent parts mostly **overlap**; they rarely share a
+rim, so coincidence-welding finds almost nothing.
+
+### What worked — proximity weight blending
+
+For every vertex with a vertex from **another part** within radius `R`:
+
+```
+w_mixed = w_own + Σ_q w_q · (1 − d_q/R)²
+w_final = renormalise( top4( w_mixed ) )
+```
+
+Implementation requirements, each non-optional:
+
+- **Dense accumulation.** Expand the 4-influence binding to a dense vector over all joints before
+ mixing, then reduce back to 4. Mixing sparse 4-slot bindings directly loses influences.
+- **Write after all reads.** Buffer results and commit at the end, or the blend depends on
+ iteration order and stops being reproducible.
+- **Uniform grid hash at one cell per radius**, so a query touches at most 27 buckets. Brute force
+ is O(n²) and unusable past ~50k vertices.
+- **Interior vertices are never touched** — they keep the source binding exactly.
+
+**Radius:** `R = 0.006H` `single-subject`. Chosen against a control run with the blend disabled,
+sweeping 11 clips × 4 times × 2 shoulders × 2 azimuths = **176 frames**:
+
+| | background through splits | thin dark creases |
+|---|---|---|
+| blend off | 974 px in 30 blobs | 31,316 px |
+| blend R = 0.006H | **287 px in 15 blobs** | 36,470 px |
+
+**The trade is real and must be stated when this stage runs:** averaging two parts' bindings makes
+them travel together, which closes the hole, but pulls each slightly off the path its own joints
+would take — so creases get *worse* by ~16%. This was accepted deliberately: **a hole shows the
+background, a crease shows skin.** Do not let a later stage "fix" the crease count by disabling the
+blend.
+
+Residual, documented rather than hidden: creases are not eliminated by this method. Removing them
+entirely requires welding the parts into one continuous mesh with a single unified weight field,
+which changes the part structure and breaks per-part UI.
+
+**Gate R2:**
+```
+|1 − Σ w| ≤ 2e-7 for every vertex (normalised)
+maxSkinIndex ≤ bones.length − 1 (still in range after reduction)
+```
+
+---
+
+## Stage R3 — Clip identification
+
+For a rig that arrives **with** clips.
+
+1. Sample the feature vector (§1) for each clip.
+2. Classify (§2), name, set the `inferred` flag (§3), decide `loop` (§4).
+3. Transfer tracks exactly: key times and values byte-for-byte, `STEP → InterpolateDiscrete`,
+ `LINEAR → InterpolateLinear`, binding string `${nodeName}.${property}` with
+ `rotation → quaternion`, `translation → position`, `scale → scale`.
+4. Keep `sourceName`, channel/sampler indices and per-accessor hashes on `track.userData` so the
+ parity chain back to one source animation survives renaming.
+
+**Gate R3:** track count, key count, per-track byte equality, duration equality, and exactly two
+distinct interpolation constants across the set.
+
+---
+
+## Stage R4 — Action design
+
+For authoring clips a rig does **not** have. This is where the measurement vocabulary pays off
+twice: the same feature vector that identifies a clip **specifies** one.
+
+### The loop
+
+```
+target features → author tracks → measure with §1 → compare → iterate
+```
+
+A designed clip is accepted only when its measured features land inside the target band. "Looks
+right" is not a criterion; the classifier from §2 must agree the clip is what it claims to be.
+
+### Chain resolution
+
+Author on **chains**, not individual joints. Resolve from topology:
+
+- `spine` — root → highest-degree path toward the head
+- `arm.{l,r}` — clavicle → hand leaf
+- `leg.{l,r}` — hip → foot leaf
+- symmetry pairs by mirrored local X within tolerance
+
+**Medial/lateral convention gate:** after resolution, assert `leftAnchor.x > 0 > rightAnchor.x` in
+model space. This one comparison catches a mirrored rig — the failure where every left-hand action
+plays on the right and nothing about it looks wrong in isolation.
+
+### Primitives
+
+| Primitive | Use | Parameters |
+|---|---|---|
+| **Gait** | walk / run / dash | cadence, stride, contact fraction, hip rise, arm counter-swing |
+| **Ballistic** | jump / leap | takeoff velocity, apex rise, flight time, land absorption |
+| **Reach** | strike / gesture | target socket, windup fraction, follow-through, return |
+| **Additive** | breathing, sway | amplitude, period, joint mask — layered on any base |
+
+Gait is a phase machine, not a sine wave. Each leg has stance and swing; the **contact constraint**
+is what separates an animation from a slide: while a foot is in stance its world position must not
+move.
+
+```
+footSlide = max over stance frames ‖foot_world(t) − foot_world(t_contact)‖
+require footSlide ≤ 0.01H
+```
+
+This is the single most valuable gate in the stage. A gait that violates it reads as "floaty" or
+"skating" to every viewer while being hard to name by eye.
+
+### Design targets, worked
+
+To author a walk for a rig of height H:
+
+```
+duration ≈ 1.0–1.2 s per cycle
+speed target 0.40H/s → travel = speed × duration
+rise 0.015H–0.025H (hips stay flat; more reads as a limp)
+handRange 0.15H–0.25H (counter-swing, opposite phase to the leg) — hip-relative
+footRange ≈ stride ≈ travel / 2 per foot per cycle — hip-relative
+contact 0.60 of cycle per foot, so both feet are down 0.20 of the time
+poseReturn ≤ 0.5° → loopable by §4
+```
+
+**Frame correction — found by implementing this.** §1 defines `handRange` and `footRange` as
+**world-space** per-axis ranges, and under that definition the two bands above are unsatisfiable at
+any speed: a forward-travelling gait carries its limbs with the body, so `footRange ≈ travel` and
+`handRange ≈ travel + swing`. The bands only become meaningful once the root's planar motion is
+removed, so the limb bands in this section are **hip-relative** and are marked as such. The global
+features — `duration`, `travel`, `rise`, `speed`, `scaleDelta`, `poseReturn` — stay in world space,
+which is the only frame the §2 classifier is meaningful in. Two frames, stated, rather than one
+frame that quietly cannot hold.
+
+`footRange ≈ travel / 2` also compares two different quantities: `travel / 2` is the **step length**
+between alternating footfalls, while §1's `footRange` is a **positional range**. A phase machine
+puts the hip-relative foot excursion at `contactFraction × travel` — 1.2× the spec's figure at the
+walk contact fraction of 0.60, 0.8× at the run's 0.40. The implementation reads the `≈` as ±30%.
+
+Run: raise speed into `[0.60H/s, 1.50H/s)`, drop contact fraction below 0.5 so a flight phase
+exists, raise `handRange` toward 0.35H. The classifier must then report `run`, not `walk`, without
+being told — that is the acceptance test.
+
+**Gate R4:**
+```
+classifier(authored) == intended class (§2 agrees)
+footSlide ≤ 0.01H during every stance frame
+scaleDelta == 0 (never author joint scale)
+poseReturn ≤ 0.5° for any clip declared loop
+no joint exceeds its measured range from the source clips, where source clips exist
+```
+
+---
+
+## Stage R5 — Runtime assembly
+
+Three integration traps, all of which produced *zero visible motion* in a scene that otherwise
+rendered correctly.
+
+### 5.1 Ticker collection vs lazy geometry
+
+A viewer that walks the scene once at `start()` collecting `userData.tick` **misses every demo
+whose rig arrives later**. The mixer holds the action; nothing calls `mixer.update`; every clip
+plays silently.
+
+```ts
+refreshTickers(): void { /* re-walk the scene for userData.tick */ }
+// call after any late geometry lands
+```
+
+Any lazily-built character must trigger a ticker refresh when its payload resolves. Same for the
+animation UI: mount the panel as a function so it can also run *after* the controller exists.
+
+### 5.2 Presentation offsets vs animated pose
+
+If the viewer offsets parts for an explode/inspect view, it must **subtract the offset it applied
+last frame** before the rig ticks, and re-apply after — never restore a cached rest pose. A cached
+rest pose overwrites whatever the animation just produced:
+
+```ts
+removeExplodeOffset(); // hand the animated transform back
+for (const tick of tickers) tick(dt, elapsed);
+applyExplodeOffset(); // presentation on top
+```
+
+### 5.3 Controller contract
+
+```
+play(name) stopAllAction → restore bind pose → reset → set loop mode → play
+seek(name,t) as play, then paused = true, time = t, mixer.update(0), updateMatrixWorld(true)
+stop() stopAllAction → restore bind pose → active = 'idle'
+advance(dt) mixer.update(dt) → updateMatrixWorld(true)
+```
+
+Restoring the bind pose **before** each play is what stops clips bleeding into one another: a
+clip that ends mid-pose leaves joints displaced, and the next clip's tracks only overwrite the
+joints they address. Loop mode comes from the measured `loop` flag: `LoopRepeat, Infinity` or
+`LoopOnce, 1` with `clampWhenFinished = true`.
+
+---
+
+## Stage R6 — Gates
+
+Nothing ships until all of these pass. Each exists because its absence let a real failure through.
+
+| # | Gate | Criterion | Catches |
+|---|---|---|---|
+| G1 | binding reaches node | `maxSampledBindingDelta ≤ 2^-23` over ≥5 times × all clips | clips that play silently |
+| G2 | deformation finite | `applyBoneTransform` on ≥64 vertices/mesh/frame, all finite | bad indices, NaN weights |
+| G3 | bind restore | `maxBindRestoreDelta ≤ 1e-12` after `stop()` | pose bleed between clips |
+| G4 | weights normalised | `|1 − Σw| ≤ 2e-7` every vertex | shrinking/inflating limbs |
+| G5 | indices in range | `maxSkinIndex ≤ bones−1` | one vertex to infinity |
+| G6 | every visible mesh bound | `visibleMeshCount == visibleSkinnedMeshCount` | a part left behind in bind pose |
+| G7 | medial/lateral | `leftAnchor.x > 0 > rightAnchor.x` | mirrored rig |
+| G8 | foot contact | `footSlide ≤ 0.01H` in stance | skating gaits |
+| G9 | no joint scale | `scaleDelta == 0` unless the source has it | weight-blend invalidation |
+| G10 | skin integrity sweep | background-through-split ≤ measured baseline | tearing under motion |
+
+### G10 is a visual gate and needs a harness
+
+Sweeping poses is not optional — **five poses is not coverage**. The sweep that found the real
+defects was 11 clips × 4 times × 2 sides × 2 azimuths = **176 frames**.
+
+Method: render on a saturated background the model cannot contain, count background pixels *inside*
+the silhouette, then apply a distance transform and keep only blobs thin enough to be a split rather
+than a legitimate opening (an armpit, a gap between straps). Report both numbers — holes and
+creases — because Stage R2 trades one against the other, and a single combined score hides that.
+
+---
+
+## Appendix — the failures behind the rules
+
+Kept because each cost real time and none was visible in review.
+
+1. **Attached bind mode cancels `matrixWorld`.** Two "fixes" shipped before the right one: a blank
+ frame, then a half-height figure. Rule: identity bind, offset from bounds only. → R1
+2. **Ticker snapshot before lazy geometry.** Every clip silent, UI fully functional. → R5.1
+3. **Display offset double-counting the armature translation.** Exactly 0.5 m of float. → R1
+4. **Coincidence-welding instead of proximity blending.** Closed one crack, left 28 frames
+ cracked. → R2
+5. **Index-paired comparison between meshes of different vertex counts.** Produced a confident,
+ completely invalid number (29.08% vs an actual 2.51%). Any cross-mesh comparison needs a spatial
+ join. → measurement discipline
+6. **Comparing local-space geometry against world-space reference.** Off by 0.47 m and self-
+ consistent. Always state the frame. → measurement discipline
+7. **Flipped V when sampling textures.** glTF UV origin is top-left. → R2/material
+8. **`NlaTrack.00N` shipped as user-facing labels.** Eleven unusable buttons. → R3
+9. **A loop rule that contradicted its own data.** `idle-gesture`, travel 0.121, correctly looped.
+ → R4
+
+---
+
+## What this pipeline does not solve
+
+- **Creases at part overlaps.** R2 reduces holes and slightly worsens creases. Eliminating creases
+ needs one continuous mesh with a unified weight field — a different topology contract.
+- **Retargeting between skeletons.** Everything here assumes one skeleton. Cross-rig retarget needs
+ a joint correspondence and its own gates.
+- **Intent.** No measurement distinguishes a strike from a stumble. `inferred: true` is the honest
+ answer, not a placeholder for a better classifier.
diff --git a/docs/standard-prompts/README.md b/docs/standard-prompts/README.md
new file mode 100644
index 0000000..148f83e
--- /dev/null
+++ b/docs/standard-prompts/README.md
@@ -0,0 +1,38 @@
+# Standard prompts
+
+Four prompts, one per job. Each is copy-paste, each completes in one pass, and each states its own
+exit condition. Replace every `<PLACEHOLDER>` before pasting.
+
+| Prompt | Use when | Route |
+|---|---|---|
+| [`build.md`](build.md) | a reference image, no mesh | reconstruct from primitives, gated |
+| [`glb-force-measured.md`](glb-force-measured.md) | a GLB is available and every parameter it measures should be forced, not approximated | measure, force, prove with parity gates |
+| [`polish.md`](polish.md) | a build that renders but does not match | bounded correction, one defect at a time |
+| [`vfx.md`](vfx.md) | the rig and its clips play, only the effects are missing | measure the events off a real mixer, then schedule against them |
+
+Rigging and animation on top of a GLB: [`../GLB_ANIMATED_CHARACTER_PROMPT.md`](../GLB_ANIMATED_CHARACTER_PROMPT.md).
+
+## Why these were rewritten
+
+The previous prompts blocked more than they built, for three reasons that were mechanical rather
+than stylistic:
+
+1. **They pointed at a file that does not exist.** `GLB_ANIMATED_CHARACTER_PROMPT.md` delegated the
+ whole geometry route to `docs/GLB_CHARACTER_PROMPT.md`, which was never written. An agent
+ reaching the largest step of the run found a dead reference. `build.md` is that missing file.
+
+2. **They ran a gate before producing the gate's input.** `validate_sculpt_spec.py --strict-quality`
+ fails with ~89 causes on a freshly scaffolded spec, because the scripts only scaffold —
+ `preSpecAssessment.objectClass.primaryType` is literally `"unassessed"`, all eight complexity
+ scores are `0`, and `detailInventory` is empty. Told to "run the gate and do not advance", an
+ agent stops on its first command, every time. **Every prompt here now fills the scaffold before
+ it validates**, and says exactly which fields.
+
+3. **They treated every stop as equally serious.** A missing input and a failed measurement need
+ different responses. Each prompt below separates *produce the input and continue* from
+ *stop and ask*, and lists which is which.
+
+## The rule the four share
+
+> A gate is a question. Answer it with evidence, or say you could not — never by lowering the bar,
+> and never by stopping before you have tried to produce the evidence it asked for.
diff --git a/docs/standard-prompts/build.md b/docs/standard-prompts/build.md
new file mode 100644
index 0000000..d5ca30f
--- /dev/null
+++ b/docs/standard-prompts/build.md
@@ -0,0 +1,111 @@
+# Build — reference image to a gated procedural model
+
+The reconstruction route. This is the file `GLB_ANIMATED_CHARACTER_PROMPT.md` delegates its
+Stages 1–3 to.
+
+**The one thing that makes this prompt not block:** the forge scripts *scaffold*, they do not
+*assess*. A freshly generated spec carries `primaryType: "unassessed"`, eight complexity scores of
+`0`, an empty `detailInventory` and `anatomy.applies` unset — so `--strict-quality` fails it with
+around 89 causes. Those are not defects to report; they are **your fields to fill**. Fill them, then
+validate.
+
+Replace every `<PLACEHOLDER>`, paste as one prompt.
+
+````text
+Rebuild the subject in this reference as a procedural Three.js model, using img2threejs.
+
+## Inputs
+- Reference: <ABSOLUTE_PATH_TO_IMAGE>
+- Subject name: <SubjectName>
+- Demo id: <subject-id>
+- Profile: <character | animated-character | object>
+- Real longest dimension: <e.g. 1.70 m> # sanity-checks scale; never used to scale
+
+## Step 0 — Can this subject be built at all?
+
+Segment the figure from the background and report as numbers:
+ · width/height at the hip band (48-54% of figure height), knee (68-74%), ankle (92-99%)
+ · silhouette area / height²
+ · whether the silhouette WIDENS below the hip, and by how much
+
+The character template is 61 anatomy components and ZERO garments — clothing is not shipped in
+v1.5. If a meaningful share of the silhouette is cloth standing away from the body (flared skirt,
+hanging sleeve, cape, trailing panel), STOP HERE and tell me: what fraction, and what will be lost.
+A body-shaped figure delivered under the subject's name is the failure this step exists to prevent.
+For a subject like that the GLB route is the honest one — say so and stop.
+
+## Step 1 — Intake
+
+ python3 forge/state.py init --state .img2threejs/state.json \
+ --reference <image> --profile <profile> --spec object-sculpt-spec.json
+ python3 forge/stage1_intake/probe_image.py <image>
+ python3 forge/stage1_intake/extract_landmarks.py <image> \
+ --out anatomy.json --overlay overlay.png
+ python3 forge/stage1_intake/build_detail_inventory.py <image> \
+ --mode component-zones --out detail-inventory.json
+
+Two things about the overlay, both measured, both worth knowing before you trust it:
+ · it divides the IMAGE height, not the figure's bounding box, so every guide is offset by
+ whatever margin sits above the head. Re-read the guides against the figure top.
+ · `styleHeads` defaults to 6.0. Measure the head against the figure and set the real value;
+ on a stylized 8-head figure the default puts the "nose base" guide on the eyes.
+
+## Step 2 — Assess. This is YOUR work, not the script's.
+
+Open the assessment and fill it from looking at the reference. Nothing downstream can succeed
+until these hold real values:
+
+ preSpecAssessment.objectClass.primaryType not "unassessed"
+ preSpecAssessment.objectClass.primaryDomain object | character | hybrid
+ objectClass.formLanguage / structureKind / motionPotential / materialFamilies non-empty
+ complexity.scores all eight, from what you see, not defaults
+ complexity.estimatedCounts real counts
+ detailInventory >= targetMinDetails entries
+ anatomy.applies = true, with styleHeads, proportions, pose, faceLandmarks
+
+Enumerate the identity-defining details first — bevels and rounding, panel seams, fasteners,
+engraved or painted linework, gloss vs matte zones, wear. Drop any detail you cannot place on a
+real component rather than faking it.
+
+## Step 3 — Spec, then gate
+
+ python3 forge/stage2_spec/new_sculpt_spec.py "<SubjectName>" --image <image> \
+ --assessment assessment.json --out object-sculpt-spec.json
+ python3 forge/stage2_spec/validate_sculpt_spec.py object-sculpt-spec.json --strict-quality
+
+Expect failures on the first run. Read each cause and answer it — a missing
+`colorMaterialRecipe` means derive that component's colour from the reference pixels, not that the
+gate is wrong. Iterate until it exits 0.
+
+Only then:
+
+ python3 forge/stage3_build/generate_threejs_factory.py object-sculpt-spec.json \
+ --out src/create<SubjectName>Model.ts
+
+The generator repeats the gate and is fail-closed: on failure it exits 2 with
+`{"status":"BLOCKED", ...}` and writes NO file. If you see that, the spec is not ready — go back to
+Step 2. Never pass `--allow-nonstrict`.
+
+## Step 4 — Render and review, one pass at a time
+
+Render, package one reference-vs-render sheet, and judge it. Do not advance a pass until its
+review passes. Record per-region confidence for anything the single view cannot show.
+
+## When to stop, and when not to
+
+STOP and ask me:
+ · Step 0 says the subject is mostly cloth
+ · a gate fails for a reason you cannot resolve from the reference
+ · `next.py` exits 3 / `status=stopped`
+
+DO NOT stop for:
+ · a scaffolded field being empty — fill it, that is the job
+ · strict-quality failing on the first run — read the causes and answer them
+ · a detail you cannot place — drop it, note it, continue
+
+## Report
+
+Components · strict-quality exit and cause count · passes cleared · details inventoried vs target ·
+per-region confidence · and one line naming what still does not match. Never say "done" when it is
+"improved".
+````
diff --git a/docs/standard-prompts/glb-force-measured.md b/docs/standard-prompts/glb-force-measured.md
new file mode 100644
index 0000000..3ce314d
--- /dev/null
+++ b/docs/standard-prompts/glb-force-measured.md
@@ -0,0 +1,161 @@
+# Force-measured — lock the build to what the GLB actually measures
+
+For a build that has a GLB alongside the reference. The GLB is a **measurement instrument**: the
+pipeline reads its parameters, encodes the measured surface, and emits TypeScript that carries those
+numbers. No `.glb` and no `.bin` ships or is fetched at runtime, and no texture image is copied —
+this pipeline emits code, and that contract does not bend because a mesh happens to be available.
+
+Same rule as [`build.md`](build.md) and the GLB prompts on `main`. What this one adds is a single
+word: **force**.
+
+## What "force" means, and what "1:1" refers to
+
+Without it, a build measures the GLB and then *approximates* — a diameter becomes "about right", a
+roughness becomes a plausible guess, a proportion drifts toward the template. Every one of those is
+a value the GLB already answered exactly.
+
+> **1:1 refers to the measured PARAMETERS, not to the file.** Every parameter the GLB genuinely
+> carries is forced to its measured value instead of an inferred one, and each comes with the check
+> that proves it landed in the emitted code.
+
+Forced to measured:
+
+| | |
+|---|---|
+| dimensions and proportions | overall size, per-band widths, centroids, part bounds |
+| appearance scalars | base colour, roughness, metalness, emissive, alpha mode |
+| structure | part count and hierarchy, socket and pivot positions |
+| rig, when present | skeleton, skin joint order, inverse binds, joint weights |
+| motion, when present | clip names, durations, keyframes |
+
+## What the GLB cannot hand over — say this before the review, not after
+
+None of these is a defect and none is negotiable:
+
+- **Texture images and normal maps are deliberately not copied.** The code-only contract is the
+ point of this project, not an obstacle to it. Appearance is carried as per-vertex colour sampled
+ from the base-colour map at each vertex UV, so detail finer than the vertex spacing is not carried.
+ Where a map drove metalness or roughness, the emitted value is a measured median, and that is
+ recorded as a median rather than presented as an authored constant.
+- **Nothing finer than the node's own cell size survives**, because nothing finer was measured.
+- **Rigging and animation are usually absent.** `skinCount: 0` and `animationCount: 0` are the
+ common case; then there is nothing to force and Stage R authoring applies instead.
+- Quantisation, stated once so nobody rediscovers it at review: positions are 16-bit over the
+ model's own bounding box (~0.03 mm on a 2 m figure, finer than the source triangles), normals are
+ 16-bit octahedral (~1°, and authored hard edges survive because normals are carried rather than
+ recomputed), indices are lossless, and keyframes stay float32 — a quantised quaternion drifts
+ visibly over a looping clip.
+
+## Why the usual quality gate is the wrong instrument here
+
+`--strict-quality` exists to stop a **shallow spec** reaching codegen: an unassessed `objectClass`,
+an empty `detailInventory`, a `colorMaterialRecipe` nobody derived. Every one of those asks *"did
+you infer this responsibly?"*
+
+On a forced build the answer is that the value was not inferred at all — it was measured. So the
+gate is **replaced, not lowered**: parity gates compare the emitted code against the measurement,
+which is a stricter question than whether a judgement was defensible.
+
+## The prompt
+
+````text
+Build this subject with every parameter the GLB measures FORCED to its measured value.
+
+## Inputs
+- GLB (measurement instrument): <ABSOLUTE_PATH_TO_GLB>
+- Reference image (optional): <PATH_OR_NONE>
+- Subject name: <SubjectName>
+- Demo id: <subject-id>
+- Overwrite: <yes | no> # yes = replace an existing demo of this id in place
+
+## Contract
+
+The GLB is measured, never shipped. Symlink it somewhere gitignored; the running demo must fetch no
+`.glb` and no `.bin`. Texture images are not copied — appearance is carried as per-vertex colour.
+The deliverable is TypeScript.
+
+Part names are HYPOTHESES from measured bounds and must say so. On a rigged mesh the BONE names are
+the rig's own and must NOT carry that caveat.
+
+## Step 1 — Ask the bytes what the file is, before decoding it
+
+ python3 forge/stage1_intake/probe_glb.py <glb> --out glb-probe.json
+
+`skinCount` and `animationCount` decide the route:
+ · skinCount == 0 static: parts stay separate, an LOD ladder is allowed
+ · skinCount >= 1 rigged: read the skin, never author one beside it. See Step 3.
+ · skinCount > 1 choose one explicitly and say why
+ · animationCount > 0 clips are measured too, keyed to BONE INDEX, never to bone name
+
+## Step 2 — Measure, then force
+
+Take every parameter in the table above from the GLB and write the measured value into the spec.
+Where the pipeline would normally infer, it must not: name each forced field and the number it took.
+
+Keep vertices in the space the file put them in. For a rigged mesh that is BIND space — the space
+the inverse bind matrices are expressed in. Normalisation is a TRANSFORM, never an edit to the
+buffer: scale on the mesh so bones parented to it scale with the skin, offset on the group. Editing
+vertices to normalise moves the mesh out from under its own skeleton.
+
+Per-vertex colour is sampled from the base-colour TEXTURE at each vertex UV, not from a `color`
+attribute. A rigged GLB typically ships UVs and a texture and no vertex colours at all; reading only
+the attribute makes every vertex fall back to the flat base colour and the figure comes out white.
+The texture is sRGB bytes and the material factor is linear: apply the factor in linear space, then
+convert back.
+
+## Step 3 — If it is rigged, four rules, none negotiable
+
+1. ONE detail level. Do not decimate. Decimation rewrites the vertex list while `skinIndex` /
+ `skinWeight` are per-vertex — every weight would address a vertex that no longer exists and the
+ figure tears apart the moment a clip plays. It looks perfect until then.
+2. ONE skinned shell, not named parts. Rigging merges the mesh; advertising per-part pivots would be
+ a contract the geometry cannot honour. Expose the skeleton instead.
+3. Bones parents-first, `parent` as an INDEX with `-1` for a root, clip tracks keyed to bone index.
+ A clip naming a bone the skeleton does not have is DROPPED and named in the report — never bound
+ to whatever happens to sit at that index.
+4. `updateMatrixWorld(true)` BEFORE constructing the Skeleton. `calculateInverses()` reads each
+ bone's current world matrix; built in the wrong order it captures identity, the rest pose never
+ cancels, and the model renders a corpse while reporting `bound: true`.
+
+## Step 4 — Parity gates. These REPLACE the fidelity gates and are stricter, not looser.
+
+Report each as a number, not a verdict:
+
+ vertex count emitted vs measured EQUAL
+ triangle count emitted vs measured EQUAL
+ bounding box emitted vs measured within the quantisation step
+ base colour per part within the stated tolerance
+ roughness/metalness per part EQUAL to the measured value or median
+ Σ skin weights per vertex |Σw - 1| < 1e-5
+ skinIndex range every index < bone count
+ bone count emitted vs measured EQUAL
+ clip count emitted vs measured EQUAL, or the difference named clip by clip
+ clip duration per clip EQUAL
+ binding delta seek each clip to >= 5 times <= 2^-23
+
+The last one is the only check that separates a clip that PLAYS from one that merely exists, loads,
+holds an action and reports a duration while driving nothing.
+
+A parity gate that cannot be evaluated reports `unevaluated` with the missing input named. Never a
+pass.
+
+## Step 5 — Emit
+
+Factory, embedded surface data, codec and spec — all TypeScript, nothing fetched at runtime. With
+`Overwrite: yes`, replace the files for this demo id and KEEP its id, camera and registry entry;
+do not re-litigate settled decisions.
+
+## What NOT to do on this route
+
+ · do not run `--strict-quality`; it asks about inference and there is none here. Parity is the gate.
+ · do not enumerate a `detailInventory` for geometry the GLB already measured.
+ · do not smooth, re-topologise, weld or decimate. Those change the thing you are measuring.
+ · do not rename what the file already named.
+ · do not stop because a fidelity gate is unhappy. Stop when a PARITY gate fails.
+
+## Report
+
+Forced parameters and the value each took · vertex/triangle counts emitted vs measured · bounds
+delta · bone count · clips with durations · maxSampledBindingDelta per clip · LOD count · and one
+line naming what the GLB could not hand over, from the list above.
+````
diff --git a/docs/standard-prompts/polish.md b/docs/standard-prompts/polish.md
new file mode 100644
index 0000000..328227f
--- /dev/null
+++ b/docs/standard-prompts/polish.md
@@ -0,0 +1,58 @@
+# Polish — a build that renders but does not match
+
+For a model that already exists and already passes its gates, and is still wrong to look at.
+
+**Why polish used to stall:** told to "fix everything that does not match", an agent rewrites the
+factory, and the next render is different in ways nobody can attribute. This prompt fixes **one
+defect per cycle**, with the measurement before and after, so a change that made things worse is
+visible immediately instead of being buried under four other changes.
+
+````text
+Polish this img2threejs build against its reference. One defect per cycle.
+
+## Inputs
+- Factory: <PATH_TO_create<Name>Model.ts>
+- Spec: <PATH_TO_object-sculpt-spec.json>
+- Reference: <PATH_TO_REFERENCE>
+- Budget: <N> cycles # stop when spent, and report what is left
+
+## Cycle
+
+1. RENDER and package one reference-vs-render sheet. One sheet, not a scattering of screenshots.
+
+2. NAME the single worst defect in one sentence — what is wrong, where, and how you can tell.
+ Rank by identity impact, not by how easy it is to fix. A wrong silhouette outranks a wrong
+ gloss, always.
+
+3. MEASURE it before touching anything. Interior difference banded by height, ΔE00 for a colour,
+ silhouette IoU for a shape, per-region confidence for anything the view cannot show. Write the
+ number down. "It looks off" is not a measurement and cannot be checked afterwards.
+
+4. ATTRIBUTE it to a component id and a spec field. If you cannot name the field, you are guessing
+ — say so and pick the next defect instead of editing blind.
+
+5. FIX exactly that field. Do not touch a second component in the same cycle, however tempting.
+
+6. RE-MEASURE the same number. Three outcomes and all three are results:
+ improved -> keep it, record both numbers
+ unchanged -> revert it. The hypothesis was wrong; say what it was.
+ worse -> revert it, and say what that rules out.
+
+7. Re-run the gates that cover what you touched. Never lower a threshold to pass one.
+
+## Rules
+
+ · A cycle that reverts is a successful cycle. It bought information.
+ · Never fix two defects at once. Attribution is the whole value here.
+ · Never edit the generated factory by hand — edit the spec and regenerate, or the next
+ regeneration silently discards your work.
+ · If a defect traces to something the reference cannot show, stop and say so: no number of cycles
+ will resolve what the image does not contain.
+ · If the same defect survives two cycles, stop and report it. A third attempt is guessing.
+
+## Report
+
+Per cycle: defect · measured before · field changed · measured after · kept or reverted.
+Then: which defects remain, ranked, and which of them the reference cannot resolve.
+Say "improved", never "done", unless every ranked defect is closed.
+````
diff --git a/docs/standard-prompts/vfx.md b/docs/standard-prompts/vfx.md
new file mode 100644
index 0000000..724cfbb
--- /dev/null
+++ b/docs/standard-prompts/vfx.md
@@ -0,0 +1,96 @@
+# VFX — the effects layer for a character that already moves
+
+Use this once the rig and its clips exist and play. It is the effects pass, not a rigging pass.
+
+**Read this first: img2threejs has no particle subsystem.** There is no emitter type, no VFX gate,
+no effect registry. What the pipeline gives you is anchors, a destruction model, and — the part that
+matters most here — **a way to measure the clips instead of eyeballing them**:
+
+ actionProfile.sockets[] attachment / effect / grip / joint positions, in local coordinates
+ destruction{} breakable, fractureGroup, seamRefs, detachableFragments,
+ breakImpulse, debrisMaterial
+ material.emissive the glow channel
+ userData.sculptRuntime nodes, meshes, sockets, colliders, destructionGroups, height
+ userData.tick the per-frame hook
+
+Everything visual is code you write, in plain `three`. Say which parts are authored rather than
+measured — the same honesty rule the rest of the pipeline runs on, applied to effects.
+
+## The measuring machinery already exists — call it, don't rebuild it
+
+The prompt below asks you to sweep every clip through a real `AnimationMixer` rather than reading
+timings off a scrub bar. That harness is already emitted:
+
+- `emit_animation_runtime.py` emits `seek(name, t)` — play, pause, set time, `mixer.update(0)`,
+ `updateMatrixWorld(true)`. That is a real evaluation at a real time, which is exactly what Gate R1
+ uses to tell a clip that plays from one that merely exists.
+- `clip_features.py` already measures `handRange`, `footRange`, `stance` intervals and `poseReturn`
+ at N = 25 samples per clip.
+- Everything in this project is expressed as a fraction of figure height `H`, and
+ `userData.sculptRuntime.height` carries it. The prompt's "normalise to figure heights" is that
+ same convention, not a new one.
+
+## Anchoring — the rule that keeps effects alive through a rebuild
+
+Every effect binds to a socket, a bone, or a destruction group **that already exists in the spec**.
+No magic coordinates. If the anchor you need is not there, add it to the spec and regenerate — a
+`sockets[]` entry with an id and a local position — rather than hard-coding a vector into the effect
+code. A hard-coded position silently detaches the moment geometry is regenerated, and nothing warns
+you.
+
+On a rigged model an effect that must follow a limb binds to the **bone**, not to a pivot: rigging
+merges the mesh and the per-part pivots no longer reach the geometry.
+
+Additive blending for anything emissive; disable depth WRITE but keep depth TEST, or the effect
+punches a hole through the model it is attached to. One `userData.tick(dt, elapsed)` per effect
+group. The mixer takes the frame **delta** while the generic tick contract passes elapsed — say in a
+comment which one each call site is passing. Plain `three` only, no new dependency, no runtime
+fetch, and every effect disposable: geometry, material and texture released on teardown.
+
+## The prompt
+
+````text
+Build the effects layer for the character already in this showcase — the rig and its clips exist,
+only the VFX is missing.
+
+Start from the subject. Study what this character is and how its actions read in the world it
+comes from; the effects should belong to it, not to a generic effect kit. Then find the events —
+don't eyeball timings off a scrub bar. Sweep every embedded clip through a real AnimationMixer and
+measure where a strike actually stops at extension, where weight actually meets the ground, and
+where the body is driven by a force arriving from outside the clip. Normalise to figure heights so
+the table survives a change of scale.
+
+Build around the stop, not the travel — the interesting part of any impact is the instant it
+arrests. Schedule the effects against that measured table rather than a live "it just decelerated"
+test: scheduling fires on the exact frame, and it's the only way a windup can exist at all,
+because nothing else knows a strike is coming. Add hitstop; the clip itself slowing for a few tens
+of milliseconds is most of the felt impact.
+
+Give the character a small vocabulary of impact kinds and make them differ in motion first, colour
+second — a light hit that is only a paler heavy hit is still a heavy hit. Take the palette from
+the world the character lives in, not from an element wheel, and keep one contrasting accent so
+something in frame reads against the rest. A blow the character takes is not a strike played
+backwards: rings turn inward, debris comes off the body, no flash at the hand.
+
+Calibrate continuous layers — motion trails, breath, ambient drift — per clip against that clip's
+own measured speed; one global threshold smears the fast clips and leaves the slow ones bare. Pool
+everything, allocate nothing after construction, and start every object invisible so the viewer's
+framing pass never measures an effect. Then show me the loudest action, the quietest one, and a
+ground contact.
+````
+
+## Report
+
+The measured event table — clip, time, event kind, position in figure heights — before any effect
+exists, because everything downstream is scheduled against it. Then per effect: anchor
+(socket / bone / destruction group id), scale basis, blend mode, tick owner, disposal path. Finally
+one line naming what is authored rather than measured, and the frame cost you measured — not the one
+you expect.
+
+## For an object rather than a character
+
+An object has no clips to sweep, so there is no event table to measure and the whole scheduling
+argument does not apply. Anchor on the same sockets and destruction groups, drive from
+`userData.tick`, and break along the `seamRefs` and `detachableFragments` the spec already declares —
+`debrisMaterial` is authored there, so use it rather than inventing a second material that will
+drift from it.
diff --git a/forge/_shared/workflow_state.py b/forge/_shared/workflow_state.py
index cf24c34..0172bd7 100644
--- a/forge/_shared/workflow_state.py
+++ b/forge/_shared/workflow_state.py
@@ -78,6 +78,65 @@ FINAL_STEPS: Final = (
("action-ready", "Verify explodable/clickable hierarchy, pivots, sockets, and root.userData.sculptRuntime"),
)
+# Stage R -- rigging and animation, docs/pipelines/character-rigging-animation-1.5.2.md.
+#
+# These exist as a checklist scope because the 1.5.2 gates were reachable only by hand: every
+# module under forge/stage5_rig/ was callable, and nothing in the workflow ever told anyone to
+# call one. A gate that nothing invokes reports a clean verdict forever, which is the exact
+# failure the whole gate system exists to end.
+#
+# The ORDER is load-bearing and is not a preference:
+# - mesh repair happens BEFORE the freeze, because a mesh may legitimately need fixing;
+# - the freeze happens BEFORE any rig work, because after it the geometry is evidence;
+# - mesh-parity is verified AFTER binding, because that is the only moment the claim
+# "implementation did not touch the mesh" can be falsified.
+# Moving the freeze later would let a bind quietly rewrite vertices and then freeze the result,
+# and the manifest would certify the damage instead of catching it.
+RIG_STEPS: Final = (
+ (
+ "rig-contract-read",
+ "Read grimoire/readiness/animation_contract.md and docs/pipelines/character-rigging-animation-1.5.2.md completely",
+ ),
+ (
+ "glb-rig-reference",
+ "python3 forge/stage5_rig/glb_rig_reference.py {reference} --out glb-rig.json "
+ "(skeleton, skin joint order, inverse binds and clips read FROM the GLB; skip with a reason only when there is no GLB)",
+ ),
+ (
+ "mesh-repair",
+ "Inspect the meshes for breakage and repair them now, before the freeze; "
+ "record what was repaired, or skip with a reason when nothing is broken",
+ ),
+ (
+ "mesh-freeze",
+ "node runtime/scripts/export_mesh_buffers.mjs --url <preview> --out meshes.json && "
+ "python3 forge/stage5_rig/mesh_parity.py freeze meshes.json --out mesh-manifest.json",
+ ),
+ (
+ "rig-payload-validate",
+ "python3 forge/stage5_rig/validate_rig_payload.py --payload rig-payload.json "
+ "(structural payload integrity ONLY -- never pose stress or likeness; a sculpt spec is NOT "
+ "a rig payload, they are different schemas)",
+ ),
+ (
+ "rig-bind",
+ "Bind the skeleton: ADD skeleton, skinIndex and skinWeight only. Vertex positions, normals, uvs and indices are frozen evidence",
+ ),
+ (
+ "mesh-parity-verify",
+ "node runtime/scripts/export_mesh_buffers.mjs --url <preview> --out meshes-after.json && "
+ "python3 forge/stage5_rig/mesh_parity.py verify mesh-manifest.json meshes-after.json",
+ ),
+ (
+ "clip-measure",
+ "python3 forge/stage5_rig/clip_features.py sampled-clips.json (measure, classify, name, and decide loop from poseReturn)",
+ ),
+ (
+ "rig-gates",
+ "python3 forge/stage5_rig/rig_gates.py rig-gate-payload.json (G1-G10; an unevaluated gate is not a pass)",
+ ),
+)
+
class WorkflowStateError(ValueError):
pass
@@ -102,15 +161,15 @@ def new_state(
max_per_pass: int = 3,
max_total: int = 6,
) -> dict[str, Any]:
- if profile not in {"generic", "cs2", "character"}:
- raise WorkflowStateError("profile must be generic, cs2, or character")
+ if profile not in {"generic", "cs2", "character", "animated-character"}:
+ raise WorkflowStateError("profile must be generic, cs2, character, or animated-character")
if max_per_pass < 1 or max_total < 1 or max_per_pass > max_total:
raise WorkflowStateError("loop limits require 1 <= max-per-pass <= max-total")
setup = [_step(*item, scope="setup") for item in SETUP_STEPS]
insertion = next(index for index, item in enumerate(setup) if item["id"] == "local-spec-search")
if profile == "cs2":
setup[insertion:insertion] = [_step(*item, scope="setup") for item in CS2_STEPS]
- elif profile == "character":
+ elif profile in {"character", "animated-character"}:
setup[insertion:insertion] = [_step(*item, scope="setup") for item in CHARACTER_STEPS]
pass_steps = list(PASS_STEPS)
if profile == "cs2":
@@ -124,7 +183,12 @@ def new_state(
"currentPass": "",
"checklist": setup
+ [_step(*item, scope="pass") for item in pass_steps]
- + [_step(*item, scope="final") for item in FINAL_STEPS],
+ + [_step(*item, scope="final") for item in FINAL_STEPS]
+ + (
+ [_step(*item, scope="rig") for item in RIG_STEPS]
+ if profile == "animated-character"
+ else []
+ ),
"loops": {
"perPass": {},
"total": 0,
@@ -146,7 +210,7 @@ def validate_state(state: Any) -> dict[str, Any]:
raise WorkflowStateError("state must be a JSON object")
if state.get("schemaVersion") != SCHEMA_VERSION:
raise WorkflowStateError(f"unsupported state schemaVersion: {state.get('schemaVersion')!r}")
- if state.get("profile") not in {"generic", "cs2", "character"}:
+ if state.get("profile") not in {"generic", "cs2", "character", "animated-character"}:
raise WorkflowStateError("state profile is invalid")
checklist = state.get("checklist")
if not isinstance(checklist, list) or not checklist:
@@ -158,7 +222,7 @@ def validate_state(state: Any) -> dict[str, Any]:
if entry["id"] in seen:
raise WorkflowStateError(f"duplicate checklist step: {entry['id']}")
seen.add(entry["id"])
- if entry.get("scope") not in {"setup", "pass", "final"}:
+ if entry.get("scope") not in {"setup", "pass", "final", "rig"}:
raise WorkflowStateError(f"invalid checklist scope for {entry['id']}")
if entry.get("status") not in STEP_STATUSES:
raise WorkflowStateError(f"invalid checklist status for {entry['id']}")
@@ -246,7 +310,15 @@ def next_entry(state: dict[str, Any]) -> dict[str, Any] | None:
"command": "python3 forge/next.py --state .img2threejs/state.json {spec}",
}
final_pending = _pending(_entries(state, "final"))
- return final_pending[0] if final_pending else None
+ if final_pending:
+ return final_pending[0]
+ # Stage R runs LAST, after the static model is complete and its coverage gates have passed:
+ # rigging is additive to a finished mesh, and binding a model whose parts are still moving
+ # would freeze geometry that has not settled. Dispatching it here is what makes the rig steps
+ # reachable at all -- a checklist entry no dispatcher returns is a step `next.py` never asks
+ # for, which is the same defect as a gate nothing invokes.
+ rig_pending = _pending(_entries(state, "rig"))
+ return rig_pending[0] if rig_pending else None
def recompute(state: dict[str, Any]) -> None:
@@ -383,7 +455,7 @@ def status_payload(state: dict[str, Any]) -> dict[str, Any]:
entry = next_entry(state)
current_pass = str(state.get("currentPass") or "")
loops = state["loops"]
- visible_scopes = {"setup", "final"}
+ visible_scopes = {"setup", "final", "rig"}
if current_pass != "complete":
visible_scopes.add("pass")
return {
diff --git a/forge/stage3_build/generate_threejs_factory.py b/forge/stage3_build/generate_threejs_factory.py
index 40431dd..1b2f122 100644
--- a/forge/stage3_build/generate_threejs_factory.py
+++ b/forge/stage3_build/generate_threejs_factory.py
@@ -2235,7 +2235,19 @@ def _rig_weight_function_lines(spec: dict[str, Any], ordered: list[dict[str, Any
" const position = mesh.geometry.getAttribute('position');",
" if (!position) continue;",
" mesh.updateWorldMatrix(true, false);",
+ " // applyMatrix4 mutates the vertex buffer in place and is NOT idempotent: running it",
+ " // twice on one geometry applies the world matrix squared, and every component lands",
+ " // somewhere it has no reason to be -- the model reads as blown apart rather than",
+ " // wrong. Throw rather than skip, because a silent skip would leave a mesh in the",
+ " // wrong space and the failure would resurface later as a subtler misplacement.",
+ " if (mesh.geometry.userData.worldBaked) {",
+ " throw new Error(",
+ " `geometry for '${boneId}' is already world-baked; baking twice squares the ` +",
+ " 'world matrix and scatters the parts. Build a fresh factory instead of re-binding.'",
+ " );",
+ " }",
" mesh.geometry.applyMatrix4(mesh.matrixWorld);",
+ " mesh.geometry.userData.worldBaked = true;",
" root.add(mesh);",
" mesh.position.set(0, 0, 0);",
" mesh.quaternion.identity();",
diff --git a/forge/stage5_rig/CONTRACT_1.5.2.md b/forge/stage5_rig/CONTRACT_1.5.2.md
new file mode 100644
index 0000000..659b416
--- /dev/null
+++ b/forge/stage5_rig/CONTRACT_1.5.2.md
@@ -0,0 +1,72 @@
+# Stage R — 1.5.2 implementation contract
+
+The spec is `docs/pipelines/character-rigging-animation-1.5.2.md`. This file fixes the
+**module boundaries and payload shapes** so the R-stage modules compose without importing
+three.js and without a renderer. Every module here is pure Python 3.10+ stdlib.
+
+Everything is expressed as a fraction of **figure height H**. A payload carries `H`
+explicitly; no module may assume `H == 1.0`.
+
+## Sampled-clip payload (the only animation input format)
+
+Produced by a host that can evaluate a rig (three.js, Blender, a test fixture). Positions
+are **world** space, already divided by nothing — modules normalise by `H` themselves.
+
+```json
+{
+ "figureHeight": 1.0,
+ "landmarks": ["hip", "head", "hand.l", "hand.r", "foot.l", "foot.r"],
+ "clips": [
+ {
+ "sourceName": "NlaTrack.003",
+ "duration": 2.833,
+ "sampleTimes": [0.0, "... N = 25 evenly spaced ..."],
+ "landmarkPositions": {
+ "hip": [[x, y, z], "... N entries ..."],
+ "head": [[x, y, z], "..."]
+ },
+ "jointScaleDelta": [0.0, "... N entries, max |scale_j(t) - 1| over joints ..."],
+ "poseReturn": 0.0,
+ "stance": {"foot.l": [[t0, t1]], "foot.r": [[t0, t1]]}
+ }
+ ]
+}
+```
+
+- `sampleTimes` length == every `landmarkPositions[*]` length == `jointScaleDelta` length.
+- `poseReturn` is degrees: max per-joint rotation delta between `t = 0` and `t = duration`.
+ A host that cannot measure it omits the key; modules must then report `loop: null`
+ ("undecidable"), never guess `false`.
+- `stance` is optional; only Gate G8 needs it. Intervals are in seconds.
+
+## Module map — one owner per file, no cross-writes
+
+| File | Owns | Public API |
+|---|---|---|
+| `clip_features.py` | §1 vocabulary, §2 classifier, §3 naming, §4 loop rule | `measure_clip`, `ClipFeatures`, `classify`, `decide_loop`, `name_clip`, `ClipName`, `load_payload` |
+| `skin_conditioning.py` | §R2 proximity weight blending + Gate R2 | `blend_weights`, `SkinBinding`, `BlendReport`, `validate_binding` |
+| `action_design.py` | §R4 targets, primitives, chain resolution, footSlide | `walk_targets`, `run_targets`, `TargetBand`, `accepts`, `resolve_chains`, `foot_slide` |
+| `rig_gates.py` | §R6 G1–G10 runner | `run_gates`, `GateResult`, `GateReport` |
+| `emit_animation_runtime.py` | §R5 controller/ticker TS emitter | `emit_animation_runtime` |
+
+`rig_gates.py` imports from `clip_features`, `skin_conditioning` and `action_design`.
+Nothing imports from `rig_gates`. No other file in `forge/` is edited by these modules.
+
+## Shared numeric conventions
+
+- Tolerances are module constants with the spec's name: `BINDING_EPSILON = 2 ** -23`,
+ `WEIGHT_SUM_TOLERANCE = 2e-7`, `BIND_RESTORE_TOLERANCE = 1e-12`, `FOOT_SLIDE_LIMIT = 0.01`,
+ `POSE_RETURN_DEGREES = 0.5`, `LOOP_HIP_TOLERANCE = 0.01`, `BLEND_RADIUS = 0.006`.
+- Every threshold carrying `single-subject` in the spec is exported as a **named default
+ that a caller can override**, and the dataclass records the value actually used.
+- A module never prints. CLIs (`if __name__ == "__main__"`) write JSON to stdout and use
+ exit code 1 on gate failure, matching `validate_rig_payload.py`.
+
+## Honesty rules that are load-bearing
+
+- `classify` returns **all** matching labels (a clip can be `in-place` + `planted` +
+ `gesture`), plus a primary motion class. It never invents a class for an empty match.
+- `name_clip` sets `inferred: true` whenever the label wording implies intent, and keeps
+ `sourceName` verbatim.
+- Any gate that cannot be evaluated because its input is absent reports
+ `status: "unevaluated"` with a reason. It is never silently a pass.
diff --git a/forge/stage5_rig/action_design.py b/forge/stage5_rig/action_design.py
new file mode 100644
index 0000000..0b94aed
--- /dev/null
+++ b/forge/stage5_rig/action_design.py
@@ -0,0 +1,2158 @@
+#!/usr/bin/env python3
+"""Stage R4 — action design: target bands, gait primitives, chain resolution, footSlide.
+
+Spec: `docs/pipelines/character-rigging-animation-1.5.2.md`, Stage R4, read against §1
+(the measurement vocabulary) and §2 (the classifier), because R4's acceptance test IS the
+§2 classifier: a designed clip is accepted only when the classifier — which is never told
+what the clip was meant to be — independently reports the intended class.
+
+ target features -> author tracks -> measure with §1 -> compare -> iterate
+
+**"Looks right" is not a criterion.** Nothing in this module accepts a clip on the strength
+of an eyeball. Every criterion in `Acceptance` is a number compared against a band, and a
+criterion whose input is missing reports `unevaluated` with a reason — never a silent pass.
+
+Module boundary: `forge/stage5_rig/CONTRACT_1.5.2.md`. This file owns §R4 targets,
+primitives, chain resolution and footSlide. It does NOT own the feature vocabulary or the
+classifier — those live in `clip_features.py` and are imported defensively below.
+
+Everything is a fraction of figure height H. No function here assumes `H == 1.0`.
+
+Pure Python 3.10+ stdlib. No pip installs, no three.js, no renderer.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from dataclasses import dataclass, field
+from typing import Any, Callable, Iterable, Literal, Mapping, Optional, Sequence
+
+# --------------------------------------------------------------------------------------
+# Sibling module, imported defensively.
+#
+# `clip_features.py` (§1 vocabulary, §2 classifier) is owned by another author and may land
+# after this file. The import is guarded with a bare `except Exception` rather than
+# `except ImportError` on purpose: a module that exists but is half-written raises whatever
+# its own body raises, and this module must still import so its own tests can run. Callers
+# can always inject `measure` / `classifier` explicitly, which is what the tests do.
+# --------------------------------------------------------------------------------------
+
+try: # pragma: no cover - presence depends on the sibling module landing
+ from clip_features import ( # type: ignore # noqa: F401
+ ClipFeatures,
+ classify as _clip_features_classify,
+ measure_clip as _clip_features_measure,
+ )
+
+ CLIP_FEATURES_AVAILABLE = True
+except Exception: # noqa: BLE001 - see comment above
+ ClipFeatures = None # type: ignore[assignment]
+ _clip_features_classify = None # type: ignore[assignment]
+ _clip_features_measure = None # type: ignore[assignment]
+ CLIP_FEATURES_AVAILABLE = False
+
+
+def default_measure() -> Optional[Callable[..., Any]]:
+ """`clip_features.measure_clip` if it is importable, else None (never a stub)."""
+ return _clip_features_measure
+
+
+def default_classifier() -> Optional[Callable[..., Any]]:
+ """`clip_features.classify` if it is importable, else None (never a stub)."""
+ return _clip_features_classify
+
+
+# --------------------------------------------------------------------------------------
+# Named tolerances (CONTRACT_1.5.2.md "Shared numeric conventions"). Every one is a module
+# constant carrying the spec's own name, and every one is overridable at the call site.
+# --------------------------------------------------------------------------------------
+
+FOOT_SLIDE_LIMIT = 0.01
+"""Gate R4 / G8: `footSlide <= 0.01H` during every stance frame."""
+
+POSE_RETURN_DEGREES = 0.5
+"""§4: `loop <=> poseReturn <= 0.5 deg per rotation joint`."""
+
+SYMMETRY_TOLERANCE = 1e-4
+"""Mirrored-local-X tolerance used to pair left/right chains. Absolute, in model units."""
+
+FOOT_RANGE_TOLERANCE = 0.30
+"""Reading chosen for the spec's `footRange ~= travel / 2`.
+
+The spec writes `~=` and gives no band. +/-30% is the reading taken here, and it has to be
+at least +/-20% for a reason worth stating rather than smoothing over: a gait built as a
+phase machine puts the hip-relative foot excursion at `contactFraction x travel`, which is
+1.2x the spec's figure at the walk contact fraction of 0.60 and 0.8x at the run's 0.40.
+`travel / 2` is the *step* length between alternating footfalls; §1's `footRange` is a
+per-axis positional range. They are not the same quantity. See LIMB_FEATURE_FRAME.
+"""
+
+MEDIAL_AXIS_TOLERANCE: Optional[float] = None
+"""Default absolute tolerance for "the spine sits on the midline". None = do not check.
+
+Left deliberately off by default: the spine-medial check needs an absolute model-unit
+tolerance, and inventing one from H would make `check_medial_lateral` fail on rigs that are
+merely built off-origin. Callers with a known H pass `medial_tolerance=0.02 * H`.
+"""
+
+LIMB_FEATURE_FRAME = "hip-relative"
+"""The frame the `handRange` / `footRange` bands in §R4's worked example are stated in.
+
+§1 defines both as world-space per-axis ranges **pooled over both limbs**. Two properties
+of that definition put the spec's authoring bands out of reach, and `clip_features`
+documents both on `measure_clip` itself:
+
+1. World space carries the root along, so a forward-travelling gait gives
+ `footRange ~= travel` and `handRange ~= travel + swing`. Neither can land in the spec's
+ `0.15H-0.25H` / `~travel/2` bands at any speed.
+2. Pooling both limbs puts the *lateral separation* between them inside the number. Two
+ hands held 0.18H apart and swung 0.20H measure whichever is larger, so an authoring
+ band on the swing reads the stance width instead.
+
+`band_features()` therefore measures these two against a hip-relative clip and takes each
+limb's own largest axis range (`ClipFeatures.landmark_ranges`, which exists for exactly
+this) rather than the pooled figure. This changes nothing about §2: the classifier is
+always handed the world-space, pooled `ClipFeatures`, because those are the numbers its
+thresholds were derived from. The global features (`duration`, `travel`, `rise`, `speed`,
+`scaleDelta`, `poseReturn`) stay in world space too.
+"""
+
+MOTION_CLASSES = ("idle", "walk", "run", "dash", "jump", "leap")
+"""§2's primary motion classes. `in-place`, `planted` and `gesture` are modifiers, not
+primaries — a clip can carry several at once (CONTRACT: "classify returns all matching
+labels ... plus a primary motion class")."""
+
+Status = Literal["pass", "fail", "unevaluated"]
+
+
+# --------------------------------------------------------------------------------------
+# Small vector helpers (stdlib only; no numpy)
+# --------------------------------------------------------------------------------------
+
+Vec3 = tuple[float, float, float]
+
+
+def _vec3(value: Any, label: str) -> Vec3:
+ if not isinstance(value, (list, tuple)) or len(value) != 3:
+ raise ValueError(f"{label} must be a length-3 vector, got {value!r}")
+ out = tuple(float(component) for component in value)
+ if not all(math.isfinite(component) for component in out):
+ raise ValueError(f"{label} must be finite, got {value!r}")
+ return out # type: ignore[return-value]
+
+
+def _distance(a: Vec3, b: Vec3) -> float:
+ return math.sqrt((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2)
+
+
+def _add(a: Vec3, b: Vec3) -> Vec3:
+ return (a[0] + b[0], a[1] + b[1], a[2] + b[2])
+
+
+# --------------------------------------------------------------------------------------
+# Feature access — tolerant of ClipFeatures' exact field naming
+# --------------------------------------------------------------------------------------
+
+FEATURE_ALIASES: dict[str, tuple[str, ...]] = {
+ "duration": ("duration",),
+ "travel": ("travel",),
+ "rise": ("rise",),
+ "speed": ("speed",),
+ "handRange": ("handRange", "hand_range"),
+ "footRange": ("footRange", "foot_range"),
+ "headRise": ("headRise", "head_rise"),
+ "scaleDelta": ("scaleDelta", "scale_delta"),
+ "poseReturn": ("poseReturn", "pose_return"),
+ "footSlide": ("footSlide", "foot_slide"),
+ "contact": ("contact", "contactFraction", "contact_fraction"),
+}
+
+
+def feature_value(features: Any, name: str) -> Optional[float]:
+ """Read one §1 feature off a `ClipFeatures`, a dict, or anything with attributes.
+
+ Returns None when the feature is genuinely absent — which is what makes a criterion
+ `unevaluated` rather than a pass. `clip_features.ClipFeatures` may spell its fields in
+ either snake_case or camelCase; both are tried, so this module does not have to guess
+ the sibling's house style at import time.
+ """
+ for alias in FEATURE_ALIASES.get(name, (name,)):
+ if isinstance(features, Mapping):
+ if alias in features:
+ value = features[alias]
+ return None if value is None else float(value)
+ else:
+ value = getattr(features, alias, None)
+ if value is not None:
+ return float(value)
+ return None
+
+
+_CANONICAL_BY_ALIAS: dict[str, str] = {
+ alias: canonical for canonical, aliases in FEATURE_ALIASES.items() for alias in aliases
+}
+
+
+class _FeatureView:
+ """Attribute access over a feature mapping, so §2's classifier can read a plain dict.
+
+ `clip_features.classify` reads `features.travel`, `features.speed` and friends off a
+ `ClipFeatures`. A caller holding a measured-features JSON document has a dict instead.
+ This adapts one to the other without copying §2's threshold logic anywhere.
+
+ A feature that is genuinely absent raises `AttributeError` rather than reading as zero —
+ a classifier silently told `travel = 0` returns `idle` with full confidence.
+ """
+
+ __slots__ = ("_values",)
+
+ def __init__(self, values: Mapping[str, Any]) -> None:
+ self._values = values
+
+ def __getattr__(self, name: str) -> float:
+ value = feature_value(self._values, _CANONICAL_BY_ALIAS.get(name, name))
+ if value is None:
+ raise AttributeError(
+ f"the measured features carry no {name!r}; §2 cannot classify without it "
+ f"(present: {sorted(self._values)})"
+ )
+ return value
+
+ def __repr__(self) -> str: # pragma: no cover - diagnostics only
+ return f"_FeatureView({dict(self._values)!r})"
+
+
+def as_classifier_input(features: Any) -> Any:
+ """Whatever §2's classifier needs, from whatever the caller has.
+
+ A `ClipFeatures` passes straight through; a mapping is wrapped in `_FeatureView`.
+ """
+ return _FeatureView(features) if isinstance(features, Mapping) else features
+
+
+def classifier_verdict(result: Any) -> tuple[Optional[str], tuple[str, ...]]:
+ """Normalise whatever `classify` returned into `(primary_class, all_labels)`.
+
+ CONTRACT_1.5.2.md says `classify` returns all matching labels plus a primary motion
+ class, but not the container. Every plausible shape is accepted here rather than
+ pinning the sibling's return type: a bare string, a sequence of labels, a
+ `(primary, labels)` pair, a mapping, or a dataclass with `primary` / `labels` fields.
+ An empty match stays empty — CONTRACT: "It never invents a class for an empty match."
+ """
+ if result is None:
+ return None, ()
+ if isinstance(result, str):
+ return (result if result in MOTION_CLASSES else None), (result,)
+ if isinstance(result, Mapping):
+ primary = result.get("primary") or result.get("motionClass") or result.get("motion_class")
+ labels = result.get("labels") or result.get("classes") or result.get("matches") or ()
+ return (str(primary) if primary else None), tuple(str(label) for label in labels)
+ # (primary, labels) pair
+ if isinstance(result, (list, tuple)) and len(result) == 2 and isinstance(result[0], (str, type(None))):
+ if isinstance(result[1], (list, tuple, set, frozenset)):
+ primary = result[0]
+ labels = tuple(str(label) for label in result[1])
+ return (str(primary) if primary else None), labels
+ if isinstance(result, (list, tuple, set, frozenset)):
+ labels = tuple(str(label) for label in result)
+ primary = next((label for label in labels if label in MOTION_CLASSES), None)
+ return primary, labels
+ # dataclass / plain object
+ primary = getattr(result, "primary", None) or getattr(result, "motion_class", None) or getattr(result, "motionClass", None)
+ labels_attr = getattr(result, "labels", None) or getattr(result, "classes", None) or ()
+ labels = tuple(str(label) for label in labels_attr)
+ if primary is None and labels:
+ primary = next((label for label in labels if label in MOTION_CLASSES), None)
+ if primary is not None and str(primary) not in labels:
+ labels = (str(primary),) + labels
+ return (str(primary) if primary else None), labels
+
+
+# --------------------------------------------------------------------------------------
+# Chain resolution — from topology, never from names
+# --------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class JointNode:
+ """One joint in the input hierarchy: id, parent, and position local to the parent."""
+
+ id: str
+ parent: Optional[str]
+ local_position: Vec3
+
+
+@dataclass(frozen=True)
+class Chain:
+ """One resolved chain: an ordered joint path from an anchor to a leaf."""
+
+ name: str
+ joint_ids: tuple[str, ...]
+ anchor_position: Vec3
+ """World (model-space) position of `joint_ids[0]`. This is what Gate G7 compares."""
+
+ @property
+ def anchor(self) -> str:
+ return self.joint_ids[0]
+
+ @property
+ def leaf(self) -> str:
+ return self.joint_ids[-1]
+
+
+@dataclass(frozen=True)
+class Chains:
+ """The resolved chain set for one rig, plus how each side label was decided."""
+
+ spine: Chain
+ arm: dict[str, Chain]
+ leg: dict[str, Chain]
+ world_positions: dict[str, Vec3]
+ side_source: str
+ """`"labels"` when the caller supplied an independent left/right claim, `"model-x"`
+ when this module fell back to assigning left = positive X. See `gate_is_independent`."""
+ symmetry_tolerance: float
+ notes: tuple[str, ...] = ()
+
+ @property
+ def gate_is_independent(self) -> bool:
+ """True when `check_medial_lateral` is capable of failing.
+
+ The medial/lateral gate compares a *claim* about which chain is the left one
+ against the *geometry*. When `side_source == "model-x"` the claim was derived from
+ that same geometry, so the comparison is a tautology and passes by construction —
+ it is still run, and still catches a pair that is not mirrored at all, but it can
+ no longer catch a mirrored rig. Pass `side_labels=` to `resolve_chains` (from the
+ source rig's own naming, or from an explicit map) to give the gate teeth.
+ """
+ return self.side_source == "labels"
+
+ def __getitem__(self, name: str) -> Chain:
+ if name == "spine":
+ return self.spine
+ group, _, side = name.partition(".")
+ if group == "arm" and side in self.arm:
+ return self.arm[side]
+ if group == "leg" and side in self.leg:
+ return self.leg[side]
+ raise KeyError(name)
+
+ def all_chains(self) -> tuple[Chain, ...]:
+ return (self.spine, self.arm["l"], self.arm["r"], self.leg["l"], self.leg["r"])
+
+
+class ChainResolutionError(ValueError):
+ """Raised when the hierarchy does not present the structure R4 needs.
+
+ Fail-closed on purpose (same discipline as `rig_spec.validate_rig_spec`): a chain
+ resolver that guesses produces an action authored onto the wrong joints, which is
+ exactly the class of failure §0 says is total and silent.
+ """
+
+
+def _coerce_nodes(nodes: Iterable[Any]) -> list[JointNode]:
+ coerced: list[JointNode] = []
+ for index, node in enumerate(nodes):
+ if isinstance(node, JointNode):
+ coerced.append(node)
+ continue
+ if isinstance(node, Mapping):
+ node_id = node.get("id") or node.get("name")
+ parent = node.get("parent")
+ position = node.get("local_position", node.get("localPosition", node.get("position")))
+ elif isinstance(node, (list, tuple)) and len(node) == 3:
+ node_id, parent, position = node
+ else:
+ raise ChainResolutionError(f"node {index} is not a JointNode, mapping or 3-tuple: {node!r}")
+ if not node_id:
+ raise ChainResolutionError(f"node {index} has no id")
+ coerced.append(
+ JointNode(
+ id=str(node_id),
+ parent=None if parent in (None, "") else str(parent),
+ local_position=_vec3(position, f"node {node_id!r} local_position"),
+ )
+ )
+ return coerced
+
+
+def _children_map(nodes: Sequence[JointNode]) -> dict[str, list[str]]:
+ children: dict[str, list[str]] = {node.id: [] for node in nodes}
+ for node in nodes:
+ if node.parent is None:
+ continue
+ if node.parent not in children:
+ raise ChainResolutionError(f"joint {node.id!r} has unresolved parent {node.parent!r}")
+ children[node.parent].append(node.id)
+ return children
+
+
+def _world_positions(nodes: Sequence[JointNode]) -> dict[str, Vec3]:
+ by_id = {node.id: node for node in nodes}
+ world: dict[str, Vec3] = {}
+
+ def resolve(node_id: str, seen: frozenset[str]) -> Vec3:
+ if node_id in world:
+ return world[node_id]
+ if node_id in seen:
+ raise ChainResolutionError(f"cycle in the joint hierarchy through {node_id!r}")
+ node = by_id[node_id]
+ if node.parent is None:
+ world[node_id] = node.local_position
+ else:
+ world[node_id] = _add(resolve(node.parent, seen | {node_id}), node.local_position)
+ return world[node_id]
+
+ for node in nodes:
+ resolve(node.id, frozenset())
+ return world
+
+
+def _descend_to_branch(start: str, children: Mapping[str, list[str]]) -> list[str]:
+ """Walk the single-child chain from `start` until a branch or a leaf. Inclusive."""
+ path = [start]
+ current = start
+ while len(children[current]) == 1:
+ current = children[current][0]
+ path.append(current)
+ return path
+
+
+def _deepest_leaf_path(start: str, children: Mapping[str, list[str]], world: Mapping[str, Vec3]) -> list[str]:
+ """Path from `start` to the leaf of its longest sub-chain.
+
+ Ties are broken deterministically — longest joint count, then greatest accumulated
+ segment length, then lexicographic id — so a hand that branches into fingers resolves
+ to the same leaf on every run rather than to whichever child happened to be first.
+ """
+
+ def walk(node_id: str) -> tuple[int, float, list[str]]:
+ kids = children[node_id]
+ if not kids:
+ return 1, 0.0, [node_id]
+ best: Optional[tuple[int, float, list[str]]] = None
+ for kid in sorted(kids):
+ depth, length, path = walk(kid)
+ segment = _distance(world[node_id], world[kid])
+ candidate = (depth + 1, length + segment, [node_id] + path)
+ if best is None or (candidate[0], candidate[1]) > (best[0], best[1]):
+ best = candidate
+ assert best is not None
+ return best
+
+ return walk(start)[2]
+
+
+def _mirror_pairs(
+ candidates: Sequence[str],
+ local: Mapping[str, Vec3],
+ tolerance: float,
+) -> tuple[list[tuple[str, str]], list[str]]:
+ """Partition sibling joints into mirrored-local-X pairs plus the unpaired remainder."""
+ unused = list(candidates)
+ pairs: list[tuple[str, str]] = []
+ while unused:
+ a = unused.pop(0)
+ ax, ay, az = local[a]
+ if abs(ax) <= tolerance:
+ continue # on the midline: medial, cannot be half of a lateral pair
+ match: Optional[str] = None
+ for b in unused:
+ bx, by, bz = local[b]
+ if abs(ax + bx) <= tolerance and abs(ay - by) <= tolerance and abs(az - bz) <= tolerance:
+ match = b
+ break
+ if match is not None:
+ unused.remove(match)
+ pairs.append((a, match))
+ paired = {joint for pair in pairs for joint in pair}
+ unpaired = [joint for joint in candidates if joint not in paired]
+ return pairs, unpaired
+
+
+def resolve_chains(
+ nodes: Iterable[Any],
+ side_labels: Optional[Mapping[str, str]] = None,
+ symmetry_tolerance: float = SYMMETRY_TOLERANCE,
+) -> Chains:
+ """Resolve `spine`, `arm.{l,r}` and `leg.{l,r}` from the hierarchy's shape.
+
+ §R4: "Author on **chains**, not individual joints. Resolve from topology." Nothing here
+ reads a joint name, and Stage R0 gives the reason: "Do not infer from names ... clips
+ target technical nodes that are not joints". A rig whose joints are called `node_17`
+ resolves exactly as well as one called `clavicle.l`.
+
+ The shape being matched:
+
+ root -> (single-child chain) -> HIP BRANCH first node with >= 2 children
+ the mirrored-X child pair here -> leg.{l,r}, each descending to a foot leaf
+ the medial child here -> spine, continuing upward to
+ SHOULDER BRANCH next node with >= 2 children
+ the mirrored-X child pair here -> arm.{l,r}, each descending to a hand leaf
+ the medial child here -> the rest of the spine, ending at the head leaf
+
+ SIDE LABELS — the ambiguity worth naming. Topology gives the *pair*; it cannot give
+ which half is "left". That is a labelling claim, and it has to come from outside the
+ geometry or the medial/lateral gate below becomes a tautology. `side_labels` maps any
+ joint id in a chain to `"l"` or `"r"` (typically read off the source rig's own naming,
+ which is precisely the claim a mirrored rig gets wrong). Without it this function falls
+ back to left = positive model X, records `side_source="model-x"`, and
+ `Chains.gate_is_independent` reports False so no caller mistakes the resulting pass for
+ evidence.
+
+ Raises `ChainResolutionError` rather than guessing when the hierarchy does not present
+ two branch points with a mirrored pair at each.
+ """
+ node_list = _coerce_nodes(nodes)
+ if not node_list:
+ raise ChainResolutionError("no joints supplied")
+ roots = [node.id for node in node_list if node.parent is None]
+ if len(roots) != 1:
+ raise ChainResolutionError(f"expected exactly one root joint, found {len(roots)}: {sorted(roots)}")
+ root = roots[0]
+
+ children = _children_map(node_list)
+ world = _world_positions(node_list)
+ local = {node.id: node.local_position for node in node_list}
+ notes: list[str] = []
+
+ hip_path = _descend_to_branch(root, children)
+ hip = hip_path[-1]
+ if len(children[hip]) < 2:
+ raise ChainResolutionError(
+ f"no branch point below the root: the chain from {root!r} ends at leaf {hip!r}. "
+ "R4 needs a hip branch (legs + spine) and a shoulder branch (arms + neck)."
+ )
+
+ hip_pairs, hip_medial = _mirror_pairs(children[hip], local, symmetry_tolerance)
+ if not hip_pairs:
+ raise ChainResolutionError(
+ f"hip branch {hip!r} has no mirrored-X child pair within {symmetry_tolerance} "
+ f"(children: {sorted(children[hip])}) — cannot resolve leg.l / leg.r"
+ )
+ if len(hip_pairs) > 1:
+ # More than one lateral pair at the hip (legs plus, say, tails or skirt bones).
+ # The legs are the pair whose leaves sit lowest; the rest are recorded, not silently
+ # dropped, so a reader can see the resolver made a choice.
+ hip_pairs.sort(key=lambda pair: min(world[_deepest_leaf_path(joint, children, world)[-1]][1] for joint in pair))
+ notes.append(
+ f"hip branch {hip!r} had {len(hip_pairs)} mirrored pairs; took the lowest-leaved pair as the legs"
+ )
+ leg_pair = hip_pairs[0]
+
+ if not hip_medial:
+ raise ChainResolutionError(
+ f"hip branch {hip!r} has no medial child to continue the spine through "
+ f"(children: {sorted(children[hip])})"
+ )
+ if len(hip_medial) > 1:
+ hip_medial.sort(key=lambda joint: -world[_deepest_leaf_path(joint, children, world)[-1]][1])
+ notes.append(
+ f"hip branch {hip!r} had {len(hip_medial)} medial children; took the highest-leaved one as the spine"
+ )
+ spine_continuation = hip_medial[0]
+
+ shoulder_path = _descend_to_branch(spine_continuation, children)
+ shoulder = shoulder_path[-1]
+ if len(children[shoulder]) < 2:
+ raise ChainResolutionError(
+ f"no shoulder branch above the hip: the spine from {spine_continuation!r} ends at "
+ f"leaf {shoulder!r} — cannot resolve arm.l / arm.r"
+ )
+
+ arm_pairs, shoulder_medial = _mirror_pairs(children[shoulder], local, symmetry_tolerance)
+ if not arm_pairs:
+ raise ChainResolutionError(
+ f"shoulder branch {shoulder!r} has no mirrored-X child pair within {symmetry_tolerance} "
+ f"(children: {sorted(children[shoulder])}) — cannot resolve arm.l / arm.r"
+ )
+ if len(arm_pairs) > 1:
+ arm_pairs.sort(key=lambda pair: -min(world[joint][1] for joint in pair))
+ notes.append(
+ f"shoulder branch {shoulder!r} had {len(arm_pairs)} mirrored pairs; took the highest as the arms"
+ )
+ arm_pair = arm_pairs[0]
+
+ if not shoulder_medial:
+ raise ChainResolutionError(
+ f"shoulder branch {shoulder!r} has no medial child to carry the spine to the head "
+ f"(children: {sorted(children[shoulder])})"
+ )
+ if len(shoulder_medial) > 1:
+ shoulder_medial.sort(key=lambda joint: -world[_deepest_leaf_path(joint, children, world)[-1]][1])
+ notes.append(f"shoulder branch {shoulder!r} had {len(shoulder_medial)} medial children; took the highest")
+ head_path = _deepest_leaf_path(shoulder_medial[0], children, world)
+
+ # Each segment starts at a child of the previous segment's last joint, so there is no
+ # shared joint to trim between them.
+ spine_ids = tuple(hip_path + shoulder_path + head_path)
+
+ def side_of(pair: tuple[str, str], group: str) -> dict[str, str]:
+ if side_labels:
+ resolved: dict[str, str] = {}
+ for joint in pair:
+ path = _deepest_leaf_path(joint, children, world)
+ label = next((side_labels[j] for j in path if j in side_labels), None)
+ if label is not None:
+ resolved[str(label).lower()[:1]] = joint
+ if set(resolved) == {"l", "r"}:
+ return resolved
+ raise ChainResolutionError(
+ f"side_labels did not resolve both halves of the {group} pair {pair}: got {resolved}"
+ )
+ return {("l" if world[joint][0] > 0 else "r"): joint for joint in pair}
+
+ leg_sides = side_of(leg_pair, "leg")
+ arm_sides = side_of(arm_pair, "arm")
+ if set(leg_sides) != {"l", "r"} or set(arm_sides) != {"l", "r"}:
+ raise ChainResolutionError(
+ "a mirrored pair resolved to the same side — both anchors have the same sign of X, "
+ f"legs={leg_sides} arms={arm_sides}"
+ )
+
+ side_source = "labels" if side_labels else "model-x"
+ if side_source == "model-x":
+ notes.append(
+ "no side_labels supplied: left/right were assigned from the sign of model X, so "
+ "check_medial_lateral cannot fail on a mirrored rig (Chains.gate_is_independent is False)"
+ )
+
+ def build(name: str, anchor: str) -> Chain:
+ path = _deepest_leaf_path(anchor, children, world)
+ return Chain(name=name, joint_ids=tuple(path), anchor_position=world[anchor])
+
+ return Chains(
+ spine=Chain(name="spine", joint_ids=spine_ids, anchor_position=world[root]),
+ arm={side: build(f"arm.{side}", anchor) for side, anchor in arm_sides.items()},
+ leg={side: build(f"leg.{side}", anchor) for side, anchor in leg_sides.items()},
+ world_positions=world,
+ side_source=side_source,
+ symmetry_tolerance=symmetry_tolerance,
+ notes=tuple(notes),
+ )
+
+
+def check_medial_lateral(
+ chains: Chains,
+ medial_tolerance: Optional[float] = MEDIAL_AXIS_TOLERANCE,
+) -> list[str]:
+ """Gate G7 / §R4: assert `leftAnchor.x > 0 > rightAnchor.x` in model space.
+
+ This one comparison catches a mirrored rig — the failure where every left-hand action
+ plays on the right and nothing about it looks wrong in isolation. There is no frame in
+ which a mirrored rig renders badly: both sides are anatomically plausible, both animate
+ smoothly, and the defect only surfaces when someone notices the character draws its
+ sword with the wrong hand. Three inequalities per pair are the whole detector.
+
+ Returns a list of error strings; an empty list means the convention holds. Fail-closed:
+ a non-empty list is a hard rejection, not a warning.
+
+ Note what this can and cannot see. It compares the *claim* about which chain is left
+ against the *geometry*. When `chains.side_source == "model-x"` the claim came from that
+ geometry, so the mirrored-rig case is unreachable and only a degenerate pair (both
+ anchors on one side, or an anchor sitting on the midline) can still be caught — see
+ `Chains.gate_is_independent`.
+
+ `medial_tolerance` optionally adds the spine check: the spine's anchor and head should
+ sit on the midline. It is off by default because the tolerance is in absolute model
+ units and there is no defensible value without knowing H; callers pass `0.02 * H`.
+ """
+ errors: list[str] = []
+ for group, mapping in (("arm", chains.arm), ("leg", chains.leg)):
+ left = mapping["l"]
+ right = mapping["r"]
+ lx = left.anchor_position[0]
+ rx = right.anchor_position[0]
+ if not lx > 0:
+ errors.append(
+ f"MEDIAL_LATERAL: {group}.l anchor {left.anchor!r} has x={lx:.6g}, expected x > 0 "
+ "(left is +X in model space) — the rig is mirrored, or the side labels are swapped"
+ )
+ if not rx < 0:
+ errors.append(
+ f"MEDIAL_LATERAL: {group}.r anchor {right.anchor!r} has x={rx:.6g}, expected x < 0 "
+ "(right is -X in model space) — the rig is mirrored, or the side labels are swapped"
+ )
+ if lx * rx > 0:
+ errors.append(
+ f"MEDIAL_LATERAL: {group}.l ({lx:.6g}) and {group}.r ({rx:.6g}) are on the same side of the midline"
+ )
+ if medial_tolerance is not None:
+ for joint in (chains.spine.anchor, chains.spine.leaf):
+ x = chains.world_positions[joint][0]
+ if abs(x) > medial_tolerance:
+ errors.append(
+ f"MEDIAL_AXIS: spine joint {joint!r} has x={x:.6g}, off the midline by more than "
+ f"{medial_tolerance:.6g}"
+ )
+ return errors
+
+
+# --------------------------------------------------------------------------------------
+# Target bands
+# --------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class FeatureRange:
+ """An inclusive-low band for one §1 feature, with the spec's authoring target."""
+
+ lo: Optional[float] = None
+ hi: Optional[float] = None
+ hi_exclusive: bool = False
+ """§2 writes its upper bounds with `<` (`0.30H/s <= speed < 0.60H/s`). A band that
+ mirrors a classifier boundary must mirror its strictness or the two can disagree at the
+ boundary — which is the one place they must not."""
+ target: Optional[float] = None
+ units: str = ""
+ source: str = ""
+ """Where the number came from, quoted from the spec where possible."""
+
+ def contains(self, value: float) -> bool:
+ if self.lo is not None and value < self.lo:
+ return False
+ if self.hi is not None:
+ if self.hi_exclusive and not value < self.hi:
+ return False
+ if not self.hi_exclusive and value > self.hi:
+ return False
+ return True
+
+ def describe(self) -> str:
+ low = "-inf" if self.lo is None else f"{self.lo:.6g}"
+ if self.hi is None:
+ high = "+inf)"
+ else:
+ high = f"{self.hi:.6g}" + (")" if self.hi_exclusive else "]")
+ target = "" if self.target is None else f" target {self.target:.6g}"
+ return f"[{low}, {high}{target} {self.units}".rstrip()
+
+ @property
+ def midpoint(self) -> Optional[float]:
+ if self.target is not None:
+ return self.target
+ if self.lo is not None and self.hi is not None:
+ return 0.5 * (self.lo + self.hi)
+ return self.lo if self.lo is not None else self.hi
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "lo": self.lo,
+ "hi": self.hi,
+ "hiExclusive": self.hi_exclusive,
+ "target": self.target,
+ "units": self.units,
+ "source": self.source,
+ }
+
+
+@dataclass(frozen=True)
+class FeatureMiss:
+ """One feature that fell outside its band, and on which side."""
+
+ feature: str
+ value: float
+ side: Literal["below", "above"]
+ band: FeatureRange
+
+ def __str__(self) -> str:
+ return f"{self.feature}={self.value:.6g} is {self.side} its band {self.band.describe()}"
+
+ def to_dict(self) -> dict[str, Any]:
+ return {"feature": self.feature, "value": self.value, "side": self.side, "band": self.band.to_dict()}
+
+
+@dataclass(frozen=True)
+class BandCheck:
+ """The result of `TargetBand.contains` — always says *which* feature, never just no."""
+
+ band_name: str
+ inside: tuple[str, ...]
+ outside: tuple[FeatureMiss, ...]
+ unevaluated: tuple[tuple[str, str], ...]
+
+ @property
+ def ok(self) -> bool:
+ return not self.outside
+
+ def __bool__(self) -> bool:
+ return self.ok
+
+ def summary(self) -> str:
+ if self.ok and not self.unevaluated:
+ return f"{self.band_name}: all {len(self.inside)} features inside band"
+ parts = []
+ if self.outside:
+ parts.append("outside: " + "; ".join(str(miss) for miss in self.outside))
+ if self.unevaluated:
+ parts.append("unevaluated: " + "; ".join(f"{name} ({why})" for name, why in self.unevaluated))
+ return f"{self.band_name}: " + " | ".join(parts)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "band": self.band_name,
+ "ok": self.ok,
+ "inside": list(self.inside),
+ "outside": [miss.to_dict() for miss in self.outside],
+ "unevaluated": [{"feature": name, "reason": why} for name, why in self.unevaluated],
+ }
+
+
+@dataclass(frozen=True)
+class TargetBand:
+ """A per-feature min/max specification for a clip that is about to be authored.
+
+ §R4: "the same feature vector that identifies a clip **specifies** one." A TargetBand is
+ that vector read in the authoring direction.
+
+ UNITS — the trap worth stating once, loudly. Every positional bound here is a **fraction
+ of H**, not model units, because `clip_features.measure_clip` normalises by H before it
+ returns. A band in model units compared against a normalised measurement agrees on every
+ rig of height 1.0 and silently disagrees on every other one, which is the exact shape of
+ failure §0 is about. `figure_height` records the H the band was built for so a caller can
+ convert; `gait_parameters()` is where the conversion to model units happens, because
+ authored tracks are the one thing that does live in model space.
+ """
+
+ name: str
+ figure_height: float
+ intended_class: str
+ ranges: dict[str, FeatureRange]
+ limb_frame: str = LIMB_FEATURE_FRAME
+ notes: tuple[str, ...] = ()
+
+ def contains(self, features: Any) -> BandCheck:
+ """Check measured features against every range, naming each one that missed.
+
+ Never returns a bare bool. A caller that only wants yes/no can use the truthiness of
+ the returned `BandCheck`, but the miss list is always there — "the clip is outside
+ the band" is not actionable and "footRange=0.41H is above [0.154, 0.286]" is.
+
+ A feature the measurement does not carry is reported `unevaluated`, not inside.
+ """
+ inside: list[str] = []
+ outside: list[FeatureMiss] = []
+ unevaluated: list[tuple[str, str]] = []
+ for name, band in self.ranges.items():
+ value = feature_value(features, name)
+ if value is None:
+ unevaluated.append((name, "not present in the measured features"))
+ continue
+ if band.contains(value):
+ inside.append(name)
+ else:
+ below = band.lo is not None and value < band.lo
+ outside.append(FeatureMiss(feature=name, value=value, side="below" if below else "above", band=band))
+ return BandCheck(
+ band_name=self.name,
+ inside=tuple(inside),
+ outside=tuple(outside),
+ unevaluated=tuple(unevaluated),
+ )
+
+ def target(self, feature: str) -> float:
+ band = self.ranges[feature]
+ value = band.midpoint
+ if value is None:
+ raise KeyError(f"band {self.name!r} has no usable target for {feature!r}")
+ return value
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "name": self.name,
+ "figureHeight": self.figure_height,
+ "intendedClass": self.intended_class,
+ "limbFrame": self.limb_frame,
+ "ranges": {name: band.to_dict() for name, band in self.ranges.items()},
+ "notes": list(self.notes),
+ }
+
+
+def _gait_band(
+ *,
+ name: str,
+ intended_class: str,
+ figure_height: float,
+ duration_lo: float,
+ duration_hi: float,
+ speed_lo: float,
+ speed_hi: float,
+ speed_target: float,
+ rise_lo: float,
+ rise_hi: float,
+ hand_lo: float,
+ hand_hi: float,
+ hand_hi_exclusive: bool,
+ hand_target: float,
+ contact_lo: float,
+ contact_hi: float,
+ contact_hi_exclusive: bool,
+ contact_target: float,
+ foot_range_tolerance: float,
+ notes: Sequence[str],
+) -> TargetBand:
+ # All positional bounds are fractions of H — see TargetBand's UNITS note.
+ travel_lo = speed_target * duration_lo
+ travel_hi = speed_target * duration_hi
+ step = 0.5 * 0.5 * (travel_lo + travel_hi) # spec: footRange ~= travel / 2
+ ranges = {
+ "duration": FeatureRange(
+ lo=duration_lo, hi=duration_hi, units="s", source="spec R4: duration ~ 1.0-1.2 s per cycle"
+ ),
+ "speed": FeatureRange(
+ lo=speed_lo,
+ hi=speed_hi,
+ hi_exclusive=True,
+ target=speed_target,
+ units="H/s",
+ source=f"spec §2 class band for {intended_class}; target from spec R4",
+ ),
+ "travel": FeatureRange(
+ lo=travel_lo,
+ hi=travel_hi,
+ target=speed_target * 0.5 * (duration_lo + duration_hi),
+ units="H",
+ source="spec R4: travel = speed x duration",
+ ),
+ "rise": FeatureRange(
+ lo=rise_lo,
+ hi=rise_hi,
+ units="H",
+ source="spec R4: rise 0.015H-0.025H (hips stay flat; more reads as a limp)",
+ ),
+ "handRange": FeatureRange(
+ lo=hand_lo,
+ hi=hand_hi,
+ hi_exclusive=hand_hi_exclusive,
+ target=hand_target,
+ units=f"H ({LIMB_FEATURE_FRAME})",
+ source="spec R4: counter-swing, opposite phase to the leg",
+ ),
+ "footRange": FeatureRange(
+ lo=step * (1.0 - foot_range_tolerance),
+ hi=step * (1.0 + foot_range_tolerance),
+ target=step,
+ units=f"H ({LIMB_FEATURE_FRAME})",
+ source=f"spec R4: footRange ~= travel/2 per foot per cycle, +/-{foot_range_tolerance:.0%}",
+ ),
+ "contact": FeatureRange(
+ lo=contact_lo,
+ hi=contact_hi,
+ hi_exclusive=contact_hi_exclusive,
+ target=contact_target,
+ units="fraction of cycle per foot",
+ source="spec R4 contact fraction",
+ ),
+ "poseReturn": FeatureRange(
+ lo=0.0, hi=POSE_RETURN_DEGREES, units="deg", source="spec R4/§4: poseReturn <= 0.5 deg -> loopable"
+ ),
+ "scaleDelta": FeatureRange(lo=0.0, hi=0.0, units="", source="Gate R4: scaleDelta == 0, never author joint scale"),
+ }
+ return TargetBand(
+ name=name,
+ figure_height=figure_height,
+ intended_class=intended_class,
+ ranges=ranges,
+ notes=tuple(notes),
+ )
+
+
+def walk_targets(figure_height: float) -> TargetBand:
+ """The spec's worked walk example, encoded verbatim.
+
+ From §R4 "Design targets, worked", for a rig of height H:
+
+ duration ~ 1.0-1.2 s per cycle
+ speed target 0.40H/s -> travel = speed x duration
+ rise 0.015H-0.025H (hips stay flat; more reads as a limp)
+ handRange 0.15H-0.25H (counter-swing, opposite phase to the leg)
+ footRange ~ stride ~ travel / 2 per foot per cycle
+ contact 0.60 of cycle per foot, so both feet are down 0.20 of the time
+ poseReturn <= 0.5 deg -> loopable by §4
+
+ Two readings the spec leaves open, taken here rather than hidden:
+
+ 1. **speed is a target, not a band.** The band around it is §2's own walk class,
+ `0.30H/s <= speed < 0.60H/s`, upper bound exclusive. Deriving the band from the
+ classifier instead of inventing one is what stops the acceptance test from being
+ satisfiable by a clip the classifier would reject.
+ 2. **`footRange`/`handRange` are hip-relative.** See `LIMB_FEATURE_FRAME`: under §1's
+ world-space definition a forward-travelling gait cannot land in these bands at any
+ speed, because the limbs go where the body goes.
+
+ `contact` is not a §1 feature — it is an authoring parameter, measurable from a clip's
+ stance intervals. `band_features()` computes it; a caller who has no stance data gets
+ `unevaluated` for it, never a pass.
+ """
+ return _gait_band(
+ name="walk",
+ intended_class="walk",
+ figure_height=figure_height,
+ duration_lo=1.0,
+ duration_hi=1.2,
+ speed_lo=0.30,
+ speed_hi=0.60,
+ speed_target=0.40,
+ rise_lo=0.015,
+ rise_hi=0.025,
+ hand_lo=0.15,
+ hand_hi=0.25,
+ hand_hi_exclusive=False,
+ hand_target=0.20,
+ contact_lo=0.55,
+ contact_hi=0.65,
+ contact_hi_exclusive=False,
+ contact_target=0.60,
+ foot_range_tolerance=FOOT_RANGE_TOLERANCE,
+ notes=(
+ "handRange and footRange bands are stated in the hip-relative, per-limb frame; see LIMB_FEATURE_FRAME.",
+ "contact 0.60 per foot puts both feet down 0.20 of the cycle (0.60 + 0.60 - 1.00).",
+ "R4's 'poseReturn <= 0.5 deg -> loopable by §4' is only half of §4's rule: §4 also requires "
+ "||hip(T) - hip(0)|| <= 0.01H, which a forward-travelling walk cycle cannot satisfy in world "
+ "space at any speed. Such a clip loops once its root motion is extracted, not before — so it "
+ "should not be declared a loop on the strength of poseReturn alone.",
+ ),
+ )
+
+
+def run_targets(figure_height: float) -> TargetBand:
+ """The spec's run recipe: exactly three changes to `walk_targets`, nothing else.
+
+ §R4: "Run: raise speed into `[0.60H/s, 1.50H/s)`, drop contact fraction below 0.5 so a
+ flight phase exists, raise `handRange` toward 0.35H. The classifier must then report
+ `run`, not `walk`, without being told — that is the acceptance test."
+
+ Readings taken:
+
+ - **Only those three move.** `duration` and `rise` are inherited from the walk band
+ because the spec changes neither. A real run has more hip rise than 0.015H-0.025H;
+ that is a divergence from observed running gaits, not from this spec, and it is left
+ as written rather than quietly improved.
+ - **speed target 0.80H/s** — the measured `run-forward` value (0.799) from §2's own
+ validation table, so the target is a number the spec already recorded rather than a
+ midpoint invented here.
+ - **contact target 0.40**, giving a 0.20 flight phase by the same arithmetic the walk's
+ 0.60 uses for double support. The band's upper bound is exclusive at 0.50, matching
+ "below 0.5".
+ - **handRange band `[0.25H, 0.40H)`**, upper bound exclusive at §2's `gesture`
+ threshold. `gesture` only fires "while in-place" so a run could not collide with it,
+ but a band that runs up to and past another class's boundary invites exactly the
+ silent overlap §2 avoided by putting its boundaries in the empty gaps.
+ """
+ return _gait_band(
+ name="run",
+ intended_class="run",
+ figure_height=figure_height,
+ duration_lo=1.0,
+ duration_hi=1.2,
+ speed_lo=0.60,
+ speed_hi=1.50,
+ speed_target=0.80,
+ rise_lo=0.015,
+ rise_hi=0.025,
+ hand_lo=0.25,
+ hand_hi=0.40,
+ hand_hi_exclusive=True,
+ hand_target=0.35,
+ contact_lo=0.30,
+ contact_hi=0.50,
+ contact_hi_exclusive=True,
+ contact_target=0.40,
+ foot_range_tolerance=FOOT_RANGE_TOLERANCE,
+ notes=(
+ "inherits duration and rise from walk_targets: §R4's run recipe changes speed, contact and handRange only.",
+ "contact 0.40 per foot leaves a 0.20 flight phase (1.00 - 0.40 - 0.40).",
+ "handRange upper bound is exclusive at §2's gesture threshold of 0.40H.",
+ ),
+ )
+
+
+# --------------------------------------------------------------------------------------
+# Foot contact — the single most valuable gate in the stage
+# --------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class StanceSlide:
+ """The worst slide measured inside one stance interval of one foot."""
+
+ landmark: str
+ interval: tuple[float, float]
+ contact_time: float
+ frames: int
+ max_slide: float
+ max_slide_fraction: float
+ worst_time: float
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "landmark": self.landmark,
+ "interval": list(self.interval),
+ "contactTime": self.contact_time,
+ "frames": self.frames,
+ "maxSlide": self.max_slide,
+ "maxSlideFraction": self.max_slide_fraction,
+ "worstTime": self.worst_time,
+ }
+
+
+@dataclass(frozen=True)
+class FootSlideReport:
+ figure_height: float
+ limit: float
+ per_stance: tuple[StanceSlide, ...]
+ max_slide_fraction: Optional[float]
+ status: Status
+ reason: str
+ unmeasured: tuple[str, ...] = ()
+
+ @property
+ def ok(self) -> bool:
+ return self.status == "pass"
+
+ @property
+ def worst(self) -> Optional[StanceSlide]:
+ if not self.per_stance:
+ return None
+ return max(self.per_stance, key=lambda stance: stance.max_slide_fraction)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "figureHeight": self.figure_height,
+ "limit": self.limit,
+ "status": self.status,
+ "reason": self.reason,
+ "maxSlideFraction": self.max_slide_fraction,
+ "perStance": [stance.to_dict() for stance in self.per_stance],
+ "unmeasured": list(self.unmeasured),
+ }
+
+
+def foot_slide(
+ landmark_positions: Mapping[str, Sequence[Sequence[float]]],
+ sample_times: Sequence[float],
+ stance_intervals: Mapping[str, Sequence[Sequence[float]]],
+ figure_height: float,
+ limit: float = FOOT_SLIDE_LIMIT,
+ time_tolerance: float = 1e-9,
+) -> FootSlideReport:
+ """`footSlide = max over stance frames ||foot_world(t) - foot_world(t_contact)||`.
+
+ require footSlide <= 0.01H (FOOT_SLIDE_LIMIT)
+
+ §R4: "This is the single most valuable gate in the stage. A gait that violates it reads
+ as 'floaty' or 'skating' to every viewer while being hard to name by eye." That is the
+ whole argument for measuring it. Every viewer detects a skating gait instantly and
+ almost nobody can say what is wrong with it, so it survives review, survives playtest
+ notes, and is fixed only when someone finally puts a number on the stance frames.
+
+ `landmark_positions` must be **world** positions. Passing a hip-relative clip here
+ inverts the measurement: with the root's planar motion removed, a *correctly* planted
+ foot slides backwards by exactly `travel` per cycle and this gate rejects the one gait
+ that was right. `hip_relative_clip()` carries the same warning.
+
+ Reports `unevaluated` when there is no stance data at all — Gate G8 with no stance
+ intervals is not a pass, it is an unasked question (CONTRACT: "It is never silently a
+ pass"). Individual intervals spanning fewer than two samples are listed in `unmeasured`
+ rather than contributing a reassuring zero.
+ """
+ if figure_height <= 0:
+ raise ValueError(f"figure_height must be positive, got {figure_height}")
+ times = [float(t) for t in sample_times]
+
+ per_stance: list[StanceSlide] = []
+ unmeasured: list[str] = []
+ considered = 0
+
+ for landmark, intervals in sorted(stance_intervals.items()):
+ positions = landmark_positions.get(landmark)
+ if positions is None:
+ unmeasured.append(f"{landmark}: stance intervals given but no landmark positions")
+ continue
+ if len(positions) != len(times):
+ raise ValueError(
+ f"{landmark}: {len(positions)} positions for {len(times)} sample times — "
+ "the sampled-clip payload requires them equal"
+ )
+ for interval in intervals:
+ considered += 1
+ t0, t1 = float(interval[0]), float(interval[1])
+ frame_indices = [i for i, t in enumerate(times) if t0 - time_tolerance <= t <= t1 + time_tolerance]
+ if len(frame_indices) < 2:
+ unmeasured.append(
+ f"{landmark} stance [{t0:.6g}, {t1:.6g}]: {len(frame_indices)} sample frame(s), "
+ "too few to measure a slide"
+ )
+ continue
+ contact_index = frame_indices[0]
+ anchor = _vec3(positions[contact_index], f"{landmark}[{contact_index}]")
+ worst = 0.0
+ worst_time = times[contact_index]
+ for i in frame_indices:
+ slide = _distance(_vec3(positions[i], f"{landmark}[{i}]"), anchor)
+ if slide > worst:
+ worst = slide
+ worst_time = times[i]
+ per_stance.append(
+ StanceSlide(
+ landmark=landmark,
+ interval=(t0, t1),
+ contact_time=times[contact_index],
+ frames=len(frame_indices),
+ max_slide=worst,
+ max_slide_fraction=worst / figure_height,
+ worst_time=worst_time,
+ )
+ )
+
+ if not per_stance:
+ return FootSlideReport(
+ figure_height=figure_height,
+ limit=limit,
+ per_stance=(),
+ max_slide_fraction=None,
+ status="unevaluated",
+ reason=(
+ "no measurable stance interval: Gate G8 needs `stance` on the clip payload and at least "
+ f"two sample frames inside an interval ({considered} interval(s) considered)"
+ ),
+ unmeasured=tuple(unmeasured),
+ )
+
+ worst_overall = max(stance.max_slide_fraction for stance in per_stance)
+ if worst_overall <= limit:
+ status: Status = "pass"
+ reason = f"footSlide {worst_overall:.6g}H <= {limit:.6g}H over {len(per_stance)} stance interval(s)"
+ else:
+ status = "fail"
+ offender = max(per_stance, key=lambda stance: stance.max_slide_fraction)
+ reason = (
+ f"footSlide {worst_overall:.6g}H > {limit:.6g}H — {offender.landmark} slid "
+ f"{offender.max_slide:.6g} model units at t={offender.worst_time:.6g} while in stance "
+ f"[{offender.interval[0]:.6g}, {offender.interval[1]:.6g}]"
+ )
+ return FootSlideReport(
+ figure_height=figure_height,
+ limit=limit,
+ per_stance=tuple(per_stance),
+ max_slide_fraction=worst_overall,
+ status=status,
+ reason=reason,
+ unmeasured=tuple(unmeasured),
+ )
+
+
+# --------------------------------------------------------------------------------------
+# Primitives
+# --------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Primitive:
+ """One row of §R4's primitive table."""
+
+ name: str
+ use: str
+ parameters: tuple[str, ...]
+ note: str = ""
+
+ def to_dict(self) -> dict[str, Any]:
+ return {"name": self.name, "use": self.use, "parameters": list(self.parameters), "note": self.note}
+
+
+PRIMITIVES: dict[str, Primitive] = {
+ "gait": Primitive(
+ name="Gait",
+ use="walk / run / dash",
+ parameters=("cadence", "stride", "contactFraction", "hipRise", "armCounterSwing"),
+ note=(
+ "A phase machine, not a sine wave. Each leg has stance and swing, and while a foot is in "
+ "stance its world position must not move — see GaitPhase and foot_slide()."
+ ),
+ ),
+ "ballistic": Primitive(
+ name="Ballistic",
+ use="jump / leap",
+ parameters=("takeoffVelocity", "apexRise", "flightTime", "landAbsorption"),
+ ),
+ "reach": Primitive(
+ name="Reach",
+ use="strike / gesture",
+ parameters=("targetSocket", "windupFraction", "followThrough", "return"),
+ note="§3: a name for a Reach that implies intent carries inferred: true — no feature separates a strike from a stumble.",
+ ),
+ "additive": Primitive(
+ name="Additive",
+ use="breathing, sway",
+ parameters=("amplitude", "period", "jointMask"),
+ note="Layered on any base clip.",
+ ),
+}
+
+
+@dataclass(frozen=True)
+class GaitPhase:
+ """Stance and swing for one leg, as intervals in seconds — not an amplitude.
+
+ §R4: "Gait is a phase machine, not a sine wave. Each leg has stance and swing; the
+ **contact constraint** is what separates an animation from a slide: while a foot is in
+ stance its world position must not move."
+
+ A sine-wave foot track cannot express that constraint at all — a sinusoid is moving at
+ every instant except its two turning points, so a foot authored as a sine slides through
+ its entire stance by construction and `foot_slide` rejects it every time. The stance
+ interval is therefore first-class here and the foot position is *constant* across it.
+ """
+
+ leg: str
+ duration: float
+ contact_fraction: float
+ stance_start_fraction: float
+
+ def stance_intervals(self) -> tuple[tuple[float, float], ...]:
+ """Stance windows clipped into `[0, duration]`, wrapping where the phase does."""
+ start = self.stance_start_fraction * self.duration
+ end = start + self.contact_fraction * self.duration
+ if end <= self.duration:
+ return ((start, end),)
+ return ((0.0, end - self.duration), (start, self.duration))
+
+ def swing_intervals(self) -> tuple[tuple[float, float], ...]:
+ stance = self.stance_intervals()
+ cuts = [0.0]
+ for lo, hi in stance:
+ cuts.extend((lo, hi))
+ cuts.append(self.duration)
+ out: list[tuple[float, float]] = []
+ covered = sorted(stance)
+ cursor = 0.0
+ for lo, hi in covered:
+ if lo - cursor > 1e-12:
+ out.append((cursor, lo))
+ cursor = max(cursor, hi)
+ if self.duration - cursor > 1e-12:
+ out.append((cursor, self.duration))
+ return tuple(out)
+
+ def plant_index(self, t: float) -> tuple[int, float]:
+ """`(which plant, fraction of cycle since it)` for time `t`.
+
+ The plant index is what makes the foot advance: each successive stance is one
+ `travel` further down the path, so a foot cannot be "the same plant" one cycle later.
+ """
+ u = t / self.duration - self.stance_start_fraction
+ k = math.floor(u)
+ return k, u - k
+
+ def is_stance(self, t: float, tolerance: float = 1e-12) -> bool:
+ return self.plant_index(t)[1] <= self.contact_fraction + tolerance
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "leg": self.leg,
+ "duration": self.duration,
+ "contactFraction": self.contact_fraction,
+ "stanceStartFraction": self.stance_start_fraction,
+ "stanceIntervals": [list(interval) for interval in self.stance_intervals()],
+ "swingIntervals": [list(interval) for interval in self.swing_intervals()],
+ }
+
+
+FOOT_LIFT_FRACTION_OF_STRIDE = 0.12
+"""Swing-foot apex height as a fraction of stride. NOT from the spec — an authoring default.
+
+§R4's gait parameter list has no foot lift, so there is no spec number to quote. It is
+exposed as an override and recorded on `GaitParameters` so it is visible as a choice. It
+touches no gate: it never moves a stance frame (footSlide), and at any plausible value the
+Y excursion stays well under the Z excursion that `footRange`'s per-axis max reads.
+"""
+
+HIP_HEIGHT_FRACTION = 0.55
+ARM_LATERAL_FRACTION = 0.18
+FOOT_LATERAL_FRACTION = 0.09
+HAND_HEIGHT_FRACTION = 0.55
+HEAD_HEIGHT_FRACTION = 0.94
+"""Rest-pose placements for `synthesise_gait_tracks`. Presentation only: no §1 feature is a
+function of an absolute position, so these shift the tracks without moving any measurement."""
+
+
+@dataclass(frozen=True)
+class GaitParameters:
+ """Gait primitive parameters derived from a target band."""
+
+ band_name: str
+ figure_height: float
+ duration: float
+ cadence: float
+ """Steps per second. One cycle is two steps, so `cadence = 2 / duration`."""
+ speed: float
+ travel: float
+ stride: float
+ """Step length between alternating footfalls: `travel / 2`. See FOOT_RANGE_TOLERANCE for
+ why this is not the same quantity as §1's `footRange`."""
+ contact_fraction: float
+ double_support_fraction: float
+ """`2 * contact - 1`, clamped at 0. Positive is double support; negative would be a
+ flight phase, and is reported as `flight_fraction` instead."""
+ flight_fraction: float
+ hip_rise: float
+ arm_counter_swing: float
+ foot_lift: float
+ phases: tuple[GaitPhase, GaitPhase]
+
+ def phase(self, leg: str) -> GaitPhase:
+ for gait_phase in self.phases:
+ if gait_phase.leg == leg:
+ return gait_phase
+ raise KeyError(leg)
+
+ def stance_intervals(self) -> dict[str, list[list[float]]]:
+ """Stance windows keyed by the §1 foot landmark, ready for the clip payload."""
+ return {
+ f"foot.{gait_phase.leg.rsplit('.', 1)[-1]}": [list(i) for i in gait_phase.stance_intervals()]
+ for gait_phase in self.phases
+ }
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "band": self.band_name,
+ "figureHeight": self.figure_height,
+ "duration": self.duration,
+ "cadence": self.cadence,
+ "speed": self.speed,
+ "travel": self.travel,
+ "stride": self.stride,
+ "contactFraction": self.contact_fraction,
+ "doubleSupportFraction": self.double_support_fraction,
+ "flightFraction": self.flight_fraction,
+ "hipRise": self.hip_rise,
+ "armCounterSwing": self.arm_counter_swing,
+ "footLift": self.foot_lift,
+ "phases": [gait_phase.to_dict() for gait_phase in self.phases],
+ }
+
+
+def gait_parameters(
+ band: TargetBand,
+ figure_height: float,
+ foot_lift_fraction: float = FOOT_LIFT_FRACTION_OF_STRIDE,
+) -> GaitParameters:
+ """Derive the Gait primitive's five parameters from a target band.
+
+ cadence, stride, contact fraction, hip rise and arm counter-swing all come out of the
+ band's targets, so a band edit propagates into the authored motion instead of the two
+ drifting apart.
+
+ The two legs are half a cycle out of phase (`stance_start_fraction` 0.0 and 0.5). That
+ offset plus the contact fraction is the entire gait: at contact 0.60 the overlap is
+ 0.20 of the cycle of double support (`0.60 + 0.60 - 1.00`, the spec's own arithmetic);
+ at contact 0.40 the same subtraction gives -0.20, reported as a 0.20 flight phase, which
+ is what §R4 means by "drop contact fraction below 0.5 so a flight phase exists".
+
+ UNITS: the band is in fractions of H (see `TargetBand`); the returned parameters are in
+ **model units**, multiplied through by `figure_height`, because they exist to be turned
+ into tracks and tracks are model-space. `duration`, `cadence` and `contact_fraction` are
+ dimensionless or in seconds and pass through untouched.
+ """
+ duration = band.target("duration")
+ speed = band.target("speed") * figure_height
+ travel = speed * duration
+ contact = band.target("contact")
+ overlap = 2.0 * contact - 1.0
+ stride = 0.5 * travel
+
+ hip_rise = band.target("rise") * figure_height
+ arm_counter_swing = band.target("handRange") * figure_height
+
+ phases = (
+ GaitPhase(leg="leg.l", duration=duration, contact_fraction=contact, stance_start_fraction=0.0),
+ GaitPhase(leg="leg.r", duration=duration, contact_fraction=contact, stance_start_fraction=0.5),
+ )
+ return GaitParameters(
+ band_name=band.name,
+ figure_height=figure_height,
+ duration=duration,
+ cadence=2.0 / duration,
+ speed=speed,
+ travel=travel,
+ stride=stride,
+ contact_fraction=contact,
+ double_support_fraction=max(0.0, overlap),
+ flight_fraction=max(0.0, -overlap),
+ hip_rise=hip_rise,
+ arm_counter_swing=arm_counter_swing,
+ foot_lift=foot_lift_fraction * stride,
+ phases=phases,
+ )
+
+
+# --------------------------------------------------------------------------------------
+# Authoring — turn gait parameters into a sampled-clip payload
+# --------------------------------------------------------------------------------------
+
+SAMPLE_COUNT = 25
+"""§1: "Sample the clip at N = 25 evenly spaced times." """
+
+
+def sample_times(duration: float, count: int = SAMPLE_COUNT, endpoint: bool = False) -> list[float]:
+ """`count` evenly spaced times over `[0, duration]`.
+
+ READING CHOSEN: `endpoint=False`, i.e. `t_i = i * duration / count`, so `t = duration`
+ is not sampled. For a looping clip the pose at `t = duration` is the pose at `t = 0`;
+ including both double-counts it and, worse, offsets every other sample by
+ `duration / (N - 1)` instead of `duration / N`, which walks the samples off the phase
+ boundaries a gait is defined by. `endpoint=True` is available for a clip that is not a
+ loop and whose final pose is genuinely distinct.
+ """
+ if count < 2:
+ raise ValueError(f"need at least 2 samples, got {count}")
+ divisor = (count - 1) if endpoint else count
+ return [index * duration / divisor for index in range(count)]
+
+
+def _smoothstep(x: float) -> float:
+ return x * x * (3.0 - 2.0 * x)
+
+
+def synthesise_gait_tracks(
+ params: GaitParameters,
+ count: int = SAMPLE_COUNT,
+ endpoint: bool = False,
+ source_name: str = "authored",
+) -> dict[str, Any]:
+ """Author world-space landmark tracks for a gait, as a CONTRACT_1.5.2 clip payload.
+
+ This is the "author tracks" arrow of §R4's loop, kept in this module so the round trip
+ `targets -> author -> measure -> classify` can actually be run rather than asserted.
+
+ The contact constraint is honoured literally: for every sample inside a stance window
+ the foot's world position is the plant position, unchanged. It is not "nearly constant"
+ or "constant to within an easing curve" — it is the same three floats, so `foot_slide`
+ on this payload measures exactly 0.
+
+ Swing uses smoothstep, which is monotone. That matters beyond looking smooth: a
+ non-monotone swing would overshoot the plant positions and inflate the measured
+ `footRange` past the geometry the band was derived from.
+
+ `poseReturn` is emitted as 0.0 because every track here is exactly periodic by
+ construction (each landmark's hip-relative position at `t = duration` equals its
+ position at `t = 0`). A host evaluating a real rig measures it off the joint transforms
+ instead; this is a synthesised payload declaring a property of its own construction.
+ """
+ height = params.figure_height
+ duration = params.duration
+ times = sample_times(duration, count=count, endpoint=endpoint)
+
+ contact = params.contact_fraction
+ travel = params.travel
+ speed = params.speed
+
+ # Plant offsets chosen so each foot's hip-relative excursion is symmetric about 0:
+ # the foot plants ahead of the hip by half its stance excursion (contact * travel / 2)
+ # and lifts the same distance behind it.
+ plant_z = {"l": 0.5 * contact * travel, "r": (0.5 + 0.5 * contact) * travel}
+ lateral_x = {"l": FOOT_LATERAL_FRACTION * height, "r": -FOOT_LATERAL_FRACTION * height}
+
+ positions: dict[str, list[list[float]]] = {
+ name: [] for name in ("hip", "head", "hand.l", "hand.r", "foot.l", "foot.r")
+ }
+
+ for t in times:
+ cycle = t / duration
+ hip_z = speed * t
+ # Hips fall and rise twice per cycle — once per step, not once per cycle.
+ hip_y = HIP_HEIGHT_FRACTION * height + 0.5 * params.hip_rise * math.cos(4.0 * math.pi * cycle)
+ positions["hip"].append([0.0, hip_y, hip_z])
+ positions["head"].append(
+ [0.0, HEAD_HEIGHT_FRACTION * height + 0.5 * params.hip_rise * math.cos(4.0 * math.pi * cycle), hip_z]
+ )
+
+ for side in ("l", "r"):
+ gait_phase = params.phase(f"leg.{side}")
+ plant, frac = gait_phase.plant_index(t)
+ base_z = plant_z[side] + plant * travel
+ if frac <= contact + 1e-12:
+ foot = [lateral_x[side], 0.0, base_z]
+ else:
+ w = (frac - contact) / (1.0 - contact)
+ foot = [
+ lateral_x[side],
+ params.foot_lift * math.sin(math.pi * w),
+ base_z + travel * _smoothstep(w),
+ ]
+ positions[f"foot.{side}"].append(foot)
+
+ # Counter-swing: the hand is in opposite phase to the leg on the same side.
+ swing = 0.5 * params.arm_counter_swing * math.cos(2.0 * math.pi * (cycle - gait_phase.stance_start_fraction))
+ positions[f"hand.{side}"].append(
+ [ARM_LATERAL_FRACTION * height * (1 if side == "l" else -1), HAND_HEIGHT_FRACTION * height, hip_z - swing]
+ )
+
+ return {
+ "sourceName": source_name,
+ "duration": duration,
+ "sampleTimes": times,
+ "landmarkPositions": positions,
+ "jointScaleDelta": [0.0] * len(times),
+ "poseReturn": 0.0,
+ "stance": params.stance_intervals(),
+ }
+
+
+def build_payload(clips: Sequence[Mapping[str, Any]], figure_height: float) -> dict[str, Any]:
+ """Wrap authored clips in the CONTRACT_1.5.2 sampled-clip payload envelope."""
+ return {
+ "figureHeight": figure_height,
+ "landmarks": ["hip", "head", "hand.l", "hand.r", "foot.l", "foot.r"],
+ "clips": [dict(clip) for clip in clips],
+ }
+
+
+def hip_relative_clip(clip: Mapping[str, Any]) -> dict[str, Any]:
+ """A copy of `clip` with the root's **planar** motion removed from every landmark.
+
+ This is the frame `LIMB_FEATURE_FRAME` names, and the frame the `handRange`/`footRange`
+ bands are stated in. Vertical motion is untouched, so `rise` and `headRise` read the same
+ in both frames.
+
+ NEVER feed the result to `foot_slide`. With the root's advance removed, a correctly
+ planted foot travels backwards by exactly `travel` per cycle, so the gate would reject
+ the one gait that satisfies it. footSlide is a world-space measurement, always.
+ """
+ positions = clip["landmarkPositions"]
+ hip = [_vec3(p, "hip") for p in positions["hip"]]
+ origin = hip[0]
+ out: dict[str, list[list[float]]] = {}
+ for name, track in positions.items():
+ moved = []
+ for index, point in enumerate(track):
+ x, y, z = _vec3(point, name)
+ moved.append([x - (hip[index][0] - origin[0]), y, z - (hip[index][2] - origin[2])])
+ out[name] = moved
+ result = dict(clip)
+ result["landmarkPositions"] = out
+ result["frame"] = "hip-relative"
+ return result
+
+
+def measured_contact_fraction(clip: Mapping[str, Any]) -> Optional[float]:
+ """Mean per-foot stance time as a fraction of the cycle, from the clip's stance data."""
+ stance = clip.get("stance")
+ duration = clip.get("duration")
+ if not stance or not duration:
+ return None
+ fractions = []
+ for intervals in stance.values():
+ total = sum(float(interval[1]) - float(interval[0]) for interval in intervals)
+ fractions.append(total / float(duration))
+ return sum(fractions) / len(fractions) if fractions else None
+
+
+def _call_measure(measure: Callable[..., Any], clip: Mapping[str, Any], figure_height: float) -> Any:
+ """Call `measure_clip` without pinning down which signature the sibling settled on."""
+ for args in ((clip, figure_height), (clip,)):
+ try:
+ return measure(*args)
+ except TypeError as exc: # only a signature mismatch, never a measurement failure
+ if "positional argument" not in str(exc) and "argument" not in str(exc):
+ raise
+ return measure(clip, figure_height=figure_height)
+
+
+def _per_limb_range(features: Any, landmarks: Sequence[str]) -> Optional[float]:
+ """Max over `landmarks` of that landmark's own largest axis range, or None.
+
+ The un-pooled reading of `handRange` / `footRange`. See `LIMB_FEATURE_FRAME` point 2 for
+ why pooling is wrong for an authoring band. Returns None when the measurement does not
+ carry per-landmark ranges, so the caller falls back to the pooled figure rather than
+ getting a fabricated one.
+ """
+ ranges = getattr(features, "landmark_ranges", None)
+ if ranges is None and isinstance(features, Mapping):
+ ranges = features.get("landmarkRanges") or features.get("landmark_ranges")
+ if not ranges:
+ return None
+ values = [max(ranges[name]) for name in landmarks if name in ranges]
+ return max(values) if values else None
+
+
+def band_features(
+ clip: Mapping[str, Any],
+ figure_height: float,
+ measure: Optional[Callable[..., Any]] = None,
+) -> dict[str, float]:
+ """Measure a clip into the feature dict a `TargetBand` expects.
+
+ Global features (`duration`, `travel`, `rise`, `speed`, `headRise`, `scaleDelta`,
+ `poseReturn`) are read in world space — the only frame §2's classifier is meaningful in,
+ since `travel` and `speed` are zero by construction in any root-relative frame.
+ `handRange` and `footRange` are read per-limb from `hip_relative_clip(clip)`, per
+ `LIMB_FEATURE_FRAME`. `contact` comes from the clip's stance intervals.
+
+ The result is a plain dict for `TargetBand.contains`. It is deliberately NOT what gets
+ handed to §2's classifier — see `accepts(classifier_input=...)`.
+
+ `measure` defaults to `clip_features.measure_clip`; a caller must supply one when that
+ module is not importable, and gets a clear error rather than a fabricated measurement.
+ """
+ measure = measure or default_measure()
+ if measure is None:
+ raise RuntimeError(
+ "no measure_clip available: clip_features could not be imported and no `measure` was supplied. "
+ "band_features refuses to invent a measurement."
+ )
+ world = _call_measure(measure, clip, figure_height)
+ relative = _call_measure(measure, hip_relative_clip(clip), figure_height)
+
+ values: dict[str, float] = {}
+ for name in ("duration", "travel", "rise", "speed", "headRise", "scaleDelta", "poseReturn"):
+ value = feature_value(world, name)
+ if value is not None:
+ values[name] = value
+ for name, landmarks in (("handRange", ("hand.l", "hand.r")), ("footRange", ("foot.l", "foot.r"))):
+ value = _per_limb_range(relative, landmarks)
+ if value is None:
+ value = feature_value(relative, name)
+ if value is not None:
+ values[name] = value
+ contact = measured_contact_fraction(clip)
+ if contact is not None:
+ values["contact"] = contact
+ return values
+
+
+# --------------------------------------------------------------------------------------
+# Acceptance — Gate R4
+# --------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class Criterion:
+ name: str
+ status: Status
+ reason: str
+ detail: dict[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {"criterion": self.name, "status": self.status, "reason": self.reason, "detail": self.detail}
+
+
+@dataclass(frozen=True)
+class Acceptance:
+ """Gate R4's verdict: every criterion, with pass / fail / unevaluated and a reason.
+
+ `accepted` is False if any criterion failed. `complete` is False if any criterion could
+ not be evaluated. They are separate on purpose: "nothing failed" and "everything was
+ checked" are different claims, and collapsing them into one boolean is how an
+ unevaluated gate becomes a silent pass.
+ """
+
+ intended_class: str
+ band_name: str
+ criteria: tuple[Criterion, ...]
+
+ @property
+ def failures(self) -> tuple[Criterion, ...]:
+ return tuple(c for c in self.criteria if c.status == "fail")
+
+ @property
+ def unevaluated(self) -> tuple[Criterion, ...]:
+ return tuple(c for c in self.criteria if c.status == "unevaluated")
+
+ @property
+ def accepted(self) -> bool:
+ return not self.failures
+
+ @property
+ def complete(self) -> bool:
+ return not self.unevaluated
+
+ @property
+ def verdict(self) -> str:
+ if not self.accepted:
+ return "rejected"
+ return "accepted" if self.complete else "accepted-with-unevaluated"
+
+ def criterion(self, name: str) -> Criterion:
+ for candidate in self.criteria:
+ if candidate.name == name:
+ return candidate
+ raise KeyError(name)
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "gate": "R4",
+ "intendedClass": self.intended_class,
+ "band": self.band_name,
+ "verdict": self.verdict,
+ "accepted": self.accepted,
+ "complete": self.complete,
+ "criteria": [c.to_dict() for c in self.criteria],
+ }
+
+
+def accepts(
+ measured_features: Any,
+ band: TargetBand,
+ intended_class: str,
+ classifier: Optional[Callable[..., Any]] = None,
+ *,
+ classifier_input: Any = None,
+ foot_slide_result: Optional[FootSlideReport] = None,
+ declared_loop: Optional[bool] = None,
+ source_ranges: Optional[Mapping[str, Sequence[float]]] = None,
+ authored_ranges: Optional[Mapping[str, Sequence[float]]] = None,
+) -> Acceptance:
+ """Gate R4, in full.
+
+ classifier(authored) == intended class (§2 agrees)
+ footSlide <= 0.01H during every stance frame
+ scaleDelta == 0 (never author joint scale)
+ poseReturn <= 0.5 deg for any clip declared loop
+ no joint exceeds its measured range from the source clips, where source clips exist
+
+ plus the containment check §R4's loop is built around: the measured features land inside
+ the target band.
+
+ **"Looks right" is not a criterion.** Every entry below is a number against a bound. The
+ classifier is deliberately not told the intended class — it is handed the measurement and
+ asked what the clip is, and the answer either matches or the clip is rejected. A gate the
+ author can talk their way past is not a gate.
+
+ Any criterion whose input is absent reports `unevaluated` with a reason and does not
+ count as a pass (CONTRACT: "It is never silently a pass"). `declared_loop=False` also
+ reports `unevaluated` on the poseReturn criterion, with the reason that a non-loop clip
+ is out of the criterion's scope — under a three-value vocabulary that is more honest than
+ recording a pass nobody checked.
+
+ `classifier_input` exists because the two halves read different measurements. The band
+ check wants `band_features()`'s hip-relative, per-limb dict; §2's classifier wants the
+ world-space pooled `ClipFeatures` its thresholds were derived from, and would be a
+ different classifier if handed anything else. Pass the `ClipFeatures` here and the merged
+ dict as `measured_features`; when omitted, both read `measured_features`.
+ """
+ criteria: list[Criterion] = []
+
+ # --- band containment ---------------------------------------------------------------
+ check = band.contains(measured_features)
+ if check.outside:
+ criteria.append(
+ Criterion(
+ name="band-containment",
+ status="fail",
+ reason=check.summary(),
+ detail=check.to_dict(),
+ )
+ )
+ elif check.unevaluated:
+ criteria.append(
+ Criterion(
+ name="band-containment",
+ status="unevaluated",
+ reason=check.summary(),
+ detail=check.to_dict(),
+ )
+ )
+ else:
+ criteria.append(
+ Criterion(
+ name="band-containment",
+ status="pass",
+ reason=check.summary(),
+ detail=check.to_dict(),
+ )
+ )
+
+ # --- §2 must agree ------------------------------------------------------------------
+ classifier = classifier or default_classifier()
+ if classifier is None:
+ criteria.append(
+ Criterion(
+ name="classifier-agreement",
+ status="unevaluated",
+ reason=(
+ "no §2 classifier available: clip_features could not be imported and no `classifier` "
+ "was supplied. The acceptance test for a designed clip IS the classifier, so this is "
+ "the criterion that matters most and it was not run."
+ ),
+ )
+ )
+ else:
+ subject = as_classifier_input(measured_features if classifier_input is None else classifier_input)
+ primary, labels = classifier_verdict(classifier(subject))
+ agrees = intended_class == primary or intended_class in labels
+ criteria.append(
+ Criterion(
+ name="classifier-agreement",
+ status="pass" if agrees else "fail",
+ reason=(
+ f"§2 classified the authored clip as {primary!r} (labels {list(labels)}), "
+ f"intended {intended_class!r}" + ("" if agrees else " — the classifier does not agree")
+ ),
+ detail={"primary": primary, "labels": list(labels), "intended": intended_class},
+ )
+ )
+
+ # --- foot slide ---------------------------------------------------------------------
+ if foot_slide_result is None:
+ slide_value = feature_value(measured_features, "footSlide")
+ if slide_value is None:
+ criteria.append(
+ Criterion(
+ name="foot-slide",
+ status="unevaluated",
+ reason=(
+ "no footSlide measurement: pass `foot_slide_result=foot_slide(...)`, or a "
+ "`footSlide` feature. A gait with no stance data has not passed G8, it has "
+ "not been asked."
+ ),
+ )
+ )
+ else:
+ ok = slide_value <= FOOT_SLIDE_LIMIT
+ criteria.append(
+ Criterion(
+ name="foot-slide",
+ status="pass" if ok else "fail",
+ reason=f"footSlide {slide_value:.6g}H vs limit {FOOT_SLIDE_LIMIT:.6g}H",
+ detail={"footSlide": slide_value, "limit": FOOT_SLIDE_LIMIT},
+ )
+ )
+ else:
+ criteria.append(
+ Criterion(
+ name="foot-slide",
+ status=foot_slide_result.status,
+ reason=foot_slide_result.reason,
+ detail=foot_slide_result.to_dict(),
+ )
+ )
+
+ # --- never author joint scale -------------------------------------------------------
+ scale_delta = feature_value(measured_features, "scaleDelta")
+ if scale_delta is None:
+ criteria.append(
+ Criterion(
+ name="no-joint-scale",
+ status="unevaluated",
+ reason="no scaleDelta measurement — §1 calls this a tripwire; an unread tripwire is not a pass",
+ )
+ )
+ else:
+ criteria.append(
+ Criterion(
+ name="no-joint-scale",
+ status="pass" if scale_delta == 0 else "fail",
+ reason=(
+ f"scaleDelta = {scale_delta!r}, required exactly 0"
+ + ("" if scale_delta == 0 else " — an authored clip must never scale a joint (Gate R4/G9)")
+ ),
+ detail={"scaleDelta": scale_delta},
+ )
+ )
+
+ # --- loop pose return ---------------------------------------------------------------
+ pose_return = feature_value(measured_features, "poseReturn")
+ if declared_loop is None:
+ criteria.append(
+ Criterion(
+ name="pose-return-loop",
+ status="unevaluated",
+ reason="the clip does not declare whether it loops; §4 forbids guessing false",
+ detail={"poseReturn": pose_return},
+ )
+ )
+ elif not declared_loop:
+ criteria.append(
+ Criterion(
+ name="pose-return-loop",
+ status="unevaluated",
+ reason="clip is not declared a loop, so §4's poseReturn bound is out of scope for it",
+ detail={"poseReturn": pose_return, "declaredLoop": False},
+ )
+ )
+ elif pose_return is None:
+ criteria.append(
+ Criterion(
+ name="pose-return-loop",
+ status="unevaluated",
+ reason="clip is declared a loop but carries no poseReturn measurement",
+ detail={"declaredLoop": True},
+ )
+ )
+ else:
+ ok = pose_return <= POSE_RETURN_DEGREES
+ criteria.append(
+ Criterion(
+ name="pose-return-loop",
+ status="pass" if ok else "fail",
+ reason=f"poseReturn {pose_return:.6g} deg vs {POSE_RETURN_DEGREES:.6g} deg for a declared loop",
+ detail={"poseReturn": pose_return, "limit": POSE_RETURN_DEGREES, "declaredLoop": True},
+ )
+ )
+
+ # --- joint range vs source clips ----------------------------------------------------
+ criteria.append(_joint_range_criterion(source_ranges, authored_ranges))
+
+ return Acceptance(intended_class=intended_class, band_name=band.name, criteria=tuple(criteria))
+
+
+def _joint_range_criterion(
+ source_ranges: Optional[Mapping[str, Sequence[float]]],
+ authored_ranges: Optional[Mapping[str, Sequence[float]]],
+) -> Criterion:
+ """"no joint exceeds its measured range from the source clips, **where source clips exist**".
+
+ The trailing clause is the whole point: a rig authored from scratch has no source clips,
+ so there is no measured range to stay inside and the criterion is `unevaluated`. Calling
+ that a pass would claim a bound was checked when there was no bound.
+ """
+ if not source_ranges:
+ return Criterion(
+ name="joint-range-vs-source",
+ status="unevaluated",
+ reason=(
+ "no source clips exist for this rig, so there is no measured joint range to bound the "
+ "authored one — the criterion is out of evidence, not satisfied"
+ ),
+ )
+ if not authored_ranges:
+ return Criterion(
+ name="joint-range-vs-source",
+ status="unevaluated",
+ reason="source ranges were supplied but the authored clip's per-joint ranges were not",
+ detail={"sourceJoints": sorted(source_ranges)},
+ )
+ violations: list[dict[str, Any]] = []
+ unbounded: list[str] = []
+ checked = 0
+ for joint, authored in sorted(authored_ranges.items()):
+ source = source_ranges.get(joint)
+ if source is None:
+ unbounded.append(joint)
+ continue
+ checked += 1
+ a_lo, a_hi = float(authored[0]), float(authored[1])
+ s_lo, s_hi = float(source[0]), float(source[1])
+ if a_lo < s_lo or a_hi > s_hi:
+ violations.append(
+ {"joint": joint, "authored": [a_lo, a_hi], "source": [s_lo, s_hi]}
+ )
+ if checked == 0:
+ return Criterion(
+ name="joint-range-vs-source",
+ status="unevaluated",
+ reason="no authored joint shares an id with a source-measured joint range",
+ detail={"unbounded": unbounded},
+ )
+ if violations:
+ worst = "; ".join(
+ f"{v['joint']} authored [{v['authored'][0]:.6g}, {v['authored'][1]:.6g}] exceeds source "
+ f"[{v['source'][0]:.6g}, {v['source'][1]:.6g}]"
+ for v in violations
+ )
+ return Criterion(
+ name="joint-range-vs-source",
+ status="fail",
+ reason=f"{len(violations)} of {checked} joint(s) exceed their source-measured range: {worst}",
+ detail={"violations": violations, "unbounded": unbounded, "checked": checked},
+ )
+ return Criterion(
+ name="joint-range-vs-source",
+ status="pass",
+ reason=f"all {checked} joint(s) with a source-measured range stayed inside it",
+ detail={"checked": checked, "unbounded": unbounded},
+ )
+
+
+# --------------------------------------------------------------------------------------
+# CLI
+# --------------------------------------------------------------------------------------
+
+BANDS: dict[str, Callable[[float], TargetBand]] = {"walk": walk_targets, "run": run_targets}
+
+
+def _load_input(path: str) -> dict[str, Any]:
+ with open(path, "r", encoding="utf-8") as handle:
+ return json.load(handle)
+
+
+def main(argv: Optional[Sequence[str]] = None) -> int:
+ parser = argparse.ArgumentParser(
+ description="Stage R4 acceptance: report Gate R4 for a measured clip against a target band."
+ )
+ parser.add_argument(
+ "clip_json",
+ help=(
+ "either a CONTRACT_1.5.2 sampled-clip payload (needs clip_features for measurement), "
+ "or a features document {figureHeight, features, declaredLoop?, sourceRanges?, authoredRanges?}"
+ ),
+ )
+ parser.add_argument("intended_class", help="the class the clip claims to be, e.g. walk")
+ parser.add_argument("--band", choices=sorted(BANDS), default=None, help="target band (default: intended class)")
+ parser.add_argument("--height", type=float, default=None, help="figure height H (default: from the document)")
+ parser.add_argument("--clip-index", type=int, default=0, help="which clip of a payload to accept")
+ args = parser.parse_args(argv)
+
+ document = _load_input(args.clip_json)
+ height = args.height or float(document.get("figureHeight", 1.0))
+ band_name = args.band or args.intended_class
+ if band_name not in BANDS:
+ print(json.dumps({"error": f"no target band for {band_name!r}; known: {sorted(BANDS)}"}), file=sys.stdout)
+ return 1
+ band = BANDS[band_name](height)
+
+ foot_slide_result: Optional[FootSlideReport] = None
+ classifier_input: Any = None
+ if "clips" in document:
+ clip = document["clips"][args.clip_index]
+ measure = default_measure()
+ if measure is None:
+ print(
+ json.dumps(
+ {
+ "error": (
+ "a sampled-clip payload needs clip_features.measure_clip to measure it, and that "
+ "module is not importable; supply a pre-measured features document instead"
+ )
+ }
+ )
+ )
+ return 1
+ features: Any = band_features(clip, height, measure=measure)
+ classifier_input = _call_measure(measure, clip, height)
+ if clip.get("stance"):
+ foot_slide_result = foot_slide(
+ clip["landmarkPositions"], clip["sampleTimes"], clip["stance"], height
+ )
+ declared_loop = document.get("declaredLoop", clip.get("loop"))
+ source_ranges = document.get("sourceRanges")
+ authored_ranges = document.get("authoredRanges")
+ else:
+ features = document.get("features", document)
+ declared_loop = document.get("declaredLoop")
+ source_ranges = document.get("sourceRanges")
+ authored_ranges = document.get("authoredRanges")
+
+ acceptance = accepts(
+ features,
+ band,
+ args.intended_class,
+ classifier_input=classifier_input,
+ foot_slide_result=foot_slide_result,
+ declared_loop=declared_loop,
+ source_ranges=source_ranges,
+ authored_ranges=authored_ranges,
+ )
+ report = acceptance.to_dict()
+ report["figureHeight"] = height
+ report["measuredFeatures"] = features if isinstance(features, dict) else str(features)
+ print(json.dumps(report, indent=2, sort_keys=True))
+ return 0 if acceptance.accepted else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/forge/stage5_rig/clip_features.py b/forge/stage5_rig/clip_features.py
new file mode 100644
index 0000000..5b7097f
--- /dev/null
+++ b/forge/stage5_rig/clip_features.py
@@ -0,0 +1,759 @@
+#!/usr/bin/env python3
+"""The measurement vocabulary, classifier, naming and loop rule for animation clips (1.5.2 §1-§4).
+
+WHY THIS MODULE EXISTS AT ALL. 1.5.1 shipped eleven clips named `NlaTrack`, `NlaTrack.001`, ... and
+a loop rule that contradicted its own data. Both failures have the same shape: a claim about a clip
+that nobody measured. So there is exactly one feature vector here (§1) and everything else -- the
+class, the name, the loop flag -- is a function of it. If a claim cannot be written as a function of
+these numbers it is marked `inferred` rather than dressed up as a measurement.
+
+The same vector runs in both directions. Stage R3 measures an unknown clip to identify it; Stage R4
+states a target band and measures the clip it authored to check the classifier agrees. Same code,
+so the two can never drift apart.
+
+Every length is a fraction of figure height H. Nothing here assumes H == 1.0; the payload carries it.
+
+Pure Python 3.10+ stdlib. No pip installs, no numpy, no three.js.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+# The six landmarks §1 names. Fewer than six and the vector has holes; the module refuses rather
+# than reporting a range over the joints that happened to be present.
+REQUIRED_LANDMARKS: tuple[str, ...] = ("hip", "head", "hand.l", "hand.r", "foot.l", "foot.r")
+
+# ---------------------------------------------------------------------------------------------
+# §2 thresholds. Every one of these is `single-subject`: derived from eleven clips on one rig
+# (Lee Sin, H = 1.0), with the boundaries dropped into the empty gaps between observed clusters
+# rather than at round numbers. They are starting values, not constants -- confirm the gaps survive
+# on a second rig before hardening any of them. `classify(features, thresholds=...)` takes an
+# override and the returned Classification records the set that was actually used, so a report can
+# always be traced back to the numbers that produced it.
+# ---------------------------------------------------------------------------------------------
+IDLE_TRAVEL = 0.02 # single-subject: idle-still measured travel 0.013H
+IDLE_RISE = 0.02 # single-subject: idle-still measured rise 0.0001H
+IN_PLACE_TRAVEL = 0.30 # single-subject: jump-in-place measured travel 0.272H
+WALK_SPEED = 0.30 # single-subject: walk-forward measured 0.400 H/s
+RUN_SPEED = 0.60 # single-subject: the walk/run gap is 0.400 -> 0.799 H/s
+DASH_SPEED = 1.50 # single-subject: the run/dash gap is 0.799 -> 2.250 H/s
+JUMP_RISE = 0.15 # single-subject: jump-in-place measured rise 0.248H
+LEAP_TRAVEL = 0.50 # single-subject: separates jump-in-place (0.272H) from leap (2.826H)
+PLANTED_FOOT_RANGE = 0.10 # single-subject: "feet do not participate"
+GESTURE_HAND_RANGE = 0.40 # single-subject: arms-only, and only meaningful while in-place
+
+# §4 loop rule. These two are named in CONTRACT_1.5.2.md and shared with rig_gates.
+POSE_RETURN_DEGREES = 0.5
+LOOP_HIP_TOLERANCE = 0.01
+
+# §1 tripwire. Lee Sin measured 0.000 on all eleven clips. Raising this above zero is a deliberate
+# admission that the source rig scales joints -- which changes what Stage R2 may legally do to skin
+# weights -- not a way to quiet the flag.
+SCALE_DELTA_TRIPWIRE = 0.0
+
+# Order matters and is the spec's own: jump/leap are decided by rise+travel and outrank the speed
+# classes, because a leap that covers 2.8H in 1.4s is genuinely fast but calling it `dash` loses the
+# fact that it left the ground. Speed classes outrank idle/in-place, which are the travel-only
+# fallbacks.
+MOTION_PRECEDENCE: tuple[str, ...] = ("leap", "jump", "dash", "run", "walk", "idle", "in-place")
+
+# §3. Words that describe an INTENTION. No kinematic feature distinguishes a strike from a stumble:
+# the hand accelerates, reaches, and returns in both, and the vector above is blind to which one the
+# animator meant. A label containing any of these gets `inferred: true` -- not as a placeholder for a
+# better classifier, but because it is the honest answer and there is no better classifier coming.
+INTENT_WORDS: frozenset[str] = frozenset(
+ {
+ "attack", "block", "cast", "celebrate", "channel", "charge", "counter", "death", "defeat",
+ "defend", "dodge", "emote", "greet", "guard", "hurt", "parry", "provoke", "ready", "recall",
+ "salute", "strike", "stumble", "taunt", "threaten", "victory", "wave",
+ }
+)
+
+
+@dataclass(frozen=True)
+class Thresholds:
+ """The §2 table, as data a caller can replace.
+
+ Held together in one object so a report can record the whole set rather than the two numbers
+ that happened to fire. A classification carried around without the thresholds that produced it
+ is not reproducible.
+ """
+
+ idle_travel: float = IDLE_TRAVEL
+ idle_rise: float = IDLE_RISE
+ in_place_travel: float = IN_PLACE_TRAVEL
+ walk_speed: float = WALK_SPEED
+ run_speed: float = RUN_SPEED
+ dash_speed: float = DASH_SPEED
+ jump_rise: float = JUMP_RISE
+ leap_travel: float = LEAP_TRAVEL
+ planted_foot_range: float = PLANTED_FOOT_RANGE
+ gesture_hand_range: float = GESTURE_HAND_RANGE
+ provenance: str = "single-subject (11 clips, one rig, H = 1.0)"
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "idleTravel": self.idle_travel,
+ "idleRise": self.idle_rise,
+ "inPlaceTravel": self.in_place_travel,
+ "walkSpeed": self.walk_speed,
+ "runSpeed": self.run_speed,
+ "dashSpeed": self.dash_speed,
+ "jumpRise": self.jump_rise,
+ "leapTravel": self.leap_travel,
+ "plantedFootRange": self.planted_foot_range,
+ "gestureHandRange": self.gesture_hand_range,
+ "provenance": self.provenance,
+ }
+
+
+DEFAULT_THRESHOLDS = Thresholds()
+
+
+@dataclass(frozen=True)
+class ClipFeatures:
+ """§1, measured. Every length already divided by H, so these read as fractions of figure height.
+
+ `scales_joints` is not a descriptor sitting alongside the others -- it is the tripwire. A caller
+ is expected to look at it BEFORE looking at anything else, because a rig that scales joints
+ changes what Stage R2 may legally do to skin weights.
+
+ `pose_return` is degrees and may be None: a host that cannot measure per-joint rotation deltas
+ omits it, and `decide_loop` then reports `loop: None`. It is never filled in with a zero.
+
+ `landmark_ranges` is the per-landmark, per-axis range (normalised), kept because `hand_range` and
+ `foot_range` POOL both sides -- see `measure_clip` for why that matters and what it costs.
+ """
+
+ source_name: str
+ figure_height: float
+ sample_count: int
+ duration: float
+ travel: float
+ rise: float
+ speed: float
+ hand_range: float
+ foot_range: float
+ head_rise: float
+ scale_delta: float
+ scales_joints: bool
+ pose_return: float | None
+ hip_return: float
+ landmark_ranges: dict[str, tuple[float, float, float]]
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "sourceName": self.source_name,
+ "figureHeight": self.figure_height,
+ "sampleCount": self.sample_count,
+ "duration": self.duration,
+ "travel": self.travel,
+ "rise": self.rise,
+ "speed": self.speed,
+ "handRange": self.hand_range,
+ "footRange": self.foot_range,
+ "headRise": self.head_rise,
+ "scaleDelta": self.scale_delta,
+ "scalesJoints": self.scales_joints,
+ "poseReturn": self.pose_return,
+ "hipReturn": self.hip_return,
+ "landmarkRanges": {name: list(axes) for name, axes in self.landmark_ranges.items()},
+ }
+
+
+@dataclass(frozen=True)
+class Classification:
+ """Every label that matched, plus one primary motion class -- or None.
+
+ `labels` is a set, not a winner. A clip really can be `in-place` AND `planted` AND `gesture` at
+ once; collapsing that to one string throws away the two facts a reader most wants (the feet are
+ out of it, the hands are doing the work). `primary` exists only because a UI needs one word.
+
+ `primary` is None when nothing in the table matched. There is no `unknown` class and no nearest
+ neighbour: inventing a label for a clip that fell in a gap is how a threshold table stops being
+ evidence.
+ """
+
+ labels: tuple[str, ...]
+ primary: str | None
+ reasons: dict[str, str]
+ thresholds: Thresholds
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "labels": list(self.labels),
+ "primary": self.primary,
+ "reasons": dict(self.reasons),
+ "thresholds": self.thresholds.to_dict(),
+ }
+
+
+@dataclass(frozen=True)
+class LoopDecision:
+ """§4. `loop` is tri-state: True, False, or None for "nobody measured poseReturn"."""
+
+ loop: bool | None
+ reason: str
+ pose_return: float | None
+ hip_return: float
+ pose_return_limit: float
+ hip_tolerance: float
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "loop": self.loop,
+ "reason": self.reason,
+ "poseReturn": self.pose_return,
+ "hipReturn": self.hip_return,
+ "poseReturnLimit": self.pose_return_limit,
+ "hipTolerance": self.hip_tolerance,
+ }
+
+
+@dataclass(frozen=True)
+class ClipName:
+ """§3, mirroring the TS interface. `source_name` is never discarded.
+
+ Dropping the source name breaks the parity chain back to one source animation -- the chain that
+ lets Gate R3 prove the renamed clip is byte-for-byte the clip that arrived. A friendly label is
+ worth nothing if it cannot be traced to the strip it came from.
+ """
+
+ source_name: str
+ id: str
+ label: str
+ measured: str
+ inferred: bool
+ loop: bool | None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "sourceName": self.source_name,
+ "id": self.id,
+ "label": self.label,
+ "measured": self.measured,
+ "inferred": self.inferred,
+ "loop": self.loop,
+ }
+
+
+class _Auto:
+ """Sentinel: `loop=None` and `inferred=None` are meaningful values, so absence needs its own."""
+
+ def __repr__(self) -> str: # pragma: no cover - debugging aid only
+ return "<auto>"
+
+
+AUTO = _Auto()
+
+
+# ---------------------------------------------------------------------------------------------
+# Payload validation
+# ---------------------------------------------------------------------------------------------
+
+
+def _finite(value: Any) -> bool:
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(float(value))
+
+
+def _vec3(value: Any, label: str, clip_name: str) -> tuple[float, float, float]:
+ if not isinstance(value, (list, tuple)) or len(value) != 3 or not all(_finite(item) for item in value):
+ raise ValueError(f"clip {clip_name!r}: {label} must be a finite [x, y, z]; got {value!r}")
+ return float(value[0]), float(value[1]), float(value[2])
+
+
+def _validate_clip(
+ clip: Any,
+ figure_height: float,
+ landmarks: Sequence[str] = REQUIRED_LANDMARKS,
+) -> dict[str, Any]:
+ """Check one clip against the CONTRACT_1.5.2 payload shape, or raise naming clip and field.
+
+ The error message always carries the clip's own name. A payload with eleven clips that reports
+ "sampleTimes length mismatch" and nothing else costs an afternoon of bisecting a JSON file.
+ """
+ if not isinstance(clip, Mapping):
+ raise ValueError(f"clip must be an object; got {type(clip).__name__}")
+ name = clip.get("sourceName")
+ if not isinstance(name, str) or not name.strip():
+ raise ValueError("clip.sourceName must be a non-empty string (it is never discarded, so it must exist)")
+
+ if not _finite(figure_height) or float(figure_height) <= 0.0:
+ raise ValueError(f"clip {name!r}: figureHeight must be a finite positive number; got {figure_height!r}")
+
+ duration = clip.get("duration")
+ if not _finite(duration) or float(duration) <= 0.0:
+ raise ValueError(f"clip {name!r}: duration must be a finite positive number of seconds; got {duration!r}")
+
+ times = clip.get("sampleTimes")
+ if not isinstance(times, (list, tuple)) or len(times) < 2:
+ raise ValueError(f"clip {name!r}: sampleTimes must be a list of at least 2 times")
+ if not all(_finite(t) for t in times):
+ raise ValueError(f"clip {name!r}: sampleTimes must contain only finite numbers")
+ if any(float(times[i + 1]) < float(times[i]) for i in range(len(times) - 1)):
+ raise ValueError(f"clip {name!r}: sampleTimes must be non-decreasing")
+ count = len(times)
+
+ positions = clip.get("landmarkPositions")
+ if not isinstance(positions, Mapping):
+ raise ValueError(f"clip {name!r}: landmarkPositions must be an object keyed by landmark name")
+ resolved: dict[str, list[tuple[float, float, float]]] = {}
+ for landmark in landmarks:
+ track = positions.get(landmark)
+ if track is None:
+ raise ValueError(
+ f"clip {name!r}: landmarkPositions is missing required landmark {landmark!r} "
+ f"(§1 needs all of {', '.join(landmarks)})"
+ )
+ if not isinstance(track, (list, tuple)):
+ raise ValueError(f"clip {name!r}: landmarkPositions[{landmark!r}] must be a list of [x, y, z]")
+ if len(track) != count:
+ raise ValueError(
+ f"clip {name!r}: sampleTimes has {count} entries but "
+ f"landmarkPositions[{landmark!r}] has {len(track)}; every track must be sampled at "
+ f"the same times"
+ )
+ resolved[landmark] = [_vec3(point, f"landmarkPositions[{landmark!r}][{i}]", name) for i, point in enumerate(track)]
+
+ scale_delta = clip.get("jointScaleDelta")
+ if not isinstance(scale_delta, (list, tuple)):
+ raise ValueError(
+ f"clip {name!r}: jointScaleDelta must be a list with one entry per sample "
+ f"(it is the §1 tripwire; an absent one cannot be assumed to be zero)"
+ )
+ if len(scale_delta) != count:
+ raise ValueError(
+ f"clip {name!r}: sampleTimes has {count} entries but jointScaleDelta has {len(scale_delta)}"
+ )
+ if not all(_finite(value) for value in scale_delta):
+ raise ValueError(f"clip {name!r}: jointScaleDelta must contain only finite numbers")
+
+ pose_return = clip.get("poseReturn")
+ if pose_return is not None and not _finite(pose_return):
+ raise ValueError(
+ f"clip {name!r}: poseReturn must be a finite number of degrees, or omitted entirely "
+ f"if the host cannot measure it; got {pose_return!r}"
+ )
+
+ stance = clip.get("stance")
+ if stance is not None:
+ if not isinstance(stance, Mapping):
+ raise ValueError(f"clip {name!r}: stance must be an object keyed by foot landmark")
+ for foot, intervals in stance.items():
+ if not isinstance(intervals, (list, tuple)):
+ raise ValueError(f"clip {name!r}: stance[{foot!r}] must be a list of [t0, t1] intervals")
+ for index, interval in enumerate(intervals):
+ if (
+ not isinstance(interval, (list, tuple))
+ or len(interval) != 2
+ or not all(_finite(t) for t in interval)
+ or float(interval[0]) > float(interval[1])
+ ):
+ raise ValueError(
+ f"clip {name!r}: stance[{foot!r}][{index}] must be [t0, t1] with finite t0 <= t1"
+ )
+
+ return {
+ "sourceName": name,
+ "duration": float(duration),
+ "sampleTimes": [float(t) for t in times],
+ "landmarkPositions": resolved,
+ "jointScaleDelta": [float(value) for value in scale_delta],
+ "poseReturn": None if pose_return is None else float(pose_return),
+ "stance": stance,
+ }
+
+
+def load_payload(path_or_dict: str | Path | Mapping[str, Any]) -> dict[str, Any]:
+ """Read and validate a sampled-clip payload (CONTRACT_1.5.2.md), or raise a ValueError that names
+ the offending clip and field.
+
+ Accepts a path or an already-parsed mapping so a test fixture and a file take the same route --
+ a validator that only runs on the file path is a validator half the callers skip.
+ """
+ if isinstance(path_or_dict, Mapping):
+ payload: Any = path_or_dict
+ origin = "<dict>"
+ else:
+ path = Path(path_or_dict).expanduser()
+ origin = str(path)
+ payload = json.loads(path.read_text(encoding="utf-8"))
+
+ if not isinstance(payload, Mapping):
+ raise ValueError(f"{origin}: payload root must be an object")
+
+ figure_height = payload.get("figureHeight")
+ if not _finite(figure_height) or float(figure_height) <= 0.0:
+ raise ValueError(f"{origin}: figureHeight must be a finite positive number; got {figure_height!r}")
+
+ landmarks = payload.get("landmarks", list(REQUIRED_LANDMARKS))
+ if not isinstance(landmarks, (list, tuple)) or not all(isinstance(item, str) for item in landmarks):
+ raise ValueError(f"{origin}: landmarks must be a list of strings")
+ missing = [name for name in REQUIRED_LANDMARKS if name not in landmarks]
+ if missing:
+ raise ValueError(
+ f"{origin}: landmarks is missing {', '.join(missing)}; §1 measures all six of "
+ f"{', '.join(REQUIRED_LANDMARKS)}"
+ )
+
+ clips = payload.get("clips")
+ if not isinstance(clips, (list, tuple)) or not clips:
+ raise ValueError(f"{origin}: clips must be a non-empty list")
+
+ validated = [_validate_clip(clip, float(figure_height)) for clip in clips]
+ return {
+ "figureHeight": float(figure_height),
+ "landmarks": list(landmarks),
+ "clips": validated,
+ }
+
+
+# ---------------------------------------------------------------------------------------------
+# §1 measurement
+# ---------------------------------------------------------------------------------------------
+
+
+def _axis_ranges(tracks: Sequence[Sequence[tuple[float, float, float]]]) -> tuple[float, float, float]:
+ """Per-axis (max - min) over every sample of every supplied track, pooled."""
+ ranges: list[float] = []
+ for axis in range(3):
+ values = [point[axis] for track in tracks for point in track]
+ ranges.append(max(values) - min(values))
+ return ranges[0], ranges[1], ranges[2]
+
+
+def measure_clip(clip: Mapping[str, Any], figure_height: float) -> ClipFeatures:
+ """Measure the §1 feature vector for one sampled clip.
+
+ Definitions, verbatim from §1 and then normalised by H:
+ travel max_t ||hip_xz(t) - hip_xz(0)|| -- planar, so a jump does not read as travel
+ rise max_t hip_y - min_t hip_y
+ speed travel / duration, in H per second
+ handRange / footRange largest per-axis range over BOTH hands / BOTH feet
+ headRise vertical range of the head
+ scaleDelta max over samples of the payload's per-sample max |scale_j - 1|
+
+ TWO PROPERTIES OF handRange / footRange THAT WILL BITE A CALLER WHO ASSUMES OTHERWISE:
+
+ 1. They are measured in WORLD space, so root travel is inside them. A walk that covers 1.13H
+ measures handRange ~1.13H, not the 0.15-0.25H counter-swing band §R4 quotes as a design
+ target. That is why `gesture` is gated on `in-place`: the hand-range threshold only means
+ what it says once the root is known to be still. An R4 authoring check that wants the
+ counter-swing alone must subtract the hip, and should say so.
+
+ 2. They POOL both sides before taking the range, as the vocabulary states. Pooling puts the
+ stance width inside footRange -- two feet standing perfectly still 0.12H apart measure
+ footRange 0.12H and miss the `planted` threshold despite not moving at all. `landmark_ranges`
+ carries each landmark's own per-axis range so a caller that wants the per-foot reading
+ (max over feet of that foot's own largest axis range) can take it without re-sampling.
+ """
+ validated = _validate_clip(clip, figure_height)
+ height = float(figure_height)
+ positions = validated["landmarkPositions"]
+ hip = positions["hip"]
+
+ hip_start = hip[0]
+ travel = max(math.hypot(point[0] - hip_start[0], point[2] - hip_start[2]) for point in hip) / height
+ rise = (max(point[1] for point in hip) - min(point[1] for point in hip)) / height
+ duration = validated["duration"]
+ speed = travel / duration
+
+ landmark_ranges = {
+ name: tuple(value / height for value in _axis_ranges([track]))
+ for name, track in positions.items()
+ }
+ hand_range = max(_axis_ranges([positions["hand.l"], positions["hand.r"]])) / height
+ foot_range = max(_axis_ranges([positions["foot.l"], positions["foot.r"]])) / height
+ head_rise = landmark_ranges["head"][1]
+
+ scale_delta = max(validated["jointScaleDelta"]) if validated["jointScaleDelta"] else 0.0
+ hip_end = hip[-1]
+ hip_return = math.dist(hip_end, hip_start) / height
+
+ return ClipFeatures(
+ source_name=validated["sourceName"],
+ figure_height=height,
+ sample_count=len(validated["sampleTimes"]),
+ duration=duration,
+ travel=travel,
+ rise=rise,
+ speed=speed,
+ hand_range=hand_range,
+ foot_range=foot_range,
+ head_rise=head_rise,
+ scale_delta=scale_delta,
+ scales_joints=scale_delta > SCALE_DELTA_TRIPWIRE,
+ pose_return=validated["poseReturn"],
+ hip_return=hip_return,
+ landmark_ranges=landmark_ranges, # type: ignore[arg-type]
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# §2 classification
+# ---------------------------------------------------------------------------------------------
+
+
+def classify(features: ClipFeatures, thresholds: Thresholds | None = None) -> Classification:
+ """Apply the §2 table and return EVERY label that matched, plus one primary motion class.
+
+ Labels are not mutually exclusive and are not ranked: `arms-only` is `in-place` and `planted` and
+ `gesture`, all three measured, all three true. `primary` picks one motion class out of
+ idle/walk/run/dash/jump/leap/in-place by MOTION_PRECEDENCE for callers that need a single word,
+ and is None when the clip fell in a gap between clusters. A gap is a finding, not a bug to be
+ smoothed over with a nearest-neighbour guess.
+ """
+ limits = thresholds or DEFAULT_THRESHOLDS
+ labels: list[str] = []
+ reasons: dict[str, str] = {}
+
+ def hit(label: str, reason: str) -> None:
+ labels.append(label)
+ reasons[label] = reason
+
+ if features.travel < limits.idle_travel and features.rise < limits.idle_rise:
+ hit("idle", f"travel {features.travel:.4f} < {limits.idle_travel} and rise {features.rise:.4f} < {limits.idle_rise}")
+ in_place = features.travel < limits.in_place_travel
+ if in_place:
+ hit("in-place", f"travel {features.travel:.4f} < {limits.in_place_travel}")
+ if limits.walk_speed <= features.speed < limits.run_speed:
+ hit("walk", f"{limits.walk_speed} <= speed {features.speed:.4f} < {limits.run_speed}")
+ if limits.run_speed <= features.speed < limits.dash_speed:
+ hit("run", f"{limits.run_speed} <= speed {features.speed:.4f} < {limits.dash_speed}")
+ if features.speed >= limits.dash_speed:
+ hit("dash", f"speed {features.speed:.4f} >= {limits.dash_speed}")
+ if features.rise >= limits.jump_rise and features.travel < limits.leap_travel:
+ hit("jump", f"rise {features.rise:.4f} >= {limits.jump_rise} and travel {features.travel:.4f} < {limits.leap_travel}")
+ if features.rise >= limits.jump_rise and features.travel >= limits.leap_travel:
+ hit("leap", f"rise {features.rise:.4f} >= {limits.jump_rise} and travel {features.travel:.4f} >= {limits.leap_travel}")
+ if features.foot_range < limits.planted_foot_range:
+ hit("planted", f"footRange {features.foot_range:.4f} < {limits.planted_foot_range}")
+ if in_place and features.hand_range >= limits.gesture_hand_range:
+ hit("gesture", f"handRange {features.hand_range:.4f} >= {limits.gesture_hand_range} while in-place")
+
+ primary = next((label for label in MOTION_PRECEDENCE if label in labels), None)
+ return Classification(
+ labels=tuple(labels),
+ primary=primary,
+ reasons=reasons,
+ thresholds=limits,
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# §4 the loop rule -- corrected
+# ---------------------------------------------------------------------------------------------
+
+
+def decide_loop(
+ features: ClipFeatures,
+ pose_return_limit: float = POSE_RETURN_DEGREES,
+ hip_tolerance: float = LOOP_HIP_TOLERANCE,
+) -> LoopDecision:
+ """Decide whether a clip can repeat seamlessly. glTF carries no loop flag, so someone must.
+
+ loop <=> poseReturn <= 0.5 deg per rotation joint AND ||hip(T) - hip(0)|| <= 0.01H
+
+ WHY NOT THE 1.5.1 RULE. 1.5.1 used "a clip that neither travels nor rises can repeat seamlessly",
+ and that rule contradicted the very data it was derived from: `idle-gesture` measured
+ travel = 0.121H -- six times the idle threshold -- and was correctly marked loopable. What makes
+ a clip loop is not that the root stays put but that THE LAST POSE RETURNS TO THE FIRST. Measured
+ on the joint transforms, the corrected rule accepts a clip that wanders and comes back and
+ rejects one that ends mid-stride a centimetre from where it started. `travel` and `rise` remain
+ descriptors; they stop being the loop criterion.
+
+ UNDECIDABLE IS A THIRD ANSWER. A host that cannot measure per-joint rotation deltas omits
+ `poseReturn`, and this returns `loop=None`. Defaulting to False would look conservative and be
+ a lie: it would silently mark every loopable clip as one-shot on any host without the
+ measurement, and nothing downstream could tell the difference between "measured, does not loop"
+ and "nobody looked".
+ """
+ if features.pose_return is None:
+ return LoopDecision(
+ loop=None,
+ reason="poseReturn not measured",
+ pose_return=None,
+ hip_return=features.hip_return,
+ pose_return_limit=pose_return_limit,
+ hip_tolerance=hip_tolerance,
+ )
+
+ pose_ok = features.pose_return <= pose_return_limit
+ hip_ok = features.hip_return <= hip_tolerance
+ if pose_ok and hip_ok:
+ reason = (
+ f"poseReturn {features.pose_return:.3f} deg <= {pose_return_limit} and "
+ f"||hip(T) - hip(0)|| {features.hip_return:.4f}H <= {hip_tolerance}H"
+ )
+ return LoopDecision(True, reason, features.pose_return, features.hip_return, pose_return_limit, hip_tolerance)
+
+ failures = []
+ if not pose_ok:
+ failures.append(f"poseReturn {features.pose_return:.3f} deg > {pose_return_limit}")
+ if not hip_ok:
+ failures.append(f"||hip(T) - hip(0)|| {features.hip_return:.4f}H > {hip_tolerance}H")
+ return LoopDecision(False, "; ".join(failures), features.pose_return, features.hip_return, pose_return_limit, hip_tolerance)
+
+
+def _legacy_loop_rule_1_5_1(features: ClipFeatures, thresholds: Thresholds | None = None) -> bool:
+ """The rule §4 replaced: "a clip that neither travels nor rises can repeat seamlessly".
+
+ Kept ONLY so a test can execute the contradiction rather than describe it. `idle-gesture` travels
+ 0.121H and loops; this function returns False for it and `decide_loop` returns True. Never call
+ this from production code -- it is a regression pin, not an alternative.
+ """
+ limits = thresholds or DEFAULT_THRESHOLDS
+ return features.travel < limits.idle_travel and features.rise < limits.idle_rise
+
+
+# ---------------------------------------------------------------------------------------------
+# §3 naming
+# ---------------------------------------------------------------------------------------------
+
+_MEASURED_BY_CLASS: dict[str, tuple[str, ...]] = {
+ "walk": ("speed", "rise"),
+ "run": ("speed", "rise"),
+ "dash": ("speed", "travel"),
+ "jump": ("rise", "travel"),
+ "leap": ("rise", "travel"),
+ "idle": ("travel", "rise"),
+ "in-place": ("travel", "rise"),
+}
+
+_MEASURED_TEXT = {
+ "speed": lambda f: f"speed {f.speed:.3f} H/s",
+ "travel": lambda f: f"travel {f.travel:.3f}H",
+ "rise": lambda f: f"rise {f.rise:.3f}H",
+ "handRange": lambda f: f"handRange {f.hand_range:.3f}H",
+ "footRange": lambda f: f"footRange {f.foot_range:.3f}H",
+ "duration": lambda f: f"duration {f.duration:.3f}s",
+}
+
+
+def _slug(text: str) -> str:
+ slug = re.sub(r"[^a-z0-9]+", "-", text.strip().lower()).strip("-")
+ return slug or "clip"
+
+
+def label_implies_intent(label: str, intent_words: frozenset[str] = INTENT_WORDS) -> bool:
+ """True when any word of the label names an intention rather than a movement."""
+ return any(word in intent_words for word in re.split(r"[^a-z0-9]+", label.lower()) if word)
+
+
+def _measured_summary(features: ClipFeatures, classification: Classification) -> str:
+ keys = list(_MEASURED_BY_CLASS.get(classification.primary or "", ("travel", "rise", "speed")))
+ for label, key in (("planted", "footRange"), ("gesture", "handRange")):
+ if label in classification.labels and key not in keys:
+ keys.append(key)
+ return ", ".join(_MEASURED_TEXT[key](features) for key in keys)
+
+
+def name_clip(
+ features: ClipFeatures,
+ label: str,
+ clip_id: str | None = None,
+ inferred: bool | _Auto = AUTO,
+ loop: bool | None | _Auto = AUTO,
+ source_name: str | None = None,
+ classification: Classification | None = None,
+ intent_words: frozenset[str] = INTENT_WORDS,
+) -> ClipName:
+ """Rename a clip from its measurements and record WHICH measurement the name rests on.
+
+ Source clips arrive as `NlaTrack`, `NlaTrack.001`, ... -- Blender NLA strip names carrying no
+ information. 1.5.1 shipped those verbatim as eleven unusable buttons. Renaming is therefore
+ required, and the two rules that make it honest are:
+
+ - `source_name` survives verbatim, so the parity chain back to the source animation is intact.
+ - `inferred` is True whenever the label's wording implies intent. Detected from INTENT_WORDS by
+ default and overridable, because a label can imply intent with words no list contains. Two of
+ the eleven source clips could only be named by inference; marking them cost nothing and kept
+ the distinction between measured and guessed visible to whoever read it next.
+
+ `measured` is the short human-readable string of the numbers behind the name -- e.g.
+ "speed 0.799 H/s, rise 0.021H". It is chosen from the classification, not from the label text,
+ so a hand-written label cannot change which numbers get quoted underneath it.
+ """
+ resolved_classification = classification or classify(features)
+ resolved_loop = decide_loop(features).loop if isinstance(loop, _Auto) else loop
+ resolved_inferred = (
+ label_implies_intent(label, intent_words) if isinstance(inferred, _Auto) else bool(inferred)
+ )
+ return ClipName(
+ source_name=source_name if source_name is not None else features.source_name,
+ id=clip_id or _slug(label),
+ label=label,
+ measured=_measured_summary(features, resolved_classification),
+ inferred=resolved_inferred,
+ loop=resolved_loop,
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------------------------
+
+
+def report(payload: Mapping[str, Any]) -> dict[str, Any]:
+ """Measure, classify, name and loop-decide every clip in an already-validated payload."""
+ height = float(payload["figureHeight"])
+ entries: list[dict[str, Any]] = []
+ tripped: list[str] = []
+ for clip in payload["clips"]:
+ features = measure_clip(clip, height)
+ classification = classify(features)
+ loop = decide_loop(features)
+ label = classification.primary or features.source_name
+ name = name_clip(features, label, classification=classification, loop=loop.loop)
+ if features.scales_joints:
+ tripped.append(features.source_name)
+ entries.append(
+ {
+ "sourceName": features.source_name,
+ "features": features.to_dict(),
+ "classification": classification.to_dict(),
+ "loop": loop.to_dict(),
+ "name": name.to_dict(),
+ }
+ )
+ return {
+ "schemaVersion": 1,
+ "kind": "clip-features",
+ "figureHeight": height,
+ "clipCount": len(entries),
+ "scaleTripwire": {
+ "limit": SCALE_DELTA_TRIPWIRE,
+ "tripped": bool(tripped),
+ "clips": tripped,
+ "note": (
+ "A non-zero scaleDelta means the source rig scales joints, which changes what "
+ "Stage R2 may legally do to skin weights. Surface it before anything else proceeds."
+ ),
+ },
+ "clips": entries,
+ }
+
+
+def main(argv: list[str]) -> int:
+ if len(argv) != 1 or argv[0] in {"-h", "--help"}:
+ print("usage: clip_features.py <payload.json>", file=sys.stderr)
+ return 2
+ try:
+ payload = load_payload(argv[0])
+ result = report(payload)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 1 if result["scaleTripwire"]["tripped"] else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage5_rig/emit_animation_runtime.py b/forge/stage5_rig/emit_animation_runtime.py
new file mode 100644
index 0000000..1e5ed5a
--- /dev/null
+++ b/forge/stage5_rig/emit_animation_runtime.py
@@ -0,0 +1,457 @@
+"""Stage R5 runtime emitter: clip list -> standalone TypeScript animation runtime.
+
+Turns a list of already-identified/authored clips (Stage R3/R4 output — this
+module does not classify or author anything) into a self-contained .ts module
+that builds the R5 runtime around a three.js `AnimationMixer`: bind-space
+setup (R1), ticker collection that survives lazily-built geometry (R5.1),
+presentation-offset-vs-animated-pose ordering (R5.2), the play/seek/stop/
+advance controller contract (R5.3), and the Gate R1 harness that is the only
+check able to tell a clip that plays from a clip that merely exists.
+
+See docs/pipelines/character-rigging-animation-1.5.2.md, Stage R1 and Stage
+R5, and forge/stage5_rig/CONTRACT_1.5.2.md for the module boundary this file
+must respect (it owns emit_animation_runtime.py and nothing else; it does not
+import clip_features.py / skin_conditioning.py / action_design.py / rig_gates.py
+— its input is the plain clip-list shape documented below, not their internal
+dataclasses).
+
+Pure Python 3.10+ stdlib. No pip installs, no string.Template brace-escaping
+footguns — plain token replacement is used instead of str.format()/f-strings
+against the TS body, because that body is full of literal `{`/`}` (matches
+the idiom in forge/stage5_rig/emit_rig.py).
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any, Optional
+
+# Named export per CONTRACT_1.5.2.md's shared numeric conventions: every
+# threshold gets a module constant with the spec's name. This is the float32
+# epsilon from Stage R1's Gate R1 (docs §"Gate R1 (the one that catches
+# silent death)"): `maxSampledBindingDelta <= 2^-23`.
+BINDING_EPSILON = 2**-23
+
+# Gate R1 requires seeking each clip to AT LEAST five times ("five poses is
+# not coverage" — Stage R6/G10 makes the same point about visual sweeps, and
+# Stage R1's own gate description says "seek each clip to five times"). This
+# is a floor, not a target: callers may pass more via options, never fewer.
+MINIMUM_GATE_R1_SAMPLES = 5
+
+_REQUIRED_CLIP_KEYS = ("id", "label", "sourceName", "duration", "loop")
+
+
+def _validate_clip(clip: dict[str, Any]) -> None:
+ for key in _REQUIRED_CLIP_KEYS:
+ if key not in clip:
+ raise ValueError(f"clip missing required key '{key}': {clip!r}")
+ if clip["loop"] is not None and not isinstance(clip["loop"], bool):
+ raise ValueError(
+ f"clip '{clip.get('id')}' has loop={clip['loop']!r}; "
+ "must be True, False, or None (undecidable/unmeasured)"
+ )
+ if not isinstance(clip["duration"], (int, float)):
+ raise ValueError(f"clip '{clip.get('id')}' has non-numeric duration: {clip['duration']!r}")
+
+
+_TEMPLATE = r"""// AUTO-GENERATED by forge/stage5_rig/emit_animation_runtime.py — Stage R5 runtime.
+// Do not hand-edit; regenerate from the clip list instead.
+import * as THREE from 'three';
+
+// ---------------------------------------------------------------------------
+// Clip data. `loop: null` means Stage R3/R4 could not measure poseReturn
+// (see docs/pipelines/character-rigging-animation-1.5.2.md §"loop rule") —
+// it is NOT a synonym for `false`, and resolveLoopMode() below never treats
+// it as LoopRepeat either. Labels/sourceNames are attacker-adjacent free
+// text (JSON-escaped below); mountAnimationUI() renders them via
+// `textContent`, never `innerHTML`.
+// ---------------------------------------------------------------------------
+export interface ClipInfo {
+ id: string;
+ label: string;
+ sourceName: string;
+ duration: number;
+ loop: boolean | null;
+}
+
+export const CLIPS: ClipInfo[] = __CLIPS_JSON__;
+
+// Stage R1 Gate R1 float32 epsilon: `maxSampledBindingDelta <= 2 ** -23`.
+export const BINDING_EPSILON = 2 ** -23;
+
+export interface LoopMode {
+ mode: THREE.AnimationActionLoopStyles;
+ repetitions: number;
+ clampWhenFinished: boolean;
+}
+
+/**
+ * Loop mode comes from the MEASURED `loop` flag, never from a guess:
+ * loop === true -> LoopRepeat, Infinity
+ * loop === false -> LoopOnce, 1, clampWhenFinished = true
+ * loop === null -> LoopOnce, 1, clampWhenFinished = true, AND loop was
+ * not measured for this clip (poseReturn unmeasured /
+ * undecidable) — never silently upgraded to
+ * LoopRepeat just because that would look nicer.
+ */
+export function resolveLoopMode(clip: ClipInfo): LoopMode {
+ if (clip.loop === true) {
+ return { mode: THREE.LoopRepeat, repetitions: Infinity, clampWhenFinished: false };
+ }
+ if (clip.loop === false) {
+ return { mode: THREE.LoopOnce, repetitions: 1, clampWhenFinished: true };
+ }
+ // clip.loop === null: loop was not measured for this clip. Play once and
+ // clamp rather than assume it can repeat seamlessly.
+ return { mode: THREE.LoopOnce, repetitions: 1, clampWhenFinished: true };
+}
+
+// ---------------------------------------------------------------------------
+// Stage R1 -- Bind space. THE RULE THAT CAUSED EVERY RIGGING FAILURE IN 1.5.1.
+//
+// three.js SkinnedMesh defaults to AttachedBindMode, in which
+// bindMatrixInverse is recomputed from the mesh's matrixWorld on every
+// updateMatrixWorld, so the skinning evaluation is
+// v' = skinMatrix * bindMatrix * v // matrixWorld cancels out
+// entirely. Three things were tried before the one below, each measured:
+// 1. mesh.bind(skeleton, armature.matrixWorld) -> a
+// blank frame (the bind was applied twice).
+// 2. identity bind + a `skinSpace` wrapper transform -> the
+// figure rendered 0.5 m high and floating.
+// 3. identity bind + the armature's translation folded into the
+// display offset -> the
+// figure rendered offset by exactly that armature translation, because
+// the armature's transform is already inside skinMatrix and adding it
+// again double-counts it.
+// The rule: bind at identity, ALWAYS, and derive the display offset from the
+// mesh's own bounds — never from the armature.
+// ---------------------------------------------------------------------------
+export function computeDisplayOffset(mesh: THREE.SkinnedMesh): THREE.Vector3 {
+ mesh.geometry.computeBoundingBox();
+ const bounds = mesh.geometry.boundingBox as THREE.Box3;
+ const centre = new THREE.Vector3();
+ bounds.getCenter(centre);
+ // Bounds-only, by construction: (-centre.x, -min.y, -centre.z) seats the
+ // figure on Y = 0. No armature transform is read here, ever.
+ return new THREE.Vector3(-centre.x, -bounds.min.y, -centre.z);
+}
+
+export function bindAtIdentity(mesh: THREE.SkinnedMesh, skeleton: THREE.Skeleton, group: THREE.Object3D): void {
+ mesh.bind(skeleton, new THREE.Matrix4()); // identity, always, in attached mode
+ group.position.copy(computeDisplayOffset(mesh)); // presentation only
+}
+
+// ---------------------------------------------------------------------------
+// Stage R5.1 -- ticker collection vs lazy geometry.
+//
+// A viewer that walks the scene once at start() collecting userData.tick
+// MISSES every demo whose rig arrives later: the mixer holds the action,
+// nothing calls mixer.update, every clip plays silently. refreshTickers()
+// must be callable again, any time, and onCharacterReady() is the wiring a
+// lazily-built character calls when its payload resolves.
+// ---------------------------------------------------------------------------
+export type Tick = (dt: number, elapsed: number) => void;
+
+let tickers: Tick[] = [];
+
+export function refreshTickers(scene: THREE.Object3D): void {
+ tickers = [];
+ scene.traverse((node) => {
+ const tick = (node.userData as { tick?: Tick }).tick;
+ if (typeof tick === 'function') {
+ tickers.push(tick);
+ }
+ });
+}
+
+/** Call when a lazily-built character's rig/geometry payload resolves. */
+export function onCharacterReady(scene: THREE.Object3D): void {
+ refreshTickers(scene);
+}
+
+// ---------------------------------------------------------------------------
+// Stage R5.2 -- presentation offsets vs animated pose.
+//
+// If the viewer offsets parts for an explode/inspect view, it must subtract
+// the offset it applied last frame BEFORE the rig ticks, and re-apply it
+// AFTER. Never restore a cached rest pose here — a cached rest pose
+// overwrites whatever the animation just produced.
+// ---------------------------------------------------------------------------
+let removeExplodeOffsetHook: () => void = () => {};
+let applyExplodeOffsetHook: () => void = () => {};
+
+/** Viewer-supplied presentation hooks; both default to no-ops. */
+export function setExplodeOffsetHooks(remove: () => void, apply: () => void): void {
+ removeExplodeOffsetHook = remove;
+ applyExplodeOffsetHook = apply;
+}
+
+export function tickAll(dt: number, elapsed: number): void {
+ removeExplodeOffsetHook(); // hand the animated transform back
+ for (const tick of tickers) {
+ tick(dt, elapsed);
+ }
+ applyExplodeOffsetHook(); // presentation on top
+}
+
+// ---------------------------------------------------------------------------
+// Stage R5.3 -- controller contract.
+//
+// play(name) stopAllAction -> restore bind pose -> reset -> set loop mode -> play
+// seek(name,t) as play, then paused = true, time = t, mixer.update(0), updateMatrixWorld(true)
+// stop() stopAllAction -> restore bind pose -> active = 'idle'
+// advance(dt) mixer.update(dt) -> updateMatrixWorld(true)
+//
+// Restoring the bind pose BEFORE each play is what stops clips bleeding into
+// one another: a clip that ends mid-pose leaves joints displaced, and the
+// next clip's tracks only overwrite the joints they address.
+// ---------------------------------------------------------------------------
+interface TransformSnapshot {
+ position: THREE.Vector3;
+ quaternion: THREE.Quaternion;
+ scale: THREE.Vector3;
+}
+
+export class AnimationController {
+ readonly root: THREE.Object3D;
+ readonly mixer: THREE.AnimationMixer;
+ active: string = 'idle';
+
+ private readonly actions = new Map<string, THREE.AnimationAction>();
+ private readonly clipsById = new Map<string, ClipInfo>();
+ private readonly bindPose = new Map<THREE.Object3D, TransformSnapshot>();
+
+ constructor(root: THREE.Object3D, animationClips: THREE.AnimationClip[], clipInfos: ClipInfo[]) {
+ this.root = root;
+ this.mixer = new THREE.AnimationMixer(root);
+ this.captureBindPose();
+ for (const info of clipInfos) {
+ this.clipsById.set(info.id, info);
+ const clip = animationClips.find((candidate) => candidate.name === info.id || candidate.name === info.sourceName);
+ if (!clip) continue;
+ this.actions.set(info.id, this.mixer.clipAction(clip));
+ }
+ }
+
+ private captureBindPose(): void {
+ this.bindPose.clear();
+ this.root.traverse((node) => {
+ this.bindPose.set(node, {
+ position: node.position.clone(),
+ quaternion: node.quaternion.clone(),
+ scale: node.scale.clone(),
+ });
+ });
+ }
+
+ private restoreBindPose(): void {
+ for (const [node, pose] of this.bindPose) {
+ node.position.copy(pose.position);
+ node.quaternion.copy(pose.quaternion);
+ node.scale.copy(pose.scale);
+ }
+ }
+
+ play(name: string): void {
+ this.mixer.stopAllAction();
+ this.restoreBindPose();
+ const action = this.actions.get(name);
+ const info = this.clipsById.get(name);
+ if (!action || !info) {
+ return;
+ }
+ action.reset();
+ const loopMode = resolveLoopMode(info);
+ action.setLoop(loopMode.mode, loopMode.repetitions);
+ action.clampWhenFinished = loopMode.clampWhenFinished;
+ action.play();
+ this.active = name;
+ }
+
+ seek(name: string, t: number): void {
+ this.play(name);
+ const action = this.actions.get(name);
+ if (!action) {
+ return;
+ }
+ action.paused = true;
+ action.time = t;
+ this.mixer.update(0);
+ this.root.updateMatrixWorld(true);
+ }
+
+ stop(): void {
+ this.mixer.stopAllAction();
+ this.restoreBindPose();
+ this.active = 'idle';
+ }
+
+ advance(dt: number): void {
+ this.mixer.update(dt);
+ this.root.updateMatrixWorld(true);
+ }
+
+ getAction(name: string): THREE.AnimationAction | undefined {
+ return this.actions.get(name);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Animation UI — a MOUNT FUNCTION, not a side effect of module load, so it
+// can run after the controller exists (Stage R5.1: "Same for the animation
+// UI: mount the panel as a function so it can also run after the controller
+// exists.").
+// ---------------------------------------------------------------------------
+export function mountAnimationUI(
+ container: HTMLElement,
+ controller: AnimationController,
+ clips: ClipInfo[] = CLIPS,
+): () => void {
+ const buttons: HTMLButtonElement[] = [];
+ for (const clip of clips) {
+ const button = document.createElement('button');
+ button.textContent = clip.label; // textContent only -- never innerHTML
+ button.addEventListener('click', () => controller.play(clip.id));
+ container.appendChild(button);
+ buttons.push(button);
+ }
+ return function unmountAnimationUI(): void {
+ for (const button of buttons) {
+ container.removeChild(button);
+ }
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Gate R1 -- the ONLY check that distinguishes a clip that PLAYS from a clip
+// that merely exists, holds an action, reports a duration and drives
+// nothing. Seeks each clip to (at least) __GATE_SAMPLE_COUNT__ evenly spaced
+// times and, at each one, compares the actually-bound node transform against
+// what the track's own interpolant says it should be.
+// ---------------------------------------------------------------------------
+export interface GateR1ClipResult {
+ clipId: string;
+ maxSampledBindingDelta: number;
+ sampleTimes: number[];
+ passed: boolean;
+}
+
+function trackNodeAndProperty(trackName: string): { nodeName: string; property: 'position' | 'quaternion' | 'scale' } {
+ const dot = trackName.lastIndexOf('.');
+ const nodeName = trackName.slice(0, dot);
+ const rawProperty = trackName.slice(dot + 1);
+ const property = rawProperty === 'quaternion' || rawProperty === 'scale' ? rawProperty : 'position';
+ return { nodeName, property };
+}
+
+function readTransformComponent(node: THREE.Object3D, property: 'position' | 'quaternion' | 'scale'): number[] {
+ if (property === 'quaternion') {
+ return node.quaternion.toArray();
+ }
+ if (property === 'scale') {
+ return node.scale.toArray();
+ }
+ return node.position.toArray();
+}
+
+function maxComponentDelta(actual: number[], expected: ArrayLike<number>): number {
+ let max = 0;
+ for (let i = 0; i < actual.length; i++) {
+ const delta = Math.abs(actual[i] - (expected[i] as number));
+ if (delta > max) {
+ max = delta;
+ }
+ }
+ return max;
+}
+
+export function runGateR1(
+ controller: AnimationController,
+ animationClips: THREE.AnimationClip[],
+ sampleCount: number = __GATE_SAMPLE_COUNT__,
+): GateR1ClipResult[] {
+ const effectiveSamples = Math.max(__GATE_SAMPLE_COUNT__, sampleCount);
+ const results: GateR1ClipResult[] = [];
+ for (const clip of animationClips) {
+ let maxDelta = 0;
+ const sampleTimes: number[] = [];
+ for (let i = 0; i < effectiveSamples; i++) {
+ const t = effectiveSamples === 1 ? 0 : (clip.duration * i) / (effectiveSamples - 1);
+ sampleTimes.push(t);
+ controller.seek(clip.name, t);
+ for (const track of clip.tracks) {
+ const { nodeName, property } = trackNodeAndProperty(track.name);
+ const node = controller.root.getObjectByName(nodeName);
+ if (!node) {
+ continue;
+ }
+ const interpolant = track.createInterpolant();
+ const expected = interpolant.evaluate(t);
+ const actual = readTransformComponent(node, property);
+ const delta = maxComponentDelta(actual, expected);
+ if (delta > maxDelta) {
+ maxDelta = delta;
+ }
+ }
+ }
+ results.push({
+ clipId: clip.name,
+ maxSampledBindingDelta: maxDelta,
+ sampleTimes,
+ passed: maxDelta <= BINDING_EPSILON,
+ });
+ }
+ return results;
+}
+"""
+
+
+def emit_animation_runtime(clips: list[dict[str, Any]], options: Optional[dict[str, Any]] = None) -> str:
+ """Emit the Stage R5 runtime TypeScript module for `clips`.
+
+ `clips` items carry `id`, `label`, `sourceName`, `duration`, and `loop`
+ (`True`/`False`/`None` — `None` means poseReturn was unmeasured /
+ undecidable and must be emitted as `LoopOnce` with a comment, never
+ silently `LoopRepeat`).
+
+ `options`, all optional:
+ - `gate_sample_count` (int, default 5): the default sample count baked
+ into `runGateR1`'s signature. Gate R1 (docs §Stage R1) requires
+ seeking each clip to AT LEAST five times; values below
+ `MINIMUM_GATE_R1_SAMPLES` are rejected, not silently clamped, so a
+ caller cannot accidentally under-sample the one gate that catches
+ silent binding failure.
+ """
+ options = options or {}
+ for clip in clips:
+ _validate_clip(clip)
+
+ gate_sample_count = int(options.get("gate_sample_count", MINIMUM_GATE_R1_SAMPLES))
+ if gate_sample_count < MINIMUM_GATE_R1_SAMPLES:
+ raise ValueError(
+ f"gate_sample_count={gate_sample_count} is below MINIMUM_GATE_R1_SAMPLES="
+ f"{MINIMUM_GATE_R1_SAMPLES}; Gate R1 requires seeking each clip at least "
+ "five times to be a meaningful check"
+ )
+
+ clips_payload = [
+ {
+ "id": clip["id"],
+ "label": clip["label"],
+ "sourceName": clip["sourceName"],
+ "duration": clip["duration"],
+ "loop": clip["loop"],
+ }
+ for clip in clips
+ ]
+
+ replacements = {
+ "__CLIPS_JSON__": json.dumps(clips_payload, indent=2),
+ "__GATE_SAMPLE_COUNT__": str(gate_sample_count),
+ }
+ source = _TEMPLATE
+ for token, value in replacements.items():
+ if token not in source:
+ raise AssertionError(f"template token {token} not found — template/replacement drift")
+ source = source.replace(token, value)
+ return source
diff --git a/forge/stage5_rig/emit_rig.py b/forge/stage5_rig/emit_rig.py
index 5d1c126..5b04dec 100644
--- a/forge/stage5_rig/emit_rig.py
+++ b/forge/stage5_rig/emit_rig.py
@@ -281,6 +281,12 @@ export function createRigMilestone0() {
// world space, which requires the root bone to be a child of the mesh, not
// a sibling. Learned from createRiggedDragon.ts (`body.add(bones.root)`).
mesh.add(root);
+ // The bones are now in REST position. updateMatrixWorld() before constructing the
+ // Skeleton is load-bearing: calculateInverses() reads each bone's CURRENT world matrix,
+ // and those inverses are what cancel the rest pose during skinning. Constructed before
+ // this call it captures identity matrices, the rest pose never cancels, and every
+ // vertex is displaced by its bone's offset at rest.
+ mesh.updateMatrixWorld(true);
const skeleton = new THREE.Skeleton(BONE_IDS.map((id) => bones[id]));
mesh.bindMode = THREE.AttachedBindMode;
mesh.bind(skeleton);
diff --git a/forge/stage5_rig/glb_rig_reference.py b/forge/stage5_rig/glb_rig_reference.py
new file mode 100644
index 0000000..5a8292b
--- /dev/null
+++ b/forge/stage5_rig/glb_rig_reference.py
@@ -0,0 +1,1437 @@
+#!/usr/bin/env python3
+"""Read a GLB's OWN rig -- joints, inverse binds, clips -- instead of assuming one (1.5.2 §R0, §R3).
+
+WHY THIS MODULE EXISTS AT ALL. A reference GLB arrives carrying a real skin (`skinCount: 1`) and
+real clips (`animationCount: 11`), and the pipeline then authors a skeleton *procedurally* from the
+componentTree. Those are two different skeletons. The GLB's animation channels target GLB **node
+indices**; the GLB's `JOINTS_0` attribute indexes the GLB's **own** `skin.joints` array. Feeding
+either index space into a procedurally authored skeleton addresses a different bone at every index,
+which is exactly what "the mesh comes out badly broken or disjointed" looks like from the outside.
+The fast lane makes it worse by merging 69 GLB nodes into 20 components, so no 1:1 node -> component
+mapping exists to fall back on.
+
+So the rig is read out as explicit, validated data and the joint correspondence is made an artifact
+you can audit, not an assumption nobody wrote down.
+
+THE ORDERING RULE, from §R0.3, is the load-bearing one:
+
+ bones[i] is the node for skin.joints[i] and boneInverses[i] is matrix i of the
+ inverse-bind accessor. The ordering is the SKIN'S, never the traversal's.
+
+`GlbRig.joints` is therefore in skin order and says so; nothing here sorts, re-roots or renames it.
+And per §R0.1 a node is a Bone **iff it appears in `skin.joints`** -- never inferred from a name --
+so `deform_vs_technical` counts, out loud, how many animation channels drive nodes that are not
+joints. §R0.1 states that building those as bones corrupts the skeleton's index space; that count
+is the number that makes it visible before it does.
+
+Pure Python 3.10+ stdlib. No pip installs, no numpy, no glTF library, no three.js. GLB chunk/accessor
+decoding is reused from `forge/stage1_intake/probe_glb.py` rather than reimplemented.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import struct
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Iterable, Mapping, Sequence
+
+try: # pragma: no cover - exercised by both import routes
+ from forge.stage1_intake.probe_glb import (
+ _COMPONENT_FORMATS,
+ _TYPE_COMPONENTS,
+ _accessor_bounds,
+ _buffer_view_bytes,
+ parse_glb,
+ )
+except ImportError: # pragma: no cover - direct script execution from any cwd
+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+ from forge.stage1_intake.probe_glb import (
+ _COMPONENT_FORMATS,
+ _TYPE_COMPONENTS,
+ _accessor_bounds,
+ _buffer_view_bytes,
+ parse_glb,
+ )
+
+try: # pragma: no cover - package import
+ from .clip_features import REQUIRED_LANDMARKS
+except ImportError: # pragma: no cover - flat sys.path import (how the stage5 tests load it)
+ from clip_features import REQUIRED_LANDMARKS
+
+
+# --------------------------------------------------------------------------------------------
+# Named tolerances (CONTRACT_1.5.2.md: every threshold is a named constant a caller can override)
+# --------------------------------------------------------------------------------------------
+
+# Nearest-joint radius for `correspondence`, as a fraction of figure height H. Positions are
+# MEASURED, so the tolerance is a length, not a string-similarity score.
+CORRESPONDENCE_TOLERANCE = 0.05
+
+# §1 samples every clip at N = 25 evenly spaced times.
+DEFAULT_SAMPLE_COUNT = 25
+
+# Below this, two quaternions are treated as the same rotation and slerp degenerates to a lerp.
+SLERP_EPSILON = 1e-9
+
+# A local scale component within this of 1.0 contributes nothing to the §1 `scaleDelta` tripwire.
+SCALE_UNIT_EPSILON = 0.0
+
+TRS_PATHS = ("translation", "rotation", "scale")
+ANIMATION_PATHS = TRS_PATHS + ("weights",)
+SUPPORTED_INTERPOLATIONS = ("STEP", "LINEAR")
+
+IDENTITY_MATRIX: tuple[float, ...] = (
+ 1.0, 0.0, 0.0, 0.0,
+ 0.0, 1.0, 0.0, 0.0,
+ 0.0, 0.0, 1.0, 0.0,
+ 0.0, 0.0, 0.0, 1.0,
+)
+
+INVERSE_BIND_OMITTED = "omitted-defaults-to-identity"
+
+
+class UnsupportedInterpolation(ValueError):
+ """A sampler uses an interpolation this module does not evaluate.
+
+ Raised rather than approximated. CUBICSPLINE read as LINEAR does not fail loudly -- it produces
+ a confident wrong feature vector, which is the failure mode §0 of the pipeline exists to stop.
+ """
+
+ def __init__(self, clip_name: str, interpolation: str, detail: str = "") -> None:
+ message = (
+ f"clip {clip_name!r} uses {interpolation} interpolation, which this module does not "
+ f"evaluate; it is reported unsupported rather than approximated as LINEAR"
+ )
+ if detail:
+ message = f"{message} ({detail})"
+ super().__init__(message)
+ self.clip_name = clip_name
+ self.interpolation = interpolation
+
+
+# --------------------------------------------------------------------------------------------
+# Column-major 4x4 matrix and quaternion arithmetic (glTF convention throughout)
+# --------------------------------------------------------------------------------------------
+
+
+Vec3 = tuple[float, float, float]
+Quat = tuple[float, float, float, float] # x, y, z, w -- glTF and three.js order
+Mat4 = tuple[float, ...] # 16 floats, COLUMN-major: element (row i, col j) is m[j * 4 + i]
+
+
+def compose_trs(translation: Vec3, rotation: Quat, scale: Vec3) -> Mat4:
+ """Build the column-major local matrix glTF specifies as `M = T * R * S`."""
+ x, y, z, w = rotation
+ x2, y2, z2 = x + x, y + y, z + z
+ xx, xy, xz = x * x2, x * y2, x * z2
+ yy, yz, zz = y * y2, y * z2, z * z2
+ wx, wy, wz = w * x2, w * y2, w * z2
+ sx, sy, sz = scale
+ return (
+ (1.0 - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0.0,
+ (xy - wz) * sy, (1.0 - (xx + zz)) * sy, (yz + wx) * sy, 0.0,
+ (xz + wy) * sz, (yz - wx) * sz, (1.0 - (xx + yy)) * sz, 0.0,
+ translation[0], translation[1], translation[2], 1.0,
+ )
+
+
+def multiply(a: Mat4, b: Mat4) -> Mat4:
+ """Column-major `a * b`."""
+ out = [0.0] * 16
+ for col in range(4):
+ for row in range(4):
+ out[col * 4 + row] = sum(a[k * 4 + row] * b[col * 4 + k] for k in range(4))
+ return tuple(out)
+
+
+def matrix_translation(matrix: Mat4) -> Vec3:
+ return (matrix[12], matrix[13], matrix[14])
+
+
+def decompose(matrix: Mat4) -> tuple[Vec3, Quat, Vec3]:
+ """Split a column-major matrix into T, R (xyzw), S.
+
+ Assumes no shear, which is what glTF's `node.matrix` is required to be decomposable into. A
+ sheared matrix would come back with a rotation that is not the matrix's rotation, so a node
+ carrying one is reported rather than silently decomposed (see `_node_rest_trs`).
+ """
+ sx = math.sqrt(matrix[0] ** 2 + matrix[1] ** 2 + matrix[2] ** 2)
+ sy = math.sqrt(matrix[4] ** 2 + matrix[5] ** 2 + matrix[6] ** 2)
+ sz = math.sqrt(matrix[8] ** 2 + matrix[9] ** 2 + matrix[10] ** 2)
+ determinant = (
+ matrix[0] * (matrix[5] * matrix[10] - matrix[9] * matrix[6])
+ - matrix[4] * (matrix[1] * matrix[10] - matrix[9] * matrix[2])
+ + matrix[8] * (matrix[1] * matrix[6] - matrix[5] * matrix[2])
+ )
+ if determinant < 0.0:
+ sx = -sx
+ inv_x = 1.0 / sx if sx else 0.0
+ inv_y = 1.0 / sy if sy else 0.0
+ inv_z = 1.0 / sz if sz else 0.0
+ m11, m21, m31 = matrix[0] * inv_x, matrix[1] * inv_x, matrix[2] * inv_x
+ m12, m22, m32 = matrix[4] * inv_y, matrix[5] * inv_y, matrix[6] * inv_y
+ m13, m23, m33 = matrix[8] * inv_z, matrix[9] * inv_z, matrix[10] * inv_z
+
+ trace = m11 + m22 + m33
+ if trace > 0.0:
+ s = 0.5 / math.sqrt(trace + 1.0)
+ rotation = ((m32 - m23) * s, (m13 - m31) * s, (m21 - m12) * s, 0.25 / s)
+ elif m11 > m22 and m11 > m33:
+ s = 2.0 * math.sqrt(1.0 + m11 - m22 - m33)
+ rotation = (0.25 * s, (m12 + m21) / s, (m13 + m31) / s, (m32 - m23) / s)
+ elif m22 > m33:
+ s = 2.0 * math.sqrt(1.0 + m22 - m11 - m33)
+ rotation = ((m12 + m21) / s, 0.25 * s, (m23 + m32) / s, (m13 - m31) / s)
+ else:
+ s = 2.0 * math.sqrt(1.0 + m33 - m11 - m22)
+ rotation = ((m13 + m31) / s, (m23 + m32) / s, 0.25 * s, (m21 - m12) / s)
+ return (matrix[12], matrix[13], matrix[14]), normalize_quat(rotation), (sx, sy, sz)
+
+
+def normalize_quat(q: Quat) -> Quat:
+ length = math.sqrt(q[0] ** 2 + q[1] ** 2 + q[2] ** 2 + q[3] ** 2)
+ if length == 0.0:
+ return (0.0, 0.0, 0.0, 1.0)
+ return (q[0] / length, q[1] / length, q[2] / length, q[3] / length)
+
+
+def slerp(a: Quat, b: Quat, t: float) -> Quat:
+ """Spherical linear interpolation on the shorter arc.
+
+ A normalised lerp is NOT a substitute: over a wide arc it advances at the wrong rate, so a
+ landmark sampled from it is in the wrong place at every interior time. `test_..._slerp_not_lerp`
+ pins a case where the two differ by degrees.
+ """
+ if t <= 0.0:
+ return a
+ if t >= 1.0:
+ return b
+ cos_half = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]
+ if cos_half < 0.0:
+ b = (-b[0], -b[1], -b[2], -b[3])
+ cos_half = -cos_half
+ if cos_half >= 1.0 - SLERP_EPSILON:
+ # Degenerate arc: the endpoints are the same rotation, so lerp and slerp agree.
+ return normalize_quat(
+ (
+ a[0] + (b[0] - a[0]) * t,
+ a[1] + (b[1] - a[1]) * t,
+ a[2] + (b[2] - a[2]) * t,
+ a[3] + (b[3] - a[3]) * t,
+ )
+ )
+ sin_half = math.sqrt(1.0 - cos_half * cos_half)
+ half_theta = math.atan2(sin_half, cos_half)
+ ratio_a = math.sin((1.0 - t) * half_theta) / sin_half
+ ratio_b = math.sin(t * half_theta) / sin_half
+ return normalize_quat(
+ (
+ a[0] * ratio_a + b[0] * ratio_b,
+ a[1] * ratio_a + b[1] * ratio_b,
+ a[2] * ratio_a + b[2] * ratio_b,
+ a[3] * ratio_a + b[3] * ratio_b,
+ )
+ )
+
+
+def quaternion_angle_degrees(a: Quat, b: Quat) -> float:
+ """Absolute rotation angle between two unit quaternions, in degrees, ignoring double cover."""
+ a = normalize_quat(a)
+ b = normalize_quat(b)
+ dot = abs(a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3])
+ dot = min(1.0, max(-1.0, dot))
+ return math.degrees(2.0 * math.acos(dot))
+
+
+# --------------------------------------------------------------------------------------------
+# Accessor decoding (chunk/bufferView plumbing reused from probe_glb)
+# --------------------------------------------------------------------------------------------
+
+
+_NORMALISATION = {
+ 5120: lambda v: max(v / 127.0, -1.0),
+ 5121: lambda v: v / 255.0,
+ 5122: lambda v: max(v / 32767.0, -1.0),
+ 5123: lambda v: v / 65535.0,
+}
+
+
+def read_accessor(document: Mapping[str, Any], bin_payload: bytes, index: int) -> list[tuple[float, ...]]:
+ """Decode accessor `index` into one tuple of floats per element.
+
+ Handles the componentTypes and element types glTF allows for skins and animation samplers,
+ including `normalized` integer quantisation. Sparse accessors are refused by name rather than
+ decoded as their (wrong) base view.
+ """
+ accessors = document.get("accessors", [])
+ if not isinstance(accessors, list) or not 0 <= index < len(accessors):
+ raise ValueError(f"missing accessor {index}")
+ accessor = accessors[index]
+ if not isinstance(accessor, dict):
+ raise ValueError(f"accessor {index} is not an object")
+ if "sparse" in accessor:
+ raise ValueError(
+ f"accessor {index} uses sparse storage, which this reader does not decode; "
+ f"reading its base bufferView alone would return values the file does not mean"
+ )
+ element_type = accessor.get("type")
+ components = _TYPE_COMPONENTS.get(str(element_type))
+ if components is None:
+ raise ValueError(f"accessor {index} has unsupported type {element_type!r}")
+ component_type = int(accessor.get("componentType", 5126))
+ fmt_info = _COMPONENT_FORMATS.get(component_type)
+ if fmt_info is None:
+ raise ValueError(f"accessor {index} has unsupported componentType {component_type}")
+ fmt, component_bytes = fmt_info
+ count = int(accessor.get("count", 0))
+ if count < 0:
+ raise ValueError(f"accessor {index} has a negative count")
+
+ view_index = accessor.get("bufferView")
+ if view_index is None:
+ # glTF: an accessor with no bufferView reads as zeros. Say so; do not pretend it is data.
+ return [tuple([0.0] * components) for _ in range(count)]
+ raw = _buffer_view_bytes(document, bin_payload, int(view_index))
+ view = document["bufferViews"][int(view_index)]
+ element_bytes = component_bytes * components
+ stride = int(view.get("byteStride", element_bytes) or element_bytes)
+ if stride < element_bytes:
+ raise ValueError(f"bufferView stride {stride} is too small for accessor {index}")
+ base = int(accessor.get("byteOffset", 0))
+ normalise = _NORMALISATION.get(component_type) if accessor.get("normalized") else None
+
+ out: list[tuple[float, ...]] = []
+ for element in range(count):
+ offset = base + element * stride
+ if offset + element_bytes > len(raw):
+ raise ValueError(f"accessor {index} element {element} exceeds its bufferView")
+ values = struct.unpack_from(f"<{components}{fmt}", raw, offset)
+ if normalise is not None:
+ out.append(tuple(float(normalise(value)) for value in values))
+ else:
+ out.append(tuple(float(value) for value in values))
+ return out
+
+
+# --------------------------------------------------------------------------------------------
+# The rig record
+# --------------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class GlbJoint:
+ """One entry of `skin.joints`. `skin_joint_index` is the authority for every other index."""
+
+ skin_joint_index: int
+ node_index: int
+ node_name: str
+ parent_node_index: int | None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "skinJointIndex": self.skin_joint_index,
+ "nodeIndex": self.node_index,
+ "nodeName": self.node_name,
+ "parentNodeIndex": self.parent_node_index,
+ }
+
+
+@dataclass(frozen=True)
+class GlbSkinRecord:
+ """A single skin, read in its own joint order.
+
+ `inverse_bind_source` is either `accessor:<n>` or `omitted-defaults-to-identity`. glTF says an
+ absent `inverseBindMatrices` means identity, and that is a legal file -- but a caller that sees
+ sixteen-float identities with no provenance cannot tell "the file said identity" from "the
+ reader failed and filled in identity", so the two are never rendered the same way here.
+ """
+
+ skin_index: int
+ name: str
+ skeleton_node_index: int | None
+ joints: tuple[GlbJoint, ...]
+ inverse_bind_matrices: tuple[Mat4, ...]
+ inverse_bind_source: str
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "skinIndex": self.skin_index,
+ "name": self.name,
+ "skeletonNodeIndex": self.skeleton_node_index,
+ "jointCount": len(self.joints),
+ "jointOrder": "skin.joints (§R0.3: the ordering is the skin's, never the traversal's)",
+ "joints": [joint.to_dict() for joint in self.joints],
+ "inverseBindSource": self.inverse_bind_source,
+ "inverseBindMatrices": [list(matrix) for matrix in self.inverse_bind_matrices],
+ }
+
+
+@dataclass(frozen=True)
+class GlbChannel:
+ animation_index: int
+ channel_index: int
+ sampler_index: int
+ target_node_index: int | None
+ path: str
+ interpolation: str
+ key_count: int
+ time_min: float
+ time_max: float
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "channelIndex": self.channel_index,
+ "samplerIndex": self.sampler_index,
+ "targetNodeIndex": self.target_node_index,
+ "path": self.path,
+ "interpolation": self.interpolation,
+ "keyCount": self.key_count,
+ "timeMin": self.time_min,
+ "timeMax": self.time_max,
+ }
+
+
+@dataclass(frozen=True)
+class GlbClip:
+ animation_index: int
+ name: str
+ channels: tuple[GlbChannel, ...]
+
+ @property
+ def duration(self) -> float:
+ """Clip length = the largest channel `timeMax`. Empty clips are 0.0, not `None`."""
+ return max((channel.time_max for channel in self.channels), default=0.0)
+
+ @property
+ def interpolations(self) -> tuple[str, ...]:
+ return tuple(sorted({channel.interpolation for channel in self.channels}))
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "animationIndex": self.animation_index,
+ "name": self.name,
+ "duration": self.duration,
+ "channelCount": len(self.channels),
+ "interpolations": list(self.interpolations),
+ "channels": [channel.to_dict() for channel in self.channels],
+ }
+
+
+@dataclass
+class GlbRig:
+ """Everything the GLB itself says about its rig, with nothing inferred from names.
+
+ `joints` and `inverse_bind_matrices` are the PRIMARY skin's, in skin order, and exist only when
+ the file has exactly one skin. With zero or several skins they are empty and
+ `structural_failure` states why -- picking one for the caller would be exactly the silent guess
+ this module was written to remove.
+ """
+
+ path: str
+ node_count: int
+ nodes: tuple[dict[str, Any], ...]
+ skins: tuple[GlbSkinRecord, ...]
+ primary_skin: GlbSkinRecord | None
+ skinned_mesh_nodes: tuple[dict[str, Any], ...]
+ clips: tuple[GlbClip, ...]
+ deform_vs_technical: dict[str, Any]
+ structural_failure: str | None
+ warnings: tuple[str, ...] = ()
+ _document: dict[str, Any] = field(default_factory=dict, repr=False)
+ _bin: bytes = field(default=b"", repr=False)
+ _parents: dict[int, int | None] = field(default_factory=dict, repr=False)
+
+ # -- skin-ordered views ------------------------------------------------------------------
+
+ @property
+ def joints(self) -> tuple[GlbJoint, ...]:
+ return self.primary_skin.joints if self.primary_skin else ()
+
+ @property
+ def inverse_bind_matrices(self) -> tuple[Mat4, ...]:
+ return self.primary_skin.inverse_bind_matrices if self.primary_skin else ()
+
+ @property
+ def inverse_bind_source(self) -> str | None:
+ return self.primary_skin.inverse_bind_source if self.primary_skin else None
+
+ @property
+ def unsupported_interpolation_clips(self) -> tuple[str, ...]:
+ return tuple(
+ clip.name
+ for clip in self.clips
+ if any(
+ channel.interpolation not in SUPPORTED_INTERPOLATIONS and channel.path in TRS_PATHS
+ for channel in clip.channels
+ )
+ )
+
+ def node_name(self, index: int) -> str:
+ if 0 <= index < len(self.nodes):
+ return str(self.nodes[index]["name"])
+ return f"node-{index}"
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "schemaVersion": 1,
+ "kind": "glb-rig-reference",
+ "path": self.path,
+ "nodeCount": self.node_count,
+ "skinCount": len(self.skins),
+ "clipCount": len(self.clips),
+ "primarySkinIndex": self.primary_skin.skin_index if self.primary_skin else None,
+ "skins": [skin.to_dict() for skin in self.skins],
+ "joints": [joint.to_dict() for joint in self.joints],
+ "inverseBindSource": self.inverse_bind_source,
+ "inverseBindMatrices": [list(matrix) for matrix in self.inverse_bind_matrices],
+ "skinnedMeshNodes": list(self.skinned_mesh_nodes),
+ "clips": [clip.to_dict() for clip in self.clips],
+ "deformVsTechnical": self.deform_vs_technical,
+ "unsupportedInterpolationClips": list(self.unsupported_interpolation_clips),
+ "structuralFailure": self.structural_failure,
+ "warnings": list(self.warnings),
+ "note": (
+ "Joint order is skin.joints order (§R0.3). Animation channels address GLB node "
+ "indices and JOINTS_0 addresses this joint array; neither index space is valid "
+ "against a procedurally authored skeleton without an explicit correspondence."
+ ),
+ }
+
+
+# --------------------------------------------------------------------------------------------
+# read_rig
+# --------------------------------------------------------------------------------------------
+
+
+def _node_list(document: Mapping[str, Any]) -> list[dict[str, Any]]:
+ nodes = document.get("nodes", [])
+ return [node if isinstance(node, dict) else {} for node in nodes] if isinstance(nodes, list) else []
+
+
+def _parent_map(nodes: Sequence[Mapping[str, Any]]) -> dict[int, int | None]:
+ parents: dict[int, int | None] = {index: None for index in range(len(nodes))}
+ for index, node in enumerate(nodes):
+ children = node.get("children", [])
+ if not isinstance(children, list):
+ continue
+ for child in children:
+ child_index = int(child)
+ if 0 <= child_index < len(nodes):
+ parents[child_index] = index
+ return parents
+
+
+def read_rig(glb_path: str | Path) -> GlbRig:
+ """Extract the GLB's rig as data. Never raises on a structurally odd rig -- it records it.
+
+ A missing or ambiguous skin is a *finding* the caller has to act on, not an exception thrown
+ from the middle of a parse. `structural_failure` carries the reason; the CLI turns it into
+ exit 1.
+ """
+ path = Path(glb_path).expanduser().resolve()
+ document, bin_payload, _binary = parse_glb(path)
+ warnings: list[str] = []
+
+ nodes = _node_list(document)
+ parents = _parent_map(nodes)
+ node_records = tuple(
+ {
+ "index": index,
+ "name": node.get("name") or f"node-{index}",
+ "parentNodeIndex": parents[index],
+ "children": [int(child) for child in (node.get("children") or []) if isinstance(child, int)],
+ "mesh": node.get("mesh"),
+ "skin": node.get("skin"),
+ }
+ for index, node in enumerate(nodes)
+ )
+
+ # -- skins, each in its own joint order ---------------------------------------------------
+ raw_skins = document.get("skins", [])
+ raw_skins = raw_skins if isinstance(raw_skins, list) else []
+ skins: list[GlbSkinRecord] = []
+ for skin_index, skin in enumerate(raw_skins):
+ if not isinstance(skin, dict):
+ warnings.append(f"skin {skin_index} is not an object and was skipped")
+ continue
+ joint_indices = skin.get("joints", [])
+ if not isinstance(joint_indices, list):
+ warnings.append(f"skin {skin_index} has no joints array")
+ joint_indices = []
+ joints: list[GlbJoint] = []
+ for slot, node_index in enumerate(joint_indices):
+ node_index = int(node_index)
+ if not 0 <= node_index < len(nodes):
+ warnings.append(
+ f"skin {skin_index} joint slot {slot} references node {node_index}, which does not exist"
+ )
+ joints.append(GlbJoint(slot, node_index, f"node-{node_index}", None))
+ continue
+ joints.append(
+ GlbJoint(
+ skin_joint_index=slot,
+ node_index=node_index,
+ node_name=str(nodes[node_index].get("name") or f"node-{node_index}"),
+ parent_node_index=parents.get(node_index),
+ )
+ )
+
+ ibm_accessor = skin.get("inverseBindMatrices")
+ if ibm_accessor is None:
+ inverse_binds = tuple(IDENTITY_MATRIX for _ in joints)
+ inverse_bind_source = INVERSE_BIND_OMITTED
+ else:
+ try:
+ decoded = read_accessor(document, bin_payload, int(ibm_accessor))
+ except ValueError as exc:
+ warnings.append(f"skin {skin_index}: {exc}")
+ decoded = []
+ if len(decoded) != len(joints):
+ warnings.append(
+ f"skin {skin_index} has {len(joints)} joints but its inverseBindMatrices accessor "
+ f"holds {len(decoded)} matrices; §R0.3 pairs them index-for-index, so the pairing "
+ f"is not trustworthy"
+ )
+ inverse_binds = tuple(
+ tuple(decoded[slot]) if slot < len(decoded) and len(decoded[slot]) == 16 else IDENTITY_MATRIX
+ for slot in range(len(joints))
+ )
+ inverse_bind_source = f"accessor:{int(ibm_accessor)}"
+
+ skins.append(
+ GlbSkinRecord(
+ skin_index=skin_index,
+ name=str(skin.get("name") or f"skin-{skin_index}"),
+ skeleton_node_index=(int(skin["skeleton"]) if isinstance(skin.get("skeleton"), int) else None),
+ joints=tuple(joints),
+ inverse_bind_matrices=inverse_binds,
+ inverse_bind_source=inverse_bind_source,
+ )
+ )
+
+ primary_skin = skins[0] if len(skins) == 1 else None
+ structural_failure: str | None = None
+ if not skins:
+ structural_failure = (
+ "GLB carries no skin, so it has no rig to reference; a procedurally authored skeleton "
+ "cannot be validated against this file"
+ )
+ elif len(skins) > 1:
+ structural_failure = (
+ f"GLB carries {len(skins)} skins and no primary skin was chosen; each skin owns its own "
+ f"joint index space, so JOINTS_0 and inverse binds are only meaningful once the caller "
+ f"names one (skin indices {[skin.skin_index for skin in skins]})"
+ )
+
+ # -- skinned mesh nodes -------------------------------------------------------------------
+ skinned_mesh_nodes = tuple(
+ {
+ "nodeIndex": index,
+ "nodeName": str(node.get("name") or f"node-{index}"),
+ "meshIndex": int(node["mesh"]),
+ "skinIndex": int(node["skin"]),
+ }
+ for index, node in enumerate(nodes)
+ if isinstance(node.get("mesh"), int) and isinstance(node.get("skin"), int)
+ )
+
+ # -- clips --------------------------------------------------------------------------------
+ raw_animations = document.get("animations", [])
+ raw_animations = raw_animations if isinstance(raw_animations, list) else []
+ clips: list[GlbClip] = []
+ for animation_index, animation in enumerate(raw_animations):
+ if not isinstance(animation, dict):
+ warnings.append(f"animation {animation_index} is not an object and was skipped")
+ continue
+ samplers = animation.get("samplers", [])
+ samplers = samplers if isinstance(samplers, list) else []
+ raw_channels = animation.get("channels", [])
+ raw_channels = raw_channels if isinstance(raw_channels, list) else []
+ channels: list[GlbChannel] = []
+ for channel_index, channel in enumerate(raw_channels):
+ if not isinstance(channel, dict):
+ continue
+ sampler_index = channel.get("sampler")
+ target = channel.get("target") if isinstance(channel.get("target"), dict) else {}
+ path_name = str(target.get("path", "")) or "unknown"
+ target_node = target.get("node")
+ target_node_index = int(target_node) if isinstance(target_node, int) else None
+ interpolation = "LINEAR"
+ key_count = 0
+ time_min = 0.0
+ time_max = 0.0
+ if isinstance(sampler_index, int) and 0 <= sampler_index < len(samplers):
+ sampler = samplers[sampler_index]
+ if isinstance(sampler, dict):
+ interpolation = str(sampler.get("interpolation", "LINEAR"))
+ input_accessor = sampler.get("input")
+ if isinstance(input_accessor, int):
+ try:
+ times = [value[0] for value in read_accessor(document, bin_payload, input_accessor)]
+ except ValueError as exc:
+ warnings.append(f"animation {animation_index} channel {channel_index}: {exc}")
+ times = []
+ key_count = len(times)
+ if times:
+ time_min = min(times)
+ time_max = max(times)
+ else:
+ warnings.append(
+ f"animation {animation_index} channel {channel_index} references missing sampler {sampler_index!r}"
+ )
+ channels.append(
+ GlbChannel(
+ animation_index=animation_index,
+ channel_index=channel_index,
+ sampler_index=int(sampler_index) if isinstance(sampler_index, int) else -1,
+ target_node_index=target_node_index,
+ path=path_name,
+ interpolation=interpolation,
+ key_count=key_count,
+ time_min=time_min,
+ time_max=time_max,
+ )
+ )
+ clips.append(
+ GlbClip(
+ animation_index=animation_index,
+ name=str(animation.get("name") or f"animation-{animation_index}"),
+ channels=tuple(channels),
+ )
+ )
+
+ deform_vs_technical = _deform_vs_technical(skins, primary_skin, clips, node_records)
+ if deform_vs_technical.get("channelsTargetingTechnicalNodes"):
+ warnings.append(
+ f"{deform_vs_technical['channelsTargetingTechnicalNodes']} animation channels target nodes "
+ f"that are not in skin.joints; §R0.1 says building those as bones corrupts the skeleton's "
+ f"index space"
+ )
+
+ return GlbRig(
+ path=str(path),
+ node_count=len(nodes),
+ nodes=node_records,
+ skins=tuple(skins),
+ primary_skin=primary_skin,
+ skinned_mesh_nodes=skinned_mesh_nodes,
+ clips=tuple(clips),
+ deform_vs_technical=deform_vs_technical,
+ structural_failure=structural_failure,
+ warnings=tuple(warnings),
+ _document=dict(document),
+ _bin=bin_payload,
+ _parents=parents,
+ )
+
+
+def _deform_vs_technical(
+ skins: Sequence[GlbSkinRecord],
+ primary_skin: GlbSkinRecord | None,
+ clips: Sequence[GlbClip],
+ node_records: Sequence[Mapping[str, Any]],
+) -> dict[str, Any]:
+ """§R0.1: classify every animation-targeted node as deform (in skin.joints) or technical.
+
+ With no skin at all there is no membership test, so this reports `unevaluated` with a reason
+ (CONTRACT_1.5.2: a check whose input is absent is never silently a pass).
+ """
+ targeted: dict[int, int] = {}
+ channels_without_target = 0
+ for clip in clips:
+ for channel in clip.channels:
+ if channel.target_node_index is None:
+ channels_without_target += 1
+ continue
+ targeted[channel.target_node_index] = targeted.get(channel.target_node_index, 0) + 1
+
+ if not skins:
+ return {
+ "status": "unevaluated",
+ "reason": "GLB carries no skin, so 'is this node in skin.joints' has no answer here",
+ "basis": None,
+ "targetedNodeCount": len(targeted),
+ "channelsWithoutTargetNode": channels_without_target,
+ "deformNodes": [],
+ "technicalNodes": [],
+ "channelsTargetingJoints": None,
+ "channelsTargetingTechnicalNodes": None,
+ }
+
+ if primary_skin is not None:
+ joint_nodes = {joint.node_index for joint in primary_skin.joints}
+ basis = f"primarySkin:{primary_skin.skin_index}"
+ else:
+ joint_nodes = {joint.node_index for skin in skins for joint in skin.joints}
+ basis = "unionOfAllSkins"
+
+ def name_of(index: int) -> str:
+ if 0 <= index < len(node_records):
+ return str(node_records[index]["name"])
+ return f"node-{index}"
+
+ deform_nodes = []
+ technical_nodes = []
+ deform_channels = 0
+ technical_channels = 0
+ for node_index in sorted(targeted):
+ record = {"nodeIndex": node_index, "nodeName": name_of(node_index), "channelCount": targeted[node_index]}
+ if node_index in joint_nodes:
+ deform_nodes.append(record)
+ deform_channels += targeted[node_index]
+ else:
+ technical_nodes.append(record)
+ technical_channels += targeted[node_index]
+
+ return {
+ "status": "evaluated",
+ "reason": None,
+ "basis": basis,
+ "rule": "§R0.1: a node is a Bone IFF it appears in skin.joints; never inferred from names",
+ "targetedNodeCount": len(targeted),
+ "channelsWithoutTargetNode": channels_without_target,
+ "deformNodes": deform_nodes,
+ "technicalNodes": technical_nodes,
+ "channelsTargetingJoints": deform_channels,
+ "channelsTargetingTechnicalNodes": technical_channels,
+ }
+
+
+# --------------------------------------------------------------------------------------------
+# Rest-pose world matrices and figure height
+# --------------------------------------------------------------------------------------------
+
+
+def _node_rest_trs(node: Mapping[str, Any]) -> tuple[Vec3, Quat, Vec3]:
+ matrix = node.get("matrix")
+ if isinstance(matrix, list) and len(matrix) == 16:
+ return decompose(tuple(float(value) for value in matrix))
+ translation = node.get("translation", [0.0, 0.0, 0.0])
+ rotation = node.get("rotation", [0.0, 0.0, 0.0, 1.0])
+ scale = node.get("scale", [1.0, 1.0, 1.0])
+ return (
+ (float(translation[0]), float(translation[1]), float(translation[2])),
+ normalize_quat((float(rotation[0]), float(rotation[1]), float(rotation[2]), float(rotation[3]))),
+ (float(scale[0]), float(scale[1]), float(scale[2])),
+ )
+
+
+def _world_matrices(
+ nodes: Sequence[Mapping[str, Any]],
+ parents: Mapping[int, int | None],
+ local: Sequence[Mat4],
+) -> list[Mat4]:
+ """Compose local matrices up the hierarchy. §R0.2: link first, then root -- any other order
+ leaves world matrices stale at skeleton time."""
+ world: list[Mat4 | None] = [None] * len(nodes)
+
+ def resolve(index: int, guard: frozenset[int]) -> Mat4:
+ cached = world[index]
+ if cached is not None:
+ return cached
+ if index in guard:
+ raise ValueError(f"node {index} is part of a parent cycle; the hierarchy is not a tree")
+ parent = parents.get(index)
+ if parent is None:
+ value = local[index]
+ else:
+ value = multiply(resolve(parent, guard | {index}), local[index])
+ world[index] = value
+ return value
+
+ return [resolve(index, frozenset()) for index in range(len(nodes))]
+
+
+def rest_world_matrices(rig: GlbRig) -> list[Mat4]:
+ nodes = _node_list(rig._document)
+ local = [compose_trs(*_node_rest_trs(node)) for node in nodes]
+ return _world_matrices(nodes, rig._parents, local)
+
+
+def joint_rest_positions(rig: GlbRig) -> dict[int, Vec3]:
+ """Model-space position of each PRIMARY-SKIN joint at rest, keyed by skin joint index."""
+ world = rest_world_matrices(rig)
+ return {
+ joint.skin_joint_index: matrix_translation(world[joint.node_index])
+ for joint in rig.joints
+ if 0 <= joint.node_index < len(world)
+ }
+
+
+def derive_figure_height(rig: GlbRig) -> tuple[float, str]:
+ """Figure height H from the GLB's own mesh bounds (Y extent), with its provenance.
+
+ Everything in 1.5.2 is a fraction of H, so H is never assumed to be 1.0. If it cannot be
+ measured the caller is told to supply it rather than handed a default.
+ """
+ meshes = rig._document.get("meshes", [])
+ meshes = meshes if isinstance(meshes, list) else []
+ lows: list[float] = []
+ highs: list[float] = []
+ for mesh in meshes:
+ if not isinstance(mesh, dict):
+ continue
+ for primitive in mesh.get("primitives", []) or []:
+ if not isinstance(primitive, dict):
+ continue
+ attributes = primitive.get("attributes", {})
+ position = attributes.get("POSITION") if isinstance(attributes, dict) else None
+ if position is None:
+ continue
+ try:
+ minimum, maximum, _ = _accessor_bounds(rig._document, rig._bin, int(position))
+ except ValueError:
+ continue
+ if math.isfinite(minimum[1]) and math.isfinite(maximum[1]):
+ lows.append(minimum[1])
+ highs.append(maximum[1])
+ if not lows:
+ raise ValueError(
+ "figure height could not be measured from the GLB's mesh bounds; pass figure_height "
+ "explicitly rather than letting a module assume H == 1.0"
+ )
+ height = max(highs) - min(lows)
+ if height <= 0.0:
+ raise ValueError("figure height measured as zero from the GLB's mesh bounds; pass it explicitly")
+ return height, "meshPositionBoundsYExtent"
+
+
+# --------------------------------------------------------------------------------------------
+# Correspondence -- the thing the 1.5.2 pipeline says is missing
+# --------------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class BoneMatch:
+ bone_id: str
+ bone_position: Vec3
+ skin_joint_index: int | None
+ node_index: int | None
+ node_name: str | None
+ distance_h: float | None
+ confidence: float
+ reason: str
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "boneId": self.bone_id,
+ "bonePosition": list(self.bone_position),
+ "skinJointIndex": self.skin_joint_index,
+ "nodeIndex": self.node_index,
+ "nodeName": self.node_name,
+ "distanceH": self.distance_h,
+ "confidence": self.confidence,
+ "reason": self.reason,
+ }
+
+
+@dataclass(frozen=True)
+class Correspondence:
+ """An explicit procedural-bone -> GLB-joint map, matched by MEASURED POSITION.
+
+ The 1.5.2 pipeline lists retargeting between skeletons under "What this pipeline does not
+ solve": *"Everything here assumes one skeleton. Cross-rig retarget needs a joint correspondence
+ and its own gates."* This supplies the correspondence half and states its own limit instead of
+ implying the problem is closed:
+
+ * Matching is positional, never by name. Exporters emit `node_17`, `mixamorig:LeftArm` and
+ `Bone.003` for the same anatomy; a name match is a coincidence detector.
+ * `usable` is False whenever ANY joint on EITHER side is unmatched. A partial map retargets
+ the bones it knows and leaves the rest at bind pose, which is the disjointed mesh this
+ module exists to prevent -- so a partial map is reported as unusable, not as progress.
+ * Gates are still owed. This is the correspondence, not the "own gates" the spec also asks
+ for.
+ """
+
+ figure_height: float
+ tolerance: float
+ matches: tuple[BoneMatch, ...]
+ unmatched_procedural_bones: tuple[str, ...]
+ unmatched_glb_joints: tuple[dict[str, Any], ...]
+ usable: bool
+ reason: str
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "figureHeight": self.figure_height,
+ "tolerance": self.tolerance,
+ "toleranceUnit": "fraction of figure height H",
+ "matchedBy": "measured model-space position (never node names)",
+ "matches": [match.to_dict() for match in self.matches],
+ "unmatchedProceduralBones": list(self.unmatched_procedural_bones),
+ "unmatchedGlbJoints": [dict(joint) for joint in self.unmatched_glb_joints],
+ "usable": self.usable,
+ "reason": self.reason,
+ "limit": (
+ "1.5.2 lists cross-rig retarget as unsolved and needing 'a joint correspondence and "
+ "its own gates'. This is the correspondence; the gates are not supplied here."
+ ),
+ }
+
+
+def _bone_position(bone: Mapping[str, Any]) -> Vec3:
+ for key in ("position", "jointPosition", "modelPosition", "head"):
+ value = bone.get(key)
+ if isinstance(value, (list, tuple)) and len(value) == 3:
+ return (float(value[0]), float(value[1]), float(value[2]))
+ raise ValueError(
+ f"procedural bone {bone.get('id')!r} has no model-space joint position "
+ f"(expected one of position/jointPosition/modelPosition/head)"
+ )
+
+
+def correspondence(
+ glb_rig: GlbRig,
+ component_bones: Sequence[Mapping[str, Any]],
+ figure_height: float | None = None,
+ tolerance: float = CORRESPONDENCE_TOLERANCE,
+) -> Correspondence:
+ """Match procedurally derived bones to the GLB's skin joints by position.
+
+ `component_bones` is `[{"id": str, "position": [x, y, z]}, ...]` in the same model space as the
+ GLB's rest pose. Assignment is globally greedy on distance and mutually exclusive, so two
+ procedural bones can never claim the same GLB joint and quietly double-drive it.
+ """
+ if figure_height is None:
+ figure_height, _source = derive_figure_height(glb_rig)
+ if not math.isfinite(figure_height) or figure_height <= 0.0:
+ raise ValueError(f"figure_height must be a finite positive number; got {figure_height!r}")
+
+ joints = glb_rig.joints
+ if not joints:
+ return Correspondence(
+ figure_height=figure_height,
+ tolerance=tolerance,
+ matches=(),
+ unmatched_procedural_bones=tuple(str(bone.get("id")) for bone in component_bones),
+ unmatched_glb_joints=(),
+ usable=False,
+ reason=(
+ glb_rig.structural_failure
+ or "the GLB exposes no primary skin, so there are no joints to correspond to"
+ ),
+ )
+
+ joint_positions = joint_rest_positions(glb_rig)
+ bones = list(component_bones)
+ bone_positions = [_bone_position(bone) for bone in bones]
+
+ limit = tolerance * figure_height
+ candidates: list[tuple[float, int, int]] = []
+ for bone_i, bone_position in enumerate(bone_positions):
+ for joint in joints:
+ joint_position = joint_positions.get(joint.skin_joint_index)
+ if joint_position is None:
+ continue
+ distance = math.dist(bone_position, joint_position)
+ if distance <= limit:
+ candidates.append((distance, bone_i, joint.skin_joint_index))
+ candidates.sort(key=lambda item: (item[0], item[1], item[2]))
+
+ claimed_bones: dict[int, tuple[float, int]] = {}
+ claimed_joints: set[int] = set()
+ for distance, bone_i, joint_slot in candidates:
+ if bone_i in claimed_bones or joint_slot in claimed_joints:
+ continue
+ claimed_bones[bone_i] = (distance, joint_slot)
+ claimed_joints.add(joint_slot)
+
+ matches: list[BoneMatch] = []
+ unmatched_bones: list[str] = []
+ for bone_i, bone in enumerate(bones):
+ bone_id = str(bone.get("id", f"bone-{bone_i}"))
+ claim = claimed_bones.get(bone_i)
+ if claim is None:
+ unmatched_bones.append(bone_id)
+ matches.append(
+ BoneMatch(
+ bone_id=bone_id,
+ bone_position=bone_positions[bone_i],
+ skin_joint_index=None,
+ node_index=None,
+ node_name=None,
+ distance_h=None,
+ confidence=0.0,
+ reason=f"no GLB joint within {tolerance}H ({limit:.6g} in model units)",
+ )
+ )
+ continue
+ distance, joint_slot = claim
+ joint = joints[joint_slot]
+ distance_h = distance / figure_height
+ confidence = max(0.0, min(1.0, 1.0 - distance_h / tolerance)) if tolerance > 0 else 0.0
+ matches.append(
+ BoneMatch(
+ bone_id=bone_id,
+ bone_position=bone_positions[bone_i],
+ skin_joint_index=joint.skin_joint_index,
+ node_index=joint.node_index,
+ node_name=joint.node_name,
+ distance_h=distance_h,
+ confidence=confidence,
+ reason=f"nearest GLB joint at {distance_h:.4f}H, inside the {tolerance}H tolerance",
+ )
+ )
+
+ unmatched_joints = tuple(
+ joint.to_dict() for joint in joints if joint.skin_joint_index not in claimed_joints
+ )
+
+ if not unmatched_bones and not unmatched_joints:
+ usable = True
+ reason = (
+ f"every one of {len(bones)} procedural bones and all {len(joints)} GLB joints matched "
+ f"within {tolerance}H"
+ )
+ else:
+ usable = False
+ parts = []
+ if unmatched_bones:
+ parts.append(f"{len(unmatched_bones)} procedural bone(s) matched no GLB joint ({', '.join(unmatched_bones)})")
+ if unmatched_joints:
+ names = ", ".join(str(joint["nodeName"]) for joint in unmatched_joints)
+ parts.append(f"{len(unmatched_joints)} GLB joint(s) matched no procedural bone ({names})")
+ reason = (
+ "; ".join(parts)
+ + ". A partial correspondence retargets the bones it knows and leaves the rest at bind "
+ "pose, which is the disjointed-mesh failure this module exists to prevent, so it is "
+ "not usable for retargeting."
+ )
+
+ return Correspondence(
+ figure_height=figure_height,
+ tolerance=tolerance,
+ matches=tuple(matches),
+ unmatched_procedural_bones=tuple(unmatched_bones),
+ unmatched_glb_joints=unmatched_joints,
+ usable=usable,
+ reason=reason,
+ )
+
+
+# --------------------------------------------------------------------------------------------
+# Clip sampling -- TRS evaluation of the GLB's OWN channels
+# --------------------------------------------------------------------------------------------
+
+
+@dataclass
+class _Sampler:
+ times: list[float]
+ values: list[tuple[float, ...]]
+ interpolation: str
+
+
+def _load_samplers(rig: GlbRig, clip: GlbClip) -> dict[int, _Sampler]:
+ animation = rig._document["animations"][clip.animation_index]
+ raw_samplers = animation.get("samplers", [])
+ loaded: dict[int, _Sampler] = {}
+ for index, sampler in enumerate(raw_samplers):
+ if not isinstance(sampler, dict):
+ continue
+ input_accessor = sampler.get("input")
+ output_accessor = sampler.get("output")
+ if not isinstance(input_accessor, int) or not isinstance(output_accessor, int):
+ continue
+ times = [value[0] for value in read_accessor(rig._document, rig._bin, input_accessor)]
+ values = read_accessor(rig._document, rig._bin, output_accessor)
+ loaded[index] = _Sampler(times, values, str(sampler.get("interpolation", "LINEAR")))
+ return loaded
+
+
+def _bracket(times: Sequence[float], t: float) -> tuple[int, int, float]:
+ """Return (i, j, alpha) with times[i] <= t <= times[j]. Clamps outside the key range."""
+ if not times:
+ raise ValueError("sampler has no key times")
+ if t <= times[0]:
+ return 0, 0, 0.0
+ if t >= times[-1]:
+ last = len(times) - 1
+ return last, last, 0.0
+ low, high = 0, len(times) - 1
+ while high - low > 1:
+ middle = (low + high) // 2
+ if times[middle] <= t:
+ low = middle
+ else:
+ high = middle
+ span = times[high] - times[low]
+ alpha = 0.0 if span <= 0.0 else (t - times[low]) / span
+ return low, high, alpha
+
+
+def _evaluate_sampler(sampler: _Sampler, path: str, t: float, clip_name: str) -> tuple[float, ...]:
+ if sampler.interpolation not in SUPPORTED_INTERPOLATIONS:
+ raise UnsupportedInterpolation(clip_name, sampler.interpolation, f"path {path!r}")
+ low, high, alpha = _bracket(sampler.times, t)
+ if low >= len(sampler.values) or high >= len(sampler.values):
+ raise ValueError(
+ f"clip {clip_name!r}: sampler output has {len(sampler.values)} values for "
+ f"{len(sampler.times)} key times"
+ )
+ a = sampler.values[low]
+ b = sampler.values[high]
+ if sampler.interpolation == "STEP" or low == high or alpha == 0.0:
+ # STEP holds the value of the key at or before t, all the way to the next key.
+ return a
+ if path == "rotation":
+ quat = slerp(
+ (a[0], a[1], a[2], a[3]),
+ (b[0], b[1], b[2], b[3]),
+ alpha,
+ )
+ return quat
+ return tuple(a[i] + (b[i] - a[i]) * alpha for i in range(min(len(a), len(b))))
+
+
+def _pose_at(
+ rig: GlbRig,
+ nodes: Sequence[Mapping[str, Any]],
+ rest: Sequence[tuple[Vec3, Quat, Vec3]],
+ channels: Sequence[tuple[GlbChannel, _Sampler]],
+ t: float,
+ clip_name: str,
+) -> tuple[list[Mat4], list[tuple[Vec3, Quat, Vec3]]]:
+ """Local TRS for every node at time t (rest, overridden by the clip's channels), then world."""
+ trs = [(item[0], item[1], item[2]) for item in rest]
+ for channel, sampler in channels:
+ if channel.target_node_index is None or channel.path not in TRS_PATHS:
+ continue
+ index = channel.target_node_index
+ if not 0 <= index < len(trs):
+ continue
+ value = _evaluate_sampler(sampler, channel.path, t, clip_name)
+ translation, rotation, scale = trs[index]
+ if channel.path == "translation" and len(value) >= 3:
+ translation = (value[0], value[1], value[2])
+ elif channel.path == "rotation" and len(value) >= 4:
+ rotation = normalize_quat((value[0], value[1], value[2], value[3]))
+ elif channel.path == "scale" and len(value) >= 3:
+ scale = (value[0], value[1], value[2])
+ trs[index] = (translation, rotation, scale)
+ local = [compose_trs(*item) for item in trs]
+ return _world_matrices(nodes, rig._parents, local), trs
+
+
+def sample_clips(
+ glb_rig: GlbRig,
+ landmark_node_indices: Mapping[str, int],
+ sample_count: int = DEFAULT_SAMPLE_COUNT,
+ figure_height: float | None = None,
+) -> dict[str, Any]:
+ """Evaluate the GLB's own channels and emit a CONTRACT_1.5.2 sampled-clip payload.
+
+ The output is exactly what `clip_features.load_payload` / `measure_clip` consume, so a rig that
+ ARRIVES with clips (§R3) goes through the same §1 vocabulary as a rig whose clips were authored
+ (§R4) -- no second measurement path that can drift.
+
+ What is evaluated, and what is not:
+
+ * TRS is interpolated here, not delegated: LINEAR lerp for translation/scale, SLERP for
+ rotation, STEP as a hold. Locals are composed up the hierarchy, so landmark positions are
+ WORLD positions, which is what §1 measures.
+ * CUBICSPLINE raises `UnsupportedInterpolation` naming the clip. Reading it as LINEAR would
+ produce a feature vector that is confident and wrong.
+ * `weights` (morph) channels are not evaluated at all -- they cannot move a node -- and are
+ counted in `provenance.morphWeightChannelsIgnored`.
+ * `stance` is omitted. This host cannot measure foot contact, and CONTRACT_1.5.2 says a host
+ that cannot measure a field omits it rather than guessing.
+ """
+ missing = [name for name in REQUIRED_LANDMARKS if name not in landmark_node_indices]
+ if missing:
+ raise ValueError(
+ f"landmark_node_indices is missing {', '.join(missing)}; §1 measures all six of "
+ f"{', '.join(REQUIRED_LANDMARKS)} and a payload without them is rejected downstream"
+ )
+ if sample_count < 2:
+ raise ValueError(f"sample_count must be at least 2; got {sample_count}")
+ if figure_height is None:
+ figure_height, height_source = derive_figure_height(glb_rig)
+ else:
+ height_source = "caller"
+ if not math.isfinite(figure_height) or figure_height <= 0.0:
+ raise ValueError(f"figure_height must be a finite positive number; got {figure_height!r}")
+
+ nodes = _node_list(glb_rig._document)
+ for name, node_index in landmark_node_indices.items():
+ if not 0 <= int(node_index) < len(nodes):
+ raise ValueError(f"landmark {name!r} points at node {node_index}, which does not exist")
+ rest = [_node_rest_trs(node) for node in nodes]
+ joint_node_indices = [joint.node_index for joint in glb_rig.joints]
+
+ payload_clips: list[dict[str, Any]] = []
+ skipped: list[dict[str, Any]] = []
+ morph_channels_ignored = 0
+
+ for clip in glb_rig.clips:
+ duration = clip.duration
+ if duration <= 0.0:
+ skipped.append(
+ {
+ "sourceName": clip.name,
+ "reason": "clip duration is zero (no channel carries a positive timeMax)",
+ }
+ )
+ continue
+ samplers = _load_samplers(glb_rig, clip)
+ bound: list[tuple[GlbChannel, _Sampler]] = []
+ for channel in clip.channels:
+ sampler = samplers.get(channel.sampler_index)
+ if sampler is None:
+ continue
+ if channel.path == "weights":
+ morph_channels_ignored += 1
+ continue
+ if channel.path not in TRS_PATHS:
+ continue
+ if sampler.interpolation not in SUPPORTED_INTERPOLATIONS:
+ raise UnsupportedInterpolation(clip.name, sampler.interpolation, f"path {channel.path!r}")
+ bound.append((channel, sampler))
+
+ times = [duration * index / (sample_count - 1) for index in range(sample_count)]
+ landmark_positions: dict[str, list[list[float]]] = {name: [] for name in landmark_node_indices}
+ joint_scale_delta: list[float] = []
+ first_rotations: list[Quat] | None = None
+ last_rotations: list[Quat] | None = None
+
+ for sample_index, t in enumerate(times):
+ world, trs = _pose_at(glb_rig, nodes, rest, bound, t, clip.name)
+ for name, node_index in landmark_node_indices.items():
+ position = matrix_translation(world[int(node_index)])
+ landmark_positions[name].append([position[0], position[1], position[2]])
+ if joint_node_indices:
+ delta = 0.0
+ for node_index in joint_node_indices:
+ if not 0 <= node_index < len(trs):
+ continue
+ scale = trs[node_index][2]
+ delta = max(delta, max(abs(axis - 1.0) for axis in scale))
+ joint_scale_delta.append(delta if delta > SCALE_UNIT_EPSILON else 0.0)
+ else:
+ joint_scale_delta.append(0.0)
+ rotations = [
+ trs[node_index][1] for node_index in joint_node_indices if 0 <= node_index < len(trs)
+ ]
+ if sample_index == 0:
+ first_rotations = rotations
+ last_rotations = rotations
+
+ if first_rotations and last_rotations and len(first_rotations) == len(last_rotations):
+ pose_return = max(
+ quaternion_angle_degrees(a, b) for a, b in zip(first_rotations, last_rotations)
+ )
+ else:
+ # No joints to measure: omit the key rather than claim 0.0. CONTRACT_1.5.2 makes an
+ # absent poseReturn mean "undecidable", which is the truth here.
+ pose_return = None
+
+ clip_payload: dict[str, Any] = {
+ "sourceName": clip.name,
+ "duration": duration,
+ "sampleTimes": times,
+ "landmarkPositions": landmark_positions,
+ "jointScaleDelta": joint_scale_delta,
+ }
+ if pose_return is not None:
+ clip_payload["poseReturn"] = pose_return
+ payload_clips.append(clip_payload)
+
+ return {
+ "figureHeight": float(figure_height),
+ "landmarks": list(landmark_node_indices.keys()),
+ "clips": payload_clips,
+ "provenance": {
+ "source": glb_rig.path,
+ "sampledFrom": "the GLB's own animation channels, evaluated by glb_rig_reference",
+ "figureHeightSource": height_source,
+ "sampleCount": sample_count,
+ "landmarkNodeIndices": {name: int(index) for name, index in landmark_node_indices.items()},
+ "jointCount": len(joint_node_indices),
+ "morphWeightChannelsIgnored": morph_channels_ignored,
+ "skippedClips": skipped,
+ "stance": "omitted: this host cannot measure foot contact (CONTRACT_1.5.2 §stance)",
+ },
+ }
+
+
+# --------------------------------------------------------------------------------------------
+# CLI
+# --------------------------------------------------------------------------------------------
+
+
+def _load_landmarks(raw: str) -> dict[str, int]:
+ path = Path(raw).expanduser()
+ text = path.read_text(encoding="utf-8") if path.is_file() else raw
+ parsed = json.loads(text)
+ if not isinstance(parsed, dict):
+ raise ValueError("--landmarks must be a JSON object mapping landmark name -> node index")
+ return {str(key): int(value) for key, value in parsed.items()}
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description="Read a GLB's own rig as explicit, validated data.")
+ parser.add_argument("glb", type=Path)
+ parser.add_argument("--sample-clips", action="store_true", help="also emit a CONTRACT_1.5.2 sampled-clip payload")
+ parser.add_argument("--landmarks", help="JSON object (path or literal) mapping the six §1 landmarks to node indices")
+ parser.add_argument("--skin", type=int, help="choose one skin by index when the GLB carries several")
+ parser.add_argument("--figure-height", type=float, help="figure height H; measured from mesh bounds when omitted")
+ parser.add_argument("--sample-count", type=int, default=DEFAULT_SAMPLE_COUNT)
+ parser.add_argument("--out", type=Path, help="also write the artifact")
+ args = parser.parse_args(argv)
+
+ errors: list[str] = []
+ try:
+ rig = read_rig(args.glb)
+ except Exception as exc: # noqa: BLE001 - the file itself is unreadable
+ print(json.dumps({"ok": False, "kind": "glb-rig-reference", "errors": [str(exc)]}, indent=2))
+ return 2
+
+ if args.skin is not None:
+ chosen = [skin for skin in rig.skins if skin.skin_index == args.skin]
+ if not chosen:
+ errors.append(f"--skin {args.skin} is not one of {[skin.skin_index for skin in rig.skins]}")
+ else:
+ rig.primary_skin = chosen[0]
+ rig.structural_failure = None
+ rig.deform_vs_technical = _deform_vs_technical(rig.skins, chosen[0], rig.clips, rig.nodes)
+
+ if rig.structural_failure:
+ errors.append(rig.structural_failure)
+
+ result = rig.to_dict()
+
+ if args.sample_clips:
+ if not args.landmarks:
+ errors.append("--sample-clips needs --landmarks; §1 measures six named world landmarks")
+ else:
+ try:
+ payload = sample_clips(
+ rig,
+ _load_landmarks(args.landmarks),
+ sample_count=args.sample_count,
+ figure_height=args.figure_height,
+ )
+ result["sampledClips"] = payload
+ except UnsupportedInterpolation as exc:
+ errors.append(str(exc))
+ except (ValueError, KeyError, OSError, json.JSONDecodeError) as exc:
+ errors.append(f"sampling failed: {exc}")
+
+ result["ok"] = not errors
+ result["errors"] = errors
+ rendered = json.dumps(result, indent=2, ensure_ascii=False) + "\n"
+ if args.out:
+ output = args.out.expanduser().resolve()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ temporary = output.with_suffix(output.suffix + ".tmp")
+ temporary.write_text(rendered, encoding="utf-8")
+ temporary.replace(output)
+ print(rendered, end="")
+ return 1 if errors else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage5_rig/mesh_parity.py b/forge/stage5_rig/mesh_parity.py
new file mode 100644
index 0000000..20b2c39
--- /dev/null
+++ b/forge/stage5_rig/mesh_parity.py
@@ -0,0 +1,903 @@
+#!/usr/bin/env python3
+"""Stage R — mesh geometry freeze and the parity gate that proves the freeze held.
+
+WHY THIS EXISTS
+---------------
+Rigging a model that is already built is meant to be an ADDITIVE operation: a skeleton appears, two
+new vertex attributes appear, some clips appear. Nothing about it requires touching a single
+position, normal, uv or index. In practice the animation pass is exactly where meshes come back
+disjointed -- a limb regenerated at a different resolution, an index buffer rewired by a "helpful"
+weld, one vertex nudged so a joint looked better in one frame -- and by the time the damage is
+visible it is buried under a rig that was built on top of it, so it is no longer clear whether the
+mesh or the skinning is at fault.
+
+So the geometry is FROZEN. A mesh-repair phase may fix broken meshes first; then `freeze` records
+every geometry buffer and its hash, and from that point the implementation phase may only ADD.
+`verify` re-hashes the same buffers afterwards and proves, per mesh and per attribute, that nothing
+moved.
+
+WHAT IS FROZEN, AND THE ONE THING THAT IS DELIBERATELY NOT
+-----------------------------------------------------------
+FROZEN_ATTRIBUTES = ("position", "normal", "uv"), plus "index" -- together FROZEN_BUFFERS.
+
+`skinIndex` and `skinWeight` are DELIBERATELY NOT FROZEN. Adding them is the entire legal purpose of
+the implementation phase: a mesh that carried no skinning attributes before rigging and carries them
+afterwards is the pass condition, not a violation. Freezing them would make every successful rig
+fail this gate, and leaving position out of the frozen set would make the gate prove nothing. That
+split is the load-bearing design decision of this module. Any attribute outside FROZEN_BUFFERS that
+turns up after the freeze is therefore reported as "added (legal)" rather than as a change -- and,
+symmetrically, a FROZEN attribute that appears only after the freeze is a failure, because adding a
+uv set post-freeze changes what the surface looks like just as surely as moving it does.
+
+WHY THE HASH IS OVER PACKED BYTES AND NOT OVER THE JSON TEXT
+-------------------------------------------------------------
+The payload arrives as JSON from a browser harness and is written back out as JSON at least once
+more. JSON float formatting is not canonical: `1.0`, `1`, `1e0` and `1.0000000000000002` are choices
+a serialiser makes, and two serialisers -- or two versions of one -- may spell the same double
+differently. Hashing the text would therefore report a change every time a formatter changed its
+mind, which is the fastest way to teach everyone to ignore the gate.
+
+So the hash is taken over the PARSED numbers, re-serialised here into a byte layout this module
+defines and controls: little-endian IEEE-754 float64 for the float buffers, little-endian
+two's-complement int64 for the index buffer. Two payloads that parse to the same numbers hash
+identically however they were spelled, and two payloads that parse to different numbers cannot be
+made to collide by formatting.
+
+The layout is bit-exact, which is the point and worth stating: `0.0` and `-0.0` are different bytes
+and therefore a reported change, and two NaNs sharing a bit pattern are the same bytes and therefore
+not one.
+
+WHY THE MANIFEST KEEPS THE BUFFERS AS WELL AS THEIR HASHES
+-----------------------------------------------------------
+A hash answers "did it change?" and nothing else. Fired on a 200k-element position buffer, "the hash
+differs" hands a human two megabytes of numbers and a diff tool. So the manifest retains the frozen
+buffers next to their hashes, and a hash mismatch is followed by a linear scan -- run ONLY after a
+mismatch -- that names the first differing element and both of its values. "element 37:
+0.5 -> 0.5001, 1 of 72,000 elements differ" is a completely different bug report from "71,998 of
+72,000 elements differ", and only the scan can tell them apart.
+
+The scan compares the same packed bytes the hash consumed, eight bytes per element, so the scan and
+the hash cannot disagree about what counts as a difference. When the scan finds NO differing element
+after the hash said there was one, that is not a contradiction to hide: it means the manifest's
+recorded hash disagrees with the manifest's own retained buffer, i.e. the manifest was edited, and
+it is reported as exactly that.
+
+Pure Python 3.10+ stdlib. No pip installs, no numpy, no three.js.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import sys
+from array import array
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+SCHEMA_VERSION = 1
+
+# The vertex attributes whose bytes may not change once frozen.
+FROZEN_ATTRIBUTES: tuple[str, ...] = ("position", "normal", "uv")
+# The index buffer is frozen on the same terms; it lives beside `attributes` in the payload rather
+# than inside it, so it is named separately and then folded into one ordered tuple.
+INDEX_KEY = "index"
+FROZEN_BUFFERS: tuple[str, ...] = FROZEN_ATTRIBUTES + (INDEX_KEY,)
+
+# Every frozen buffer is packed to 8 bytes per element -- float64 or int64 -- so the mismatch scan
+# can walk the packed bytes at a fixed stride instead of re-deriving each element's encoding.
+ELEMENT_BYTES = 8
+
+STATUS_PASS = "pass"
+STATUS_FAIL = "fail"
+STATUS_UNEVALUATED = "unevaluated"
+
+# The kinds of change a failure can report. Naming the kind (not just the mesh) is what lets a
+# reader tell "someone moved a vertex" from "someone rebuilt the mesh" without opening the payload.
+KIND_HASH = "hash mismatch"
+KIND_MESH_MISSING = "mesh missing"
+KIND_MESH_ADDED = "mesh added"
+KIND_COUNT = "count changed"
+KIND_ATTRIBUTE_MISSING = "attribute missing"
+KIND_ATTRIBUTE_ADDED = "frozen attribute added"
+KIND_DUPLICATE = "duplicate mesh name"
+KIND_MALFORMED = "malformed buffer"
+
+KINDS: tuple[str, ...] = (
+ KIND_HASH,
+ KIND_MESH_MISSING,
+ KIND_MESH_ADDED,
+ KIND_COUNT,
+ KIND_ATTRIBUTE_MISSING,
+ KIND_ATTRIBUTE_ADDED,
+ KIND_DUPLICATE,
+ KIND_MALFORMED,
+)
+
+# A failure list is for a human to read. Past this many the list stops being readable and the total
+# count is the useful part.
+_MAX_REPORTED_FAILURES = 20
+# Per mismatched buffer: the first differing element is the diagnosis, the next few show whether it
+# is a nudge or a rebuild. Everything past that is the same information repeated.
+_MAX_REPORTED_DIFFS = 8
+# Legal additions are informational, not evidence; a handful is enough to see what the rig added.
+_MAX_REPORTED_ADDITIONS = 20
+
+_ORDER = {name: position for position, name in enumerate(FROZEN_BUFFERS)}
+
+FREEZE_NOTE = (
+ "Geometry frozen. Implementation may add a skeleton, skinIndex/skinWeight and clips; it may not "
+ "change position, normal, uv or index on any mesh, and it may not add or remove meshes."
+)
+_NO_MANIFEST_REASON = (
+ "no freeze manifest was supplied, so there is nothing to compare the payload against; geometry "
+ "parity is unproven, which is not the same as unbroken"
+)
+_EMPTY_MANIFEST_REASON = (
+ "the freeze manifest records no meshes, so no geometry was ever frozen; geometry parity is "
+ "unproven, which is not the same as unbroken"
+)
+
+
+# ---------------------------------------------------------------------------------------------
+# Byte layout
+# ---------------------------------------------------------------------------------------------
+
+
+def _as_floats(values: Any, label: str) -> list[float]:
+ if not isinstance(values, list):
+ raise ValueError(f"{label} must be a list of numbers, got {type(values).__name__}")
+ out: list[float] = []
+ for position, value in enumerate(values):
+ # bool is an int subclass; `True` in a position buffer is a producer bug, not a 1.0.
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise ValueError(f"{label}[{position}] is {value!r}; a float buffer holds numbers")
+ out.append(float(value))
+ return out
+
+
+def _as_ints(values: Any, label: str) -> list[int]:
+ if not isinstance(values, list):
+ raise ValueError(f"{label} must be a list of integers, got {type(values).__name__}")
+ out: list[int] = []
+ for position, value in enumerate(values):
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise ValueError(f"{label}[{position}] is {value!r}; an index buffer holds integers")
+ if isinstance(value, float) and not value.is_integer():
+ raise ValueError(
+ f"{label}[{position}] is {value!r}; an index buffer holds whole numbers. A "
+ "fractional index means the buffer was resampled, not re-serialised."
+ )
+ out.append(int(value))
+ return out
+
+
+def _packed(name: str, values: list[float] | list[int]) -> bytes:
+ """The canonical bytes of one frozen buffer: little-endian float64, or int64 for the index.
+
+ `array` is used rather than `struct.pack("<%dd")` because the latter needs every element as a
+ separate call argument, which stops being reasonable somewhere below a real mesh's vertex count.
+ `array` is native-endian, so a big-endian host byteswaps -- without that, the same mesh would
+ hash differently on different machines and the gate would fire on the CI box alone.
+ """
+ code = "q" if name == INDEX_KEY else "d"
+ try:
+ buffer = array(code, values)
+ except OverflowError as exc:
+ raise ValueError(f"{name} does not fit a 64-bit integer buffer: {exc}") from exc
+ if sys.byteorder != "little":
+ buffer.byteswap()
+ return buffer.tobytes()
+
+
+def _hash_buffer(name: str, values: list[float] | list[int]) -> str:
+ """SHA-256 over the packed bytes, prefixed with the buffer's identity and length.
+
+ The prefix is domain separation: a normal buffer that happens to hold the same numbers as a
+ position buffer must not produce the same digest, so a hash can never be quietly moved from one
+ slot to another in a hand-edited manifest.
+ """
+ tag = "i64le" if name == INDEX_KEY else "f64le"
+ digest = hashlib.sha256()
+ digest.update(f"{name}|{len(values)}|{tag}|".encode("utf-8"))
+ digest.update(_packed(name, values))
+ return digest.hexdigest()
+
+
+# ---------------------------------------------------------------------------------------------
+# Payload reading
+# ---------------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class _PayloadMesh:
+ """One mesh as it arrives: the frozen buffers converted, everything else recorded by name only.
+
+ Non-frozen attributes are never converted or hashed. Their VALUES are none of this gate's
+ business -- skinWeight is supposed to change -- so only their existence is recorded.
+ """
+
+ name: str
+ buffers: dict[str, list[float] | list[int]]
+ extra_attributes: tuple[str, ...]
+
+
+def _read_meshes(payload: Any) -> list[_PayloadMesh]:
+ if not isinstance(payload, dict):
+ raise ValueError("payload root must be an object")
+ raw = payload.get("meshes")
+ if not isinstance(raw, list):
+ raise ValueError("payload must carry a `meshes` array")
+
+ meshes: list[_PayloadMesh] = []
+ for position, entry in enumerate(raw):
+ if not isinstance(entry, dict):
+ raise ValueError(f"meshes[{position}] must be an object")
+ name = entry.get("name")
+ if not isinstance(name, str) or not name.strip():
+ raise ValueError(f"meshes[{position}].name must be a non-empty string")
+ attributes = entry.get("attributes", {})
+ if not isinstance(attributes, dict):
+ raise ValueError(f"mesh {name!r}: `attributes` must be an object")
+ if INDEX_KEY in attributes:
+ raise ValueError(
+ f"mesh {name!r}: `index` must sit beside `attributes`, not inside it. Reading both "
+ "spellings would let a payload carry two different index buffers."
+ )
+
+ buffers: dict[str, list[float] | list[int]] = {}
+ extras: list[str] = []
+ for key, values in attributes.items():
+ if key in FROZEN_ATTRIBUTES:
+ buffers[key] = _as_floats(values, f"mesh {name!r} attribute {key!r}")
+ else:
+ if not isinstance(values, list):
+ raise ValueError(f"mesh {name!r} attribute {key!r} must be a list")
+ extras.append(key)
+ if entry.get(INDEX_KEY) is not None:
+ buffers[INDEX_KEY] = _as_ints(entry[INDEX_KEY], f"mesh {name!r} index")
+
+ meshes.append(
+ _PayloadMesh(name=name, buffers=buffers, extra_attributes=tuple(sorted(extras)))
+ )
+ return meshes
+
+
+def _duplicates(names: list[str]) -> list[tuple[str, int]]:
+ counts: dict[str, int] = {}
+ for name in names:
+ counts[name] = counts.get(name, 0) + 1
+ return sorted((name, count) for name, count in counts.items() if count > 1)
+
+
+def load_payload(path: Path) -> dict[str, Any]:
+ payload = json.loads(path.expanduser().read_text(encoding="utf-8"))
+ if not isinstance(payload, dict):
+ raise ValueError("payload root must be an object")
+ return payload
+
+
+# ---------------------------------------------------------------------------------------------
+# Manifest
+# ---------------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class MeshFingerprint:
+ """What was frozen for one mesh: the counts, the hashes, and the buffers themselves."""
+
+ name: str
+ vertex_count: int
+ index_count: int
+ attributes_present: tuple[str, ...]
+ attribute_hashes: dict[str, str]
+ buffers: dict[str, list[float] | list[int]]
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "name": self.name,
+ "vertexCount": self.vertex_count,
+ "indexCount": self.index_count,
+ "attributes": list(self.attributes_present),
+ "hashes": dict(self.attribute_hashes),
+ "buffers": {name: list(values) for name, values in self.buffers.items()},
+ }
+
+ @staticmethod
+ def from_dict(entry: dict[str, Any]) -> "MeshFingerprint":
+ try:
+ name = entry["name"]
+ hashes = dict(entry["hashes"])
+ attributes = tuple(entry["attributes"])
+ raw_buffers = entry["buffers"]
+ except KeyError as exc:
+ raise ValueError(f"manifest mesh is missing {exc.args[0]!r}") from exc
+ if set(attributes) != set(hashes) or set(attributes) != set(raw_buffers):
+ raise ValueError(
+ f"manifest mesh {name!r} disagrees with itself: attributes {sorted(attributes)}, "
+ f"hashes {sorted(hashes)}, buffers {sorted(raw_buffers)}"
+ )
+ buffers: dict[str, list[float] | list[int]] = {}
+ for key, values in raw_buffers.items():
+ label = f"manifest mesh {name!r} buffer {key!r}"
+ buffers[key] = (
+ _as_ints(values, label) if key == INDEX_KEY else _as_floats(values, label)
+ )
+ return MeshFingerprint(
+ name=name,
+ vertex_count=int(entry["vertexCount"]),
+ index_count=int(entry["indexCount"]),
+ attributes_present=attributes,
+ attribute_hashes=hashes,
+ buffers=buffers,
+ )
+
+
+@dataclass(frozen=True)
+class Manifest:
+ """The frozen record. Everything downstream of a freeze is checked against this and only this."""
+
+ schema_version: int
+ frozen_attributes: tuple[str, ...]
+ meshes: tuple[MeshFingerprint, ...]
+
+ def mesh(self, name: str) -> MeshFingerprint | None:
+ for fingerprint in self.meshes:
+ if fingerprint.name == name:
+ return fingerprint
+ return None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "schemaVersion": self.schema_version,
+ "kind": "mesh-freeze-manifest",
+ "frozenAttributes": list(self.frozen_attributes),
+ "meshes": [fingerprint.to_dict() for fingerprint in self.meshes],
+ "note": FREEZE_NOTE,
+ }
+
+ def to_summary_dict(self) -> dict[str, Any]:
+ """The manifest without the retained buffers -- what a human reads, not what verify eats."""
+ return {
+ "schemaVersion": self.schema_version,
+ "kind": "mesh-freeze-summary",
+ "frozenAttributes": list(self.frozen_attributes),
+ "meshes": [
+ {
+ "name": fingerprint.name,
+ "vertexCount": fingerprint.vertex_count,
+ "indexCount": fingerprint.index_count,
+ "attributes": list(fingerprint.attributes_present),
+ "hashes": dict(fingerprint.attribute_hashes),
+ }
+ for fingerprint in self.meshes
+ ],
+ "note": FREEZE_NOTE,
+ }
+
+ @staticmethod
+ def from_dict(payload: dict[str, Any]) -> "Manifest":
+ if not isinstance(payload, dict):
+ raise ValueError("manifest root must be an object")
+ meshes = payload.get("meshes")
+ if not isinstance(meshes, list):
+ raise ValueError("manifest must carry a `meshes` array")
+ return Manifest(
+ schema_version=int(payload.get("schemaVersion", -1)),
+ frozen_attributes=tuple(payload.get("frozenAttributes", ())),
+ meshes=tuple(MeshFingerprint.from_dict(entry) for entry in meshes),
+ )
+
+
+def freeze(payload: dict[str, Any]) -> Manifest:
+ """Record every frozen buffer of every mesh. The payload is read, never modified.
+
+ Duplicate mesh names are refused here rather than recorded, because a manifest is keyed by name:
+ two meshes called "arm" could not be told apart afterwards, and a gate that cannot tell two
+ things apart will eventually pass the wrong one. `verify` reports duplicates instead of raising
+ -- it is a gate, and a gate that crashes on bad input reports nothing at all.
+ """
+ meshes = _read_meshes(payload)
+ duplicates = _duplicates([mesh.name for mesh in meshes])
+ if duplicates:
+ listed = ", ".join(f"{name!r} x{count}" for name, count in duplicates)
+ raise ValueError(
+ f"cannot freeze: duplicate mesh names ({listed}). A manifest is keyed by name, so these "
+ "meshes could not be told apart at verify time."
+ )
+
+ fingerprints: list[MeshFingerprint] = []
+ for mesh in meshes:
+ buffers = {name: mesh.buffers[name] for name in FROZEN_BUFFERS if name in mesh.buffers}
+ position = buffers.get("position")
+ if position is None:
+ raise ValueError(
+ f"cannot freeze mesh {mesh.name!r}: it has no `position` attribute, so there is no "
+ "geometry to freeze"
+ )
+ if len(position) % 3 != 0:
+ raise ValueError(
+ f"cannot freeze mesh {mesh.name!r}: position holds {len(position)} floats, which is "
+ "not a whole number of xyz vertices"
+ )
+ fingerprints.append(
+ MeshFingerprint(
+ name=mesh.name,
+ vertex_count=len(position) // 3,
+ index_count=len(buffers.get(INDEX_KEY, ())),
+ attributes_present=tuple(sorted(buffers, key=lambda key: _ORDER[key])),
+ attribute_hashes={
+ name: _hash_buffer(name, values) for name, values in buffers.items()
+ },
+ buffers={name: list(values) for name, values in buffers.items()},
+ )
+ )
+
+ return Manifest(
+ schema_version=SCHEMA_VERSION,
+ frozen_attributes=FROZEN_BUFFERS,
+ meshes=tuple(fingerprints),
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# Parity report
+# ---------------------------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class ElementDifference:
+ """One element that moved: where it is, what it was, what it became."""
+
+ index: int
+ frozen: float | int
+ current: float | int
+
+ def to_dict(self) -> dict[str, Any]:
+ return {"index": self.index, "frozen": self.frozen, "current": self.current}
+
+
+@dataclass(frozen=True)
+class ParityFailure:
+ """A single violation, named down to the mesh, the buffer and the kind of change."""
+
+ mesh: str
+ attribute: str | None
+ kind: str
+ detail: str
+ differing_elements: int = 0
+ differences: tuple[ElementDifference, ...] = ()
+
+ def __str__(self) -> str:
+ where = f"{self.mesh}.{self.attribute}" if self.attribute else self.mesh
+ return f"{where}: {self.kind} -- {self.detail}"
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "mesh": self.mesh,
+ "attribute": self.attribute,
+ "kind": self.kind,
+ "detail": self.detail,
+ "differingElements": self.differing_elements,
+ "differences": [difference.to_dict() for difference in self.differences],
+ }
+
+
+@dataclass(frozen=True)
+class ParityReport:
+ """The gate's answer. `status` is one of pass / fail / unevaluated; only pass is `ok`."""
+
+ status: str
+ meshes_frozen: int
+ meshes_compared: int
+ failure_count: int
+ failures: tuple[ParityFailure, ...]
+ addition_count: int
+ additions: tuple[str, ...]
+ reason: str | None = None
+
+ @property
+ def ok(self) -> bool:
+ # `unevaluated` is deliberately not ok. A gate whose input never arrived has not passed; it
+ # has not run.
+ return self.status == STATUS_PASS
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "schemaVersion": SCHEMA_VERSION,
+ "kind": "mesh-parity-report",
+ "status": self.status,
+ "ok": self.ok,
+ "reason": self.reason,
+ "frozenAttributes": list(FROZEN_BUFFERS),
+ "meshesFrozen": self.meshes_frozen,
+ "meshesCompared": self.meshes_compared,
+ "failureCount": self.failure_count,
+ "failures": [failure.to_dict() for failure in self.failures],
+ "addedLegalCount": self.addition_count,
+ "addedLegal": list(self.additions),
+ "summary": self.summary(),
+ }
+
+ def summary(self) -> str:
+ headers = ("KIND", "MESH", "ATTRIBUTE")
+ lines = [
+ f"mesh parity: {self.status.upper()} (schema {SCHEMA_VERSION}, frozen: "
+ + ", ".join(FROZEN_BUFFERS)
+ + ")",
+ f" meshes frozen {self.meshes_frozen} compared {self.meshes_compared} "
+ f"failures {self.failure_count} added (legal) {self.addition_count}",
+ ]
+ if self.reason:
+ lines.append(f" reason: {self.reason}")
+
+ if self.failures:
+ rows = [
+ (failure.kind, failure.mesh, failure.attribute or "-", failure.detail)
+ for failure in self.failures
+ ]
+ widths = [
+ max(len(header), max(len(row[column]) for row in rows))
+ for column, header in enumerate(headers)
+ ]
+ lines.append(
+ " "
+ + " ".join(header.ljust(widths[column]) for column, header in enumerate(headers))
+ + " DETAIL"
+ )
+ for row in rows:
+ lines.append(
+ " "
+ + " ".join(row[column].ljust(widths[column]) for column in range(3))
+ + " "
+ + row[3]
+ )
+ if self.failure_count > len(self.failures):
+ lines.append(
+ f" ... {self.failure_count - len(self.failures)} further failures not listed"
+ )
+
+ if self.additions:
+ lines.append(" added (legal): " + ", ".join(self.additions))
+ if self.addition_count > len(self.additions):
+ lines.append(
+ f" ... {self.addition_count - len(self.additions)} further additions not listed"
+ )
+ return "\n".join(lines)
+
+
+def _first_differences(
+ name: str, frozen: list[float] | list[int], current: list[float] | int | list[int]
+) -> tuple[int, tuple[ElementDifference, ...]]:
+ """Locate the differing elements of two equal-length buffers, after a hash already said so.
+
+ Compared as PACKED BYTES, not with `==`, so the scan agrees with the hash by construction: the
+ same -0.0 / 0.0 pair that the hash calls a difference is a difference here, and the same NaN bit
+ pattern that the hash calls equal is equal here. A float comparison would disagree with the hash
+ on both, and a gate whose diagnosis contradicts its own verdict is worse than no diagnosis.
+ """
+ left = _packed(name, frozen)
+ right = _packed(name, current) # type: ignore[arg-type]
+ differing = 0
+ found: list[ElementDifference] = []
+ for position in range(len(frozen)):
+ start = position * ELEMENT_BYTES
+ if left[start : start + ELEMENT_BYTES] != right[start : start + ELEMENT_BYTES]:
+ differing += 1
+ if len(found) < _MAX_REPORTED_DIFFS:
+ found.append(
+ ElementDifference(
+ index=position,
+ frozen=frozen[position],
+ current=current[position], # type: ignore[index]
+ )
+ )
+ return differing, tuple(found)
+
+
+def _compare_mesh(
+ fingerprint: MeshFingerprint, mesh: _PayloadMesh
+) -> tuple[list[ParityFailure], list[str]]:
+ failures: list[ParityFailure] = []
+ additions: list[str] = []
+
+ frozen_names = set(fingerprint.attribute_hashes)
+ present = set(mesh.buffers)
+
+ for name in sorted(frozen_names - present, key=lambda key: _ORDER[key]):
+ failures.append(
+ ParityFailure(
+ mesh=mesh.name,
+ attribute=name,
+ kind=KIND_ATTRIBUTE_MISSING,
+ detail=f"{name} was frozen with {len(fingerprint.buffers[name])} values and is "
+ "absent from the payload",
+ )
+ )
+ for name in sorted(present - frozen_names, key=lambda key: _ORDER[key]):
+ failures.append(
+ ParityFailure(
+ mesh=mesh.name,
+ attribute=name,
+ kind=KIND_ATTRIBUTE_ADDED,
+ detail=f"{name} is a frozen-class buffer that did not exist at freeze time; adding "
+ "one changes the surface just as moving it does",
+ )
+ )
+ for name in mesh.extra_attributes:
+ additions.append(f"{mesh.name}.{name}")
+
+ common = frozen_names & present
+
+ # Counts are checked against the manifest's RECORDED counts, not against the length of its
+ # retained buffers -- so a manifest whose hashes were recomputed to match a shrunken mesh still
+ # fails here, on the count it forgot to update.
+ counted: set[str] = set()
+ if "position" in common:
+ position = mesh.buffers["position"]
+ if len(position) % 3 != 0:
+ failures.append(
+ ParityFailure(
+ mesh=mesh.name,
+ attribute="position",
+ kind=KIND_MALFORMED,
+ detail=f"position holds {len(position)} floats, which is not a whole number of "
+ "xyz vertices",
+ )
+ )
+ counted.add("position")
+ elif len(position) // 3 != fingerprint.vertex_count:
+ failures.append(
+ ParityFailure(
+ mesh=mesh.name,
+ attribute=None,
+ kind=KIND_COUNT,
+ detail=f"vertexCount {fingerprint.vertex_count} -> {len(position) // 3}",
+ )
+ )
+ counted.add("position")
+ if INDEX_KEY in common and len(mesh.buffers[INDEX_KEY]) != fingerprint.index_count:
+ failures.append(
+ ParityFailure(
+ mesh=mesh.name,
+ attribute=INDEX_KEY,
+ kind=KIND_COUNT,
+ detail=f"indexCount {fingerprint.index_count} -> {len(mesh.buffers[INDEX_KEY])}",
+ )
+ )
+ counted.add(INDEX_KEY)
+
+ for name in sorted(common, key=lambda key: _ORDER[key]):
+ frozen_values = fingerprint.buffers[name]
+ current_values = mesh.buffers[name]
+ if len(frozen_values) != len(current_values):
+ # A length change is a count change, and the hash mismatch it also causes says nothing
+ # extra. Reporting both would double every truncation.
+ if name not in counted:
+ failures.append(
+ ParityFailure(
+ mesh=mesh.name,
+ attribute=name,
+ kind=KIND_COUNT,
+ detail=f"{name} holds {len(current_values)} values, frozen with "
+ f"{len(frozen_values)}",
+ )
+ )
+ continue
+ if _hash_buffer(name, current_values) == fingerprint.attribute_hashes[name]:
+ continue
+ differing, differences = _first_differences(name, frozen_values, current_values)
+ if differing == 0:
+ detail = (
+ "the payload buffer matches the manifest's own retained buffer byte for byte but "
+ "not its recorded hash: the manifest has been edited and cannot be trusted"
+ )
+ else:
+ first = differences[0]
+ detail = (
+ f"first difference at element {first.index}: {first.frozen!r} -> "
+ f"{first.current!r} ({differing} of {len(frozen_values)} elements differ)"
+ )
+ failures.append(
+ ParityFailure(
+ mesh=mesh.name,
+ attribute=name,
+ kind=KIND_HASH,
+ detail=detail,
+ differing_elements=differing,
+ differences=differences,
+ )
+ )
+
+ return failures, additions
+
+
+def verify(manifest: Manifest | None, payload: dict[str, Any]) -> ParityReport:
+ """Re-hash the payload against the freeze manifest. Meshes are matched BY NAME, never by order.
+
+ Order matching would be a silent trap: an implementation that reorders a scene graph -- which is
+ legal and common -- would be compared limb against torso and would fail for the wrong reason,
+ while an implementation that swapped two meshes' geometry would pass. Names are the only stable
+ identity, which is also why duplicate names are a structural failure rather than something to
+ zip through.
+ """
+ if manifest is None:
+ return ParityReport(
+ status=STATUS_UNEVALUATED,
+ meshes_frozen=0,
+ meshes_compared=0,
+ failure_count=0,
+ failures=(),
+ addition_count=0,
+ additions=(),
+ reason=_NO_MANIFEST_REASON,
+ )
+ if manifest.schema_version != SCHEMA_VERSION:
+ return ParityReport(
+ status=STATUS_UNEVALUATED,
+ meshes_frozen=len(manifest.meshes),
+ meshes_compared=0,
+ failure_count=0,
+ failures=(),
+ addition_count=0,
+ additions=(),
+ reason=f"manifest schemaVersion {manifest.schema_version} is not {SCHEMA_VERSION}; this "
+ "module cannot say what its hashes cover",
+ )
+ if tuple(manifest.frozen_attributes) != FROZEN_BUFFERS:
+ return ParityReport(
+ status=STATUS_UNEVALUATED,
+ meshes_frozen=len(manifest.meshes),
+ meshes_compared=0,
+ failure_count=0,
+ failures=(),
+ addition_count=0,
+ additions=(),
+ reason="manifest was frozen over "
+ f"{list(manifest.frozen_attributes)}, this module freezes {list(FROZEN_BUFFERS)}; a "
+ "comparison would prove something other than what it claims",
+ )
+ if not manifest.meshes:
+ return ParityReport(
+ status=STATUS_UNEVALUATED,
+ meshes_frozen=0,
+ meshes_compared=0,
+ failure_count=0,
+ failures=(),
+ addition_count=0,
+ additions=(),
+ reason=_EMPTY_MANIFEST_REASON,
+ )
+
+ current = _read_meshes(payload)
+ failures: list[ParityFailure] = []
+ additions: list[str] = []
+
+ manifest_duplicates = _duplicates([fingerprint.name for fingerprint in manifest.meshes])
+ payload_duplicates = _duplicates([mesh.name for mesh in current])
+ for name, count in manifest_duplicates:
+ failures.append(
+ ParityFailure(
+ mesh=name,
+ attribute=None,
+ kind=KIND_DUPLICATE,
+ detail=f"the freeze manifest records {count} meshes named {name!r}; meshes are "
+ "matched by name and these cannot be told apart",
+ )
+ )
+ for name, count in payload_duplicates:
+ failures.append(
+ ParityFailure(
+ mesh=name,
+ attribute=None,
+ kind=KIND_DUPLICATE,
+ detail=f"the payload carries {count} meshes named {name!r}; meshes are matched by "
+ "name and these cannot be told apart",
+ )
+ )
+ ambiguous = {name for name, _ in manifest_duplicates} | {name for name, _ in payload_duplicates}
+
+ by_name = {mesh.name: mesh for mesh in current if mesh.name not in ambiguous}
+ frozen_names = {fingerprint.name for fingerprint in manifest.meshes}
+ compared = 0
+
+ for fingerprint in manifest.meshes:
+ if fingerprint.name in ambiguous:
+ continue
+ mesh = by_name.get(fingerprint.name)
+ if mesh is None:
+ failures.append(
+ ParityFailure(
+ mesh=fingerprint.name,
+ attribute=None,
+ kind=KIND_MESH_MISSING,
+ detail=f"frozen with {fingerprint.vertex_count} vertices and absent from the "
+ "payload; implementation may not remove visible geometry",
+ )
+ )
+ continue
+ mesh_failures, mesh_additions = _compare_mesh(fingerprint, mesh)
+ failures.extend(mesh_failures)
+ additions.extend(mesh_additions)
+ compared += 1
+
+ for mesh in current:
+ if mesh.name in ambiguous or mesh.name in frozen_names:
+ continue
+ vertices = len(mesh.buffers.get("position", ())) // 3
+ failures.append(
+ ParityFailure(
+ mesh=mesh.name,
+ attribute=None,
+ kind=KIND_MESH_ADDED,
+ detail=f"present in the payload with {vertices} vertices and not in the manifest; "
+ "implementation may not create new visible geometry either",
+ )
+ )
+
+ return ParityReport(
+ status=STATUS_FAIL if failures else STATUS_PASS,
+ meshes_frozen=len(manifest.meshes),
+ meshes_compared=compared,
+ failure_count=len(failures),
+ failures=tuple(failures[:_MAX_REPORTED_FAILURES]),
+ addition_count=len(additions),
+ additions=tuple(additions[:_MAX_REPORTED_ADDITIONS]),
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# CLI
+# ---------------------------------------------------------------------------------------------
+
+
+def _run_freeze(args: argparse.Namespace) -> int:
+ manifest = freeze(load_payload(args.payload))
+ document = json.dumps(manifest.to_dict(), indent=2, ensure_ascii=False) + "\n"
+ if args.out:
+ args.out.expanduser().parent.mkdir(parents=True, exist_ok=True)
+ args.out.expanduser().write_text(document, encoding="utf-8")
+ # stdout gets the manifest WITHOUT its retained buffers. The buffers are a copy of the whole
+ # mesh; printing them would bury the hashes a human came to read.
+ print(json.dumps(manifest.to_summary_dict(), indent=2, ensure_ascii=False))
+ else:
+ print(document, end="")
+ return 0
+
+
+def _run_verify(args: argparse.Namespace) -> int:
+ manifest = Manifest.from_dict(
+ json.loads(args.manifest.expanduser().read_text(encoding="utf-8"))
+ )
+ report = verify(manifest, load_payload(args.payload))
+ print(json.dumps(report.to_dict(), indent=2, ensure_ascii=False))
+ return 0 if report.ok else 1
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(
+ description="Freeze mesh geometry before rigging and prove afterwards that it never moved."
+ )
+ subcommands = parser.add_subparsers(dest="command", required=True)
+
+ freezer = subcommands.add_parser("freeze", help="record the frozen buffers and their hashes")
+ freezer.add_argument("payload", type=Path, help="JSON mesh payload")
+ freezer.add_argument("--out", type=Path, help="write the full manifest here")
+ freezer.set_defaults(handler=_run_freeze)
+
+ verifier = subcommands.add_parser("verify", help="re-hash a payload against a freeze manifest")
+ verifier.add_argument("manifest", type=Path, help="manifest written by `freeze --out`")
+ verifier.add_argument("payload", type=Path, help="JSON mesh payload to check")
+ verifier.set_defaults(handler=_run_verify)
+
+ args = parser.parse_args(argv)
+ try:
+ return args.handler(args)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage5_rig/rig_gates.py b/forge/stage5_rig/rig_gates.py
new file mode 100644
index 0000000..1149e13
--- /dev/null
+++ b/forge/stage5_rig/rig_gates.py
@@ -0,0 +1,1941 @@
+#!/usr/bin/env python3
+"""Stage R6 — the G1..G10 gate runner (1.5.2 §"Stage R6 — Gates").
+
+WHY THIS MODULE EXISTS. The 1.5.1 rigging failures were not "slightly wrong"; they were total and
+silent. Eleven clips held actions, the mixer held state, buttons dispatched, and nothing moved. Two
+separate bugs each produced a plausible-looking scene with zero motion, and neither was visible in
+code review. Every gate below is one of those failures, written down as a number. The R6 table's
+"Catches" column is carried on every result for exactly that reason: a failing report has to explain
+itself without the reader opening the spec.
+
+THE HONESTY RULE IS THE POINT OF THIS MODULE. A gate whose input is absent reports
+`status: "unevaluated"` with a human-readable reason. It is NEVER silently a pass, and
+`GateReport.ok` is True only when every one of the ten reports `pass`. An unevaluated gate makes the
+whole report not-ok, because "we did not check" and "we checked and it was fine" are different
+claims and only one of them ships.
+
+UNDER-COVERAGE IS A FAILURE, NOT A PASS. G1, G2, G3, G6 and G10 consume measurements a browser/host
+harness produces — Python cannot evaluate a three.js interpolant or count background pixels. So this
+module is the arbiter, not the measurer, and its job is as much to audit the harness's coverage as
+its numbers. A harness that reports `maxSampledBindingDelta = 1e-12` over one clip at one time has
+not proved anything: the clip that plays silently is precisely the clip nobody sampled. G1 therefore
+fails a tiny delta with thin coverage, and G2 and G10 do the same for their own axes.
+
+DELEGATION. This module owns no measurement it can borrow:
+ G4/G5 -> `skin_conditioning.validate_binding` (Gate R2 lives there)
+ G7 -> `action_design.check_medial_lateral`
+ G8 -> `action_design.foot_slide` / `action_design.FOOT_SLIDE_LIMIT`
+ G9 -> `clip_features.measure_clip(...).scale_delta`
+Re-implementing any of them here would let the gate and the stage drift apart, which is how a gate
+stops being evidence.
+
+---------------------------------------------------------------------------------------------
+SPEC AMBIGUITIES AND THE READING CHOSEN
+---------------------------------------------------------------------------------------------
+1. "over >= 5 times x all clips" (G1). The spec states the delta bound but never says which side
+ under-coverage falls on. READING: coverage is part of the criterion, not a side note — a clip
+ missing from the harness's roster and a clip sampled 3 times both FAIL G1, with a reason naming
+ the clips. The roster is taken from the sampled-clip payload's `clips` when present (that is the
+ authoritative clip set); when there is no sampled-clip payload the payload must carry a top-level
+ `clipNames`. The roster is never taken from the harness's own report, which would make
+ "covered every clip" true by construction; a payload carrying neither leaves G1 `unevaluated`.
+
+2. ">= 64 vertices/mesh/frame" (G2). Same reading as G1: a mesh sampled at 8 vertices FAILS. The
+ per-mesh entry may give `verticesPerFrame` as one number (interpreted as the MINIMUM across that
+ mesh's frames, the only reading under which a single number can support a per-frame claim) or as
+ a list of per-frame counts, which is checked entry by entry.
+
+3. "materially thinner than its declared clip set allows" (G10). The spec fixes one sweep shape —
+ 11 clips x 4 times x 2 sides x 2 azimuths = 176 frames — without saying what a *different* clip
+ set requires. READING: the per-axis minima (4 times, 2 sides, 2 azimuths) are the constants and
+ the clip axis scales with the payload, so the required frame count is
+ `clips x 4 x 2 x 2`. The declared `frames` must also equal the product of the declared axes: a
+ sweep claiming 176 frames from axes that multiply to 20 is a bookkeeping error, and the spec's
+ whole point is that the declared number is not taken on trust.
+
+4. "background-through-split <= measured baseline" (G10). "Baseline" is the control run with the
+ blend disabled (§R2's `blend off` row), so it must be a measured number carried in the payload.
+ READING: an absent baseline leaves G10 `unevaluated` rather than defaulting to the Lee Sin
+ numbers — a threshold borrowed from another subject is not a measurement of this one. Holes and
+ creases are always reported as TWO numbers; §R2 trades one against the other and a single
+ combined score hides that trade. Creases are reported and NEVER gated: R2 accepts a ~16% crease
+ increase deliberately, so failing on crease count would ask a later stage to undo R2.
+
+5. "unless the source has it" (G9). READING: the exemption must be DECLARED, by
+ `sourceScalesJoints: true` on the payload, and it produces a pass carrying a warning that names
+ every clip with a non-zero scaleDelta. It never produces a silent pass, because the reason the
+ tripwire exists is that joint scale changes what Stage R2 may legally do to skin weights and
+ somebody downstream has to be told.
+
+6. G6's `visibleMeshCount == visibleSkinnedMeshCount`. Equality is the criterion as written, so a
+ payload reporting MORE skinned meshes than visible meshes also fails — the two numbers disagree
+ and one of them is wrong, which is a finding either way.
+
+7. `GateResult.measured` is deliberately typed loose (a number, a dict, or None). Several gates are
+ irreducibly multi-valued — G10 reports holes and creases, G1 reports a delta and a coverage
+ table — and flattening them to one number is the exact mistake the spec calls out for G10.
+
+8. G7 and the tautological pass. `action_design.Chains.gate_is_independent` records something the
+ R6 table does not: when left/right were assigned by "left = +X" rather than claimed from outside
+ the geometry, the gate compares the geometry against itself and the mirrored-rig case is
+ unreachable. READING: an errorless run of a non-independent gate reports `unevaluated`, not
+ `pass`. A pass that could not have failed is the silent pass this module exists to prevent. A
+ non-empty error list is still a `fail` -- a degenerate pair is a real finding either way.
+
+9. G8 and clips with no stance. `stance` is optional in the payload and nothing here can tell a
+ gait clip from a gesture clip without re-classifying. READING: a clip carrying no stance is
+ recorded and WARNED about, not failed -- failing every non-gait clip would make the gate
+ unusable -- but a payload where NO clip carries measurable stance leaves G8 `unevaluated`,
+ because a gate with no stance data is an unasked question, not a clean answer.
+
+10. G11 and a manifest/payload disagreement about which meshes exist. `mesh_parity.verify`
+ already decides this — a frozen mesh absent from the payload is `mesh missing`, a payload mesh
+ absent from the manifest is `mesh added`, and both are FAILURES ("implementation may not remove
+ visible geometry" / "...may not create new visible geometry either"). READING: this module
+ DEFERS to that decision rather than re-deciding it. G11 is a thin arbiter over
+ `mesh_parity.verify` and adds no parity rule of its own; re-deriving one here is how a gate and
+ the stage it gates start disagreeing about what "byte-identical" meant.
+
+11. G11 and legally-added attributes. `skinIndex` and `skinWeight` are deliberately outside
+ FROZEN_BUFFERS — adding them is the entire legal purpose of rigging. READING: the additions
+ `mesh_parity` reports are carried into `measured.addedLegal` for the reader and NEVER
+ contribute to the verdict. A gate that failed every successful rig would simply be switched
+ off, which is worse than not having it.
+
+12. G12 and the GLB report's `ok` field. `GlbRig.to_dict()` does not emit `ok`; the field is added
+ by `glb_rig_reference`'s CLI (`result["ok"] = not errors`), so an in-process caller's report
+ legitimately lacks it. READING: an explicit `ok: false` is honoured as a failure, and an absent
+ `ok` is DERIVED as `structuralFailure is None and not errors` rather than treated as missing
+ input. Requiring a field the library itself does not produce would leave G12 permanently
+ unevaluated for every caller that does not shell out.
+
+13. G12 and unsupported interpolation. The R6 brief groups "no skin, multiple skins without a
+ choice, unsupported interpolation" under `structuralFailure`, but `glb_rig_reference` sets
+ `structural_failure` only for the two skin cases and surfaces unsupported interpolation
+ separately as `unsupportedInterpolationClips`. READING: both are FAILURES and the reason names
+ which one fired, because a clip whose interpolation cannot be evaluated addresses the skeleton
+ no more usefully than one addressing the wrong skeleton. Neither is ever `unevaluated`: a
+ structural failure is a known-bad answer, not a missing one.
+
+14. G12 with a procedural source and no correspondence. READING: FAIL, not unevaluated. A payload
+ declaring a procedural skeleton and supplying no mapping to the GLB's joints is not a gate
+ with absent input — it is the exact defect G12 exists to catch, stated in the payload.
+
+Pure Python 3.10+ stdlib. No pip installs, no numpy, no three.js.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Mapping, Sequence
+
+# The three sibling modules below are imported flat, the way they import each other. This file
+# is the first with HARD sibling dependencies (the others import defensively or not at all), so
+# it puts its own directory on the path rather than relying on every caller to bootstrap it.
+_HERE = str(Path(__file__).resolve().parent)
+if _HERE not in sys.path:
+ sys.path.insert(0, _HERE)
+
+from action_design import ( # noqa: E402
+ FOOT_SLIDE_LIMIT,
+ MEDIAL_AXIS_TOLERANCE,
+ ChainResolutionError,
+ Chains,
+ check_medial_lateral,
+ foot_slide,
+ resolve_chains,
+)
+from clip_features import measure_clip # noqa: E402
+
+# These two are imported as NAMESPACES rather than flat. Both define their own STATUS_PASS /
+# STATUS_FAIL / STATUS_UNEVALUATED with the same string values as this module's, and
+# mesh_parity also exports a `load_payload`; importing them flat would shadow ours with
+# constants that happen to agree today and might not tomorrow.
+import glb_rig_reference # noqa: E402
+import mesh_parity # noqa: E402
+from skin_conditioning import SkinBinding, WEIGHT_SUM_TOLERANCE, validate_binding # noqa: E402
+
+# ---------------------------------------------------------------------------------------------
+# Tolerances. The names are the spec's and the values come from CONTRACT_1.5.2.md; the two that
+# skin_conditioning and action_design own are IMPORTED, never restated, so a change there cannot
+# leave this file quietly disagreeing with the stage it gates.
+# ---------------------------------------------------------------------------------------------
+BINDING_EPSILON = 2**-23 # float32 epsilon: G1
+BIND_RESTORE_TOLERANCE = 1e-12 # G3
+MINIMUM_GATE_R1_SAMPLES = 5 # G1 coverage: ">= 5 times", per clip
+MINIMUM_G2_VERTICES = 64 # G2 coverage: ">= 64 vertices/mesh/frame"
+
+# G10 sweep coverage. `single-subject`: the sweep that found the real defects was 11 clips x 4 times
+# x 2 sides x 2 azimuths = 176 frames, and the clip axis is the only one that follows the payload.
+# Callers may override; the report records the values actually used.
+MINIMUM_SWEEP_TIMES = 4
+MINIMUM_SWEEP_SIDES = 2
+MINIMUM_SWEEP_AZIMUTHS = 2
+
+STATUS_PASS = "pass"
+STATUS_FAIL = "fail"
+STATUS_UNEVALUATED = "unevaluated"
+
+
+@dataclass(frozen=True)
+class SweepCoverage:
+ """The G10 axis minima, as data a caller can replace (see ambiguity 3)."""
+
+ times: int = MINIMUM_SWEEP_TIMES
+ sides: int = MINIMUM_SWEEP_SIDES
+ azimuths: int = MINIMUM_SWEEP_AZIMUTHS
+ provenance: str = "single-subject (11 clips x 4 times x 2 sides x 2 azimuths = 176 frames)"
+
+ def required_frames(self, clip_count: int) -> int:
+ return max(0, int(clip_count)) * self.times * self.sides * self.azimuths
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "times": self.times,
+ "sides": self.sides,
+ "azimuths": self.azimuths,
+ "provenance": self.provenance,
+ }
+
+
+DEFAULT_SWEEP_COVERAGE = SweepCoverage()
+
+
+@dataclass(frozen=True)
+class GateSpec:
+ """One row of the R6 table, verbatim. `catches` is not decoration — it is the failure the gate
+ exists to catch, and it rides on every result so a failing report explains itself."""
+
+ id: str
+ name: str
+ criterion: str
+ catches: str
+ input_key: str
+
+
+GATE_SPECS: tuple[GateSpec, ...] = (
+ GateSpec(
+ "G1",
+ "binding reaches node",
+ "maxSampledBindingDelta <= 2^-23 over >= 5 times x all clips",
+ "clips that play silently",
+ "bindingSamples",
+ ),
+ GateSpec(
+ "G2",
+ "deformation finite",
+ "applyBoneTransform on >= 64 vertices/mesh/frame, all finite",
+ "bad indices, NaN weights",
+ "deformation",
+ ),
+ GateSpec(
+ "G3",
+ "bind restore",
+ "maxBindRestoreDelta <= 1e-12 after stop()",
+ "pose bleed between clips",
+ "bindRestore",
+ ),
+ GateSpec(
+ "G4",
+ "weights normalised",
+ "|1 - sum(w)| <= 2e-7 every vertex",
+ "shrinking/inflating limbs",
+ "binding",
+ ),
+ GateSpec(
+ "G5",
+ "indices in range",
+ "maxSkinIndex <= bones - 1",
+ "one vertex to infinity",
+ "binding",
+ ),
+ GateSpec(
+ "G6",
+ "every visible mesh bound",
+ "visibleMeshCount == visibleSkinnedMeshCount",
+ "a part left behind in bind pose",
+ "meshVisibility",
+ ),
+ GateSpec(
+ "G7",
+ "medial/lateral",
+ "leftAnchor.x > 0 > rightAnchor.x",
+ "mirrored rig",
+ "chainAnchors",
+ ),
+ GateSpec(
+ "G8",
+ "foot contact",
+ "footSlide <= 0.01H in stance",
+ "skating gaits",
+ "clips[].stance",
+ ),
+ GateSpec(
+ "G9",
+ "no joint scale",
+ "scaleDelta == 0 unless the source has it",
+ "weight-blend invalidation",
+ "clips",
+ ),
+ GateSpec(
+ "G10",
+ "skin integrity sweep",
+ "background-through-split <= measured baseline",
+ "tearing under motion",
+ "skinIntegritySweep",
+ ),
+ GateSpec(
+ "G11",
+ "mesh parity",
+ "every frozen buffer byte-identical after binding",
+ "rigging that rewrites mesh geometry",
+ "meshParity",
+ ),
+ GateSpec(
+ "G12",
+ "rig reference",
+ "animation refers to the GLB's own skeleton, or an explicitly usable correspondence",
+ "clip channels and skinIndex values addressing a different skeleton",
+ "rigReference",
+ ),
+)
+
+GATE_SPEC_BY_ID: dict[str, GateSpec] = {spec.id: spec for spec in GATE_SPECS}
+
+
+@dataclass(frozen=True)
+class GateResult:
+ """One gate's verdict.
+
+ `measured` is loose on purpose (ambiguity 7): several gates are irreducibly multi-valued and
+ flattening them to one number is the exact mistake the spec calls out for G10.
+
+ `warnings` carries a pass that a reader still has to be told about — G9's declared source joint
+ scaling is the case the spec names. A warning never changes `status`, and a warning is never a
+ substitute for a failure.
+ """
+
+ id: str
+ name: str
+ status: str
+ criterion: str
+ catches: str
+ threshold: Any
+ measured: Any = None
+ reason: str = ""
+ details: dict[str, Any] = field(default_factory=dict)
+ warnings: tuple[str, ...] = ()
+
+ @property
+ def passed(self) -> bool:
+ return self.status == STATUS_PASS
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "name": self.name,
+ "status": self.status,
+ "criterion": self.criterion,
+ "catches": self.catches,
+ "threshold": self.threshold,
+ "measured": self.measured,
+ "reason": self.reason,
+ "details": dict(self.details),
+ "warnings": list(self.warnings),
+ }
+
+
+@dataclass(frozen=True)
+class GateReport:
+ """All ten verdicts. `ok` is True only when every gate is `pass`."""
+
+ results: tuple[GateResult, ...]
+ figure_height: float | None = None
+ sweep_coverage: SweepCoverage = DEFAULT_SWEEP_COVERAGE
+
+ @property
+ def ok(self) -> bool:
+ return all(result.passed for result in self.results)
+
+ def by_id(self, gate_id: str) -> GateResult:
+ for result in self.results:
+ if result.id == gate_id:
+ return result
+ raise KeyError(f"no such gate: {gate_id!r}")
+
+ @property
+ def failed(self) -> tuple[GateResult, ...]:
+ return tuple(r for r in self.results if r.status == STATUS_FAIL)
+
+ @property
+ def unevaluated(self) -> tuple[GateResult, ...]:
+ return tuple(r for r in self.results if r.status == STATUS_UNEVALUATED)
+
+ def summary(self) -> dict[str, Any]:
+ """Table-shaped: one row per gate, in R6 order, plus the counts a reader reads first."""
+ rows = [
+ {
+ "id": r.id,
+ "gate": r.name,
+ "status": r.status,
+ "measured": r.measured,
+ "threshold": r.threshold,
+ "catches": r.catches,
+ "reason": r.reason,
+ "warnings": list(r.warnings),
+ }
+ for r in self.results
+ ]
+ return {
+ "ok": self.ok,
+ "figureHeight": self.figure_height,
+ "counts": {
+ "total": len(self.results),
+ "pass": sum(1 for r in self.results if r.status == STATUS_PASS),
+ "fail": len(self.failed),
+ "unevaluated": len(self.unevaluated),
+ },
+ "failed": [r.id for r in self.failed],
+ "unevaluated": [r.id for r in self.unevaluated],
+ "sweepCoverage": self.sweep_coverage.to_dict(),
+ "rows": rows,
+ "note": (
+ "ok is True only when every gate is `pass`. An unevaluated gate is not a pass: "
+ "\"we did not check\" and \"we checked and it was fine\" are different claims."
+ ),
+ }
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "schemaVersion": 1,
+ "kind": "rig-gates",
+ "ok": self.ok,
+ "figureHeight": self.figure_height,
+ "sweepCoverage": self.sweep_coverage.to_dict(),
+ "gates": [r.to_dict() for r in self.results],
+ "summary": self.summary(),
+ }
+
+
+# ---------------------------------------------------------------------------------------------
+# Small shared helpers
+# ---------------------------------------------------------------------------------------------
+
+
+def _finite(value: Any) -> bool:
+ return (
+ isinstance(value, (int, float))
+ and not isinstance(value, bool)
+ and math.isfinite(float(value))
+ )
+
+
+def _positive_int(value: Any) -> int | None:
+ if isinstance(value, bool) or not isinstance(value, int):
+ return None
+ return value if value >= 0 else None
+
+
+def _unevaluated(spec: GateSpec, reason: str, threshold: Any, **details: Any) -> GateResult:
+ """The honesty rule, in one place. Absent input is never a pass."""
+ return GateResult(
+ id=spec.id,
+ name=spec.name,
+ status=STATUS_UNEVALUATED,
+ criterion=spec.criterion,
+ catches=spec.catches,
+ threshold=threshold,
+ measured=None,
+ reason=reason,
+ details=details,
+ )
+
+
+def _verdict(
+ spec: GateSpec,
+ ok: bool,
+ threshold: Any,
+ measured: Any,
+ reason: str,
+ warnings: Sequence[str] = (),
+ **details: Any,
+) -> GateResult:
+ return GateResult(
+ id=spec.id,
+ name=spec.name,
+ status=STATUS_PASS if ok else STATUS_FAIL,
+ criterion=spec.criterion,
+ catches=spec.catches,
+ threshold=threshold,
+ measured=measured,
+ reason=reason,
+ details=details,
+ warnings=tuple(warnings),
+ )
+
+
+def _clip_roster(payload: Mapping[str, Any]) -> list[str] | None:
+ """The authoritative list of clip names the harness was supposed to cover, or None.
+
+ Taken from the sampled-clip payload's `clips` (CONTRACT_1.5.2.md) when present, else from a
+ top-level `clipNames`. It is NEVER taken from the harness's own report: a roster derived from
+ what the harness sampled makes "covered every clip" true by construction, which is precisely the
+ hole G1 exists to close.
+ """
+ clips = payload.get("clips")
+ if isinstance(clips, (list, tuple)) and clips:
+ names: list[str] = []
+ for index, clip in enumerate(clips):
+ if isinstance(clip, Mapping) and isinstance(clip.get("sourceName"), str):
+ names.append(clip["sourceName"])
+ else:
+ names.append(f"<clips[{index}] has no sourceName>")
+ return names
+ declared = payload.get("clipNames")
+ if isinstance(declared, (list, tuple)) and declared and all(isinstance(n, str) for n in declared):
+ return [str(n) for n in declared]
+ return None
+
+
+# ---------------------------------------------------------------------------------------------
+# G1 — binding reaches node
+# ---------------------------------------------------------------------------------------------
+
+
+def _normalise_sampled_clips(raw: Any) -> dict[str, dict[str, Any]] | None:
+ """Accept the three shapes a harness plausibly emits, or None if it is not one of them.
+
+ {"walk": 5} name -> sample count
+ {"walk": {"sampleCount": 5, "maxSampledBindingDelta": 1e-9}}
+ [{"sourceName": "walk", "sampleCount": 5, ...}]
+ """
+ entries: dict[str, dict[str, Any]] = {}
+ if isinstance(raw, Mapping):
+ for name, value in raw.items():
+ if not isinstance(name, str):
+ return None
+ if isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ entries[name] = {"sampleCount": value}
+ elif isinstance(value, Mapping):
+ entry = dict(value)
+ entry.setdefault("sampleCount", value.get("sampleCount"))
+ entries[name] = entry
+ else:
+ return None
+ return entries
+ if isinstance(raw, (list, tuple)):
+ for item in raw:
+ if not isinstance(item, Mapping) or not isinstance(item.get("sourceName"), str):
+ return None
+ entries[item["sourceName"]] = dict(item)
+ return entries
+ return None
+
+
+def gate_g1(payload: Mapping[str, Any]) -> GateResult:
+ """maxSampledBindingDelta <= 2^-23 over >= 5 times x all clips.
+
+ THIS IS THE GATE THAT CATCHES SILENT DEATH. A clip can exist, be loaded, hold an action and
+ report a duration while driving nothing; comparing the node's actual transform against
+ `track.createInterpolant().evaluate(t)` is the only check that tells the two apart.
+
+ Which means the delta on its own proves nothing. A harness that sampled one clip at one time and
+ reported 1e-12 has measured the one clip that was working. Coverage is therefore part of the
+ criterion (ambiguity 1), and a thin sweep FAILS.
+ """
+ spec = GATE_SPEC_BY_ID["G1"]
+ threshold = {
+ "maxSampledBindingDelta": BINDING_EPSILON,
+ "minimumSamplesPerClip": MINIMUM_GATE_R1_SAMPLES,
+ "clipCoverage": "every clip in the roster",
+ }
+ block = payload.get(spec.input_key)
+ if not isinstance(block, Mapping):
+ return _unevaluated(
+ spec,
+ f"payload has no {spec.input_key!r} block; a three.js interpolant can only be evaluated "
+ f"by the host harness, and an unrun harness is not a pass",
+ threshold,
+ )
+
+ delta = block.get("maxSampledBindingDelta")
+ if not _finite(delta):
+ return _unevaluated(
+ spec,
+ f"{spec.input_key}.maxSampledBindingDelta is missing or not a finite number "
+ f"(got {delta!r})",
+ threshold,
+ )
+ delta = float(delta)
+
+ roster = _clip_roster(payload)
+ if roster is None:
+ return _unevaluated(
+ spec,
+ "no independent clip roster: the payload carries neither a sampled-clip `clips` list "
+ "nor a top-level `clipNames`, so \"covered every clip\" cannot be checked against "
+ "anything the harness did not choose itself",
+ threshold,
+ maxSampledBindingDelta=delta,
+ )
+
+ sampled = _normalise_sampled_clips(block.get("clips"))
+ if sampled is None:
+ return _unevaluated(
+ spec,
+ f"{spec.input_key}.clips must be a per-clip sample-count map or list; without it the "
+ f"reported delta has no coverage behind it",
+ threshold,
+ maxSampledBindingDelta=delta,
+ clipsInRoster=len(roster),
+ )
+
+ missing = [name for name in roster if name not in sampled]
+ thin: dict[str, int] = {}
+ unreadable: list[str] = []
+ for name in roster:
+ entry = sampled.get(name)
+ if entry is None:
+ continue
+ count = _positive_int(entry.get("sampleCount"))
+ if count is None:
+ unreadable.append(name)
+ elif count < MINIMUM_GATE_R1_SAMPLES:
+ thin[name] = count
+ extra = [name for name in sampled if name not in roster]
+
+ coverage = {
+ "clipsInRoster": len(roster),
+ "clipsSampled": len([n for n in roster if n in sampled]),
+ "minimumSamplesPerClip": MINIMUM_GATE_R1_SAMPLES,
+ "clipsMissing": missing,
+ "clipsUnderSampled": thin,
+ "clipsWithUnreadableSampleCount": unreadable,
+ "clipsNotInRoster": extra,
+ }
+ measured = {"maxSampledBindingDelta": delta, "coverage": coverage}
+
+ problems: list[str] = []
+ if not (delta <= BINDING_EPSILON): # not(<=) also catches NaN
+ problems.append(
+ f"maxSampledBindingDelta = {delta:.6e} exceeds float32 epsilon {BINDING_EPSILON:.6e}; "
+ f"the binding path does not reach the node"
+ )
+ if missing:
+ problems.append(
+ f"the harness skipped {len(missing)} of {len(roster)} clips ({', '.join(missing)}); "
+ f"a clip nobody sampled is exactly the clip that plays silently"
+ )
+ if thin:
+ listed = ", ".join(f"{name} sampled {count}x" for name, count in sorted(thin.items()))
+ problems.append(
+ f"{len(thin)} clip(s) sampled fewer than {MINIMUM_GATE_R1_SAMPLES} times ({listed}); "
+ f"under-coverage is a failure, not a pass"
+ )
+ if unreadable:
+ problems.append(
+ f"{len(unreadable)} clip(s) report no readable sampleCount ({', '.join(unreadable)})"
+ )
+
+ warnings = []
+ if extra:
+ warnings.append(
+ f"harness sampled {len(extra)} clip(s) absent from the roster: {', '.join(extra)}"
+ )
+
+ if problems:
+ return _verdict(spec, False, threshold, measured, "; ".join(problems), warnings)
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"maxSampledBindingDelta = {delta:.3e} <= {BINDING_EPSILON:.3e} over "
+ f"{len(roster)} clip(s), each sampled at least {MINIMUM_GATE_R1_SAMPLES} times",
+ warnings,
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G2 — deformation finite
+# ---------------------------------------------------------------------------------------------
+
+
+def _per_frame_counts(entry: Any) -> tuple[int | None, list[int] | None]:
+ """Return (frames, per-frame vertex counts) from a mesh entry, or (None, None) if unreadable.
+
+ `verticesPerFrame` given as one number is read as the MINIMUM across that mesh's frames -- the
+ only reading under which a single number can support a per-frame claim (ambiguity 2).
+ """
+ if not isinstance(entry, Mapping):
+ return None, None
+ frames = _positive_int(entry.get("frames"))
+ vertices = entry.get("verticesPerFrame")
+ if isinstance(vertices, (list, tuple)):
+ counts = [_positive_int(v) for v in vertices]
+ if any(c is None for c in counts):
+ return frames, None
+ resolved = [int(c) for c in counts if c is not None]
+ if frames is None:
+ frames = len(resolved)
+ return frames, resolved
+ single = _positive_int(vertices)
+ if single is None or frames is None:
+ return frames, None
+ return frames, [single] * frames
+
+
+def gate_g2(payload: Mapping[str, Any]) -> GateResult:
+ """applyBoneTransform on >= 64 vertices/mesh/frame, all finite.
+
+ Two separate claims, and the gate needs both: a NaN weight or an out-of-range index sends one
+ vertex to infinity, and a harness that only transformed 8 vertices of a 20k mesh has not looked
+ where that vertex is. Under-sampled coverage FAILS (ambiguity 2).
+ """
+ spec = GATE_SPEC_BY_ID["G2"]
+ threshold = {
+ "allFinite": True,
+ "minimumVerticesPerMeshPerFrame": MINIMUM_G2_VERTICES,
+ "minimumFramesPerMesh": 1,
+ }
+ block = payload.get(spec.input_key)
+ if not isinstance(block, Mapping):
+ return _unevaluated(
+ spec,
+ f"payload has no {spec.input_key!r} block; applyBoneTransform runs in the host, and an "
+ f"unrun harness is not a pass",
+ threshold,
+ )
+
+ non_finite = _positive_int(block.get("nonFiniteCount"))
+ all_finite = block.get("allFinite")
+ if non_finite is None and not isinstance(all_finite, bool):
+ return _unevaluated(
+ spec,
+ f"{spec.input_key} reports neither `nonFiniteCount` nor a boolean `allFinite`; there is "
+ f"no finiteness claim to check",
+ threshold,
+ )
+
+ meshes = block.get("meshes")
+ if not isinstance(meshes, Mapping) or not meshes:
+ return _unevaluated(
+ spec,
+ f"{spec.input_key}.meshes must be a non-empty per-mesh coverage map; a finiteness claim "
+ f"with no coverage behind it says nothing about the mesh nobody transformed",
+ threshold,
+ nonFiniteCount=non_finite,
+ )
+
+ per_mesh: dict[str, Any] = {}
+ thin: list[str] = []
+ unreadable: list[str] = []
+ for name, entry in meshes.items():
+ frames, counts = _per_frame_counts(entry)
+ if counts is None or frames is None:
+ unreadable.append(str(name))
+ per_mesh[str(name)] = {"frames": frames, "minVerticesPerFrame": None}
+ continue
+ smallest = min(counts) if counts else 0
+ per_mesh[str(name)] = {"frames": frames, "minVerticesPerFrame": smallest}
+ if frames < 1:
+ thin.append(f"{name} transformed over 0 frames")
+ elif smallest < MINIMUM_G2_VERTICES:
+ thin.append(
+ f"{name} transformed {smallest} vertices in its thinnest frame "
+ f"(< {MINIMUM_G2_VERTICES})"
+ )
+
+ measured = {
+ "nonFiniteCount": non_finite,
+ "allFinite": all_finite,
+ "meshes": per_mesh,
+ "meshCount": len(meshes),
+ }
+
+ problems: list[str] = []
+ if non_finite is not None and non_finite > 0:
+ problems.append(
+ f"{non_finite} non-finite deformed vertex value(s); a bad skin index reads a garbage "
+ f"matrix and a NaN weight propagates to every vertex it touches"
+ )
+ if all_finite is False:
+ problems.append("harness reports allFinite = false")
+ if thin:
+ problems.append(
+ f"vertex coverage below {MINIMUM_G2_VERTICES}/mesh/frame: " + "; ".join(thin)
+ )
+ if unreadable:
+ problems.append(
+ f"{len(unreadable)} mesh entr(ies) report no readable frames/verticesPerFrame: "
+ + ", ".join(unreadable)
+ )
+
+ if problems:
+ return _verdict(spec, False, threshold, measured, "; ".join(problems))
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"all deformed values finite over {len(meshes)} mesh(es), each at least "
+ f"{MINIMUM_G2_VERTICES} vertices per frame",
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G3 — bind restore
+# ---------------------------------------------------------------------------------------------
+
+
+def gate_g3(payload: Mapping[str, Any]) -> GateResult:
+ """maxBindRestoreDelta <= 1e-12 after stop().
+
+ Restoring the bind pose before each play is what stops clips bleeding into one another: a clip
+ that ends mid-pose leaves joints displaced, and the next clip's tracks only overwrite the joints
+ they address. The residue is invisible until a clip that never touches the shoulder plays after
+ one that did.
+ """
+ spec = GATE_SPEC_BY_ID["G3"]
+ threshold = BIND_RESTORE_TOLERANCE
+ block = payload.get(spec.input_key)
+ if isinstance(block, Mapping):
+ delta = block.get("maxBindRestoreDelta")
+ elif _finite(block):
+ delta = block
+ else:
+ delta = None
+ if not _finite(delta):
+ return _unevaluated(
+ spec,
+ f"payload has no finite {spec.input_key}.maxBindRestoreDelta; the delta is measured in "
+ f"the host after stop(), and an unrun harness is not a pass",
+ threshold,
+ )
+ delta = float(delta)
+ if not (delta <= BIND_RESTORE_TOLERANCE): # not(<=) also catches NaN
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ delta,
+ f"maxBindRestoreDelta = {delta:.6e} exceeds {BIND_RESTORE_TOLERANCE:.1e}; joints are "
+ f"still displaced after stop(), so the next clip starts from the last one's pose",
+ )
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ delta,
+ f"maxBindRestoreDelta = {delta:.3e} <= {BIND_RESTORE_TOLERANCE:.1e}; the bind pose is "
+ f"restored exactly",
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G4 / G5 — delegated to skin_conditioning.validate_binding (Gate R2)
+# ---------------------------------------------------------------------------------------------
+
+_SUMMARY_PATTERN = re.compile(
+ r"\.\.\.\s+(\d+)\s+weight-sum failures \(worst ([^)]+)\) and (\d+) index-range failures"
+)
+
+
+@dataclass(frozen=True)
+class _BindingVerdict:
+ """One `validate_binding` run, split into the two gates that consume it.
+
+ Structural failures (wrong array lengths, joint_count < 1) belong to BOTH gates: on a malformed
+ binding neither the weight sums nor the index range has been checked, so neither may be called
+ a pass.
+ """
+
+ binding: SkinBinding | None
+ error: str | None
+ weight_failures: tuple[str, ...] = ()
+ index_failures: tuple[str, ...] = ()
+ structural_failures: tuple[str, ...] = ()
+ weight_failure_count: int = 0
+ index_failure_count: int = 0
+ worst_sum_error: float | None = None
+
+
+def _evaluate_binding(payload: Mapping[str, Any]) -> _BindingVerdict | None:
+ """Run Gate R2 once and partition its messages. Returns None when there is no binding at all."""
+ raw = payload.get("binding")
+ if raw is None:
+ return None
+ if isinstance(raw, SkinBinding):
+ binding = raw
+ elif isinstance(raw, Mapping):
+ try:
+ binding = SkinBinding.from_dict(dict(raw))
+ except Exception as exc:
+ return _BindingVerdict(binding=None, error=f"binding payload is unreadable: {exc}")
+ else:
+ return _BindingVerdict(
+ binding=None,
+ error=f"binding must be an object or a SkinBinding; got {type(raw).__name__}",
+ )
+
+ failures = validate_binding(binding)
+
+ weight: list[str] = []
+ index: list[str] = []
+ structural: list[str] = []
+ weight_count = 0
+ index_count = 0
+ worst: float | None = None
+
+ for message in failures:
+ summary = _SUMMARY_PATTERN.search(message)
+ if summary:
+ weight_count = max(weight_count, int(summary.group(1)))
+ index_count = max(index_count, int(summary.group(3)))
+ try:
+ worst = float(summary.group(2))
+ except ValueError:
+ worst = None
+ # The summary line carries both counts, so both gates get to quote it.
+ weight.append(message)
+ index.append(message)
+ elif "sum(w)" in message:
+ weight.append(message)
+ elif "skin index" in message:
+ index.append(message)
+ else:
+ structural.append(message)
+
+ weight_count = max(weight_count, sum(1 for m in weight if "sum(w)" in m))
+ index_count = max(index_count, sum(1 for m in index if "skin index" in m))
+
+ return _BindingVerdict(
+ binding=binding,
+ error=None,
+ weight_failures=tuple(weight),
+ index_failures=tuple(index),
+ structural_failures=tuple(structural),
+ weight_failure_count=weight_count,
+ index_failure_count=index_count,
+ worst_sum_error=worst,
+ )
+
+
+def gate_g4(payload: Mapping[str, Any], verdict: _BindingVerdict | None = None) -> GateResult:
+ """|1 - sum(w)| <= 2e-7 every vertex. Delegated in full to `skin_conditioning.validate_binding`.
+
+ The check is Gate R2's and stays there. Duplicating it here would let the gate and the stage
+ that produces the weights drift apart, and the first symptom of that drift would be a limb that
+ shrinks slightly every frame while both files claim to be correct.
+ """
+ spec = GATE_SPEC_BY_ID["G4"]
+ threshold = WEIGHT_SUM_TOLERANCE
+ if verdict is None:
+ verdict = _evaluate_binding(payload)
+ if verdict is None:
+ return _unevaluated(
+ spec,
+ "payload has no `binding`; weight normalisation cannot be checked without the weights",
+ threshold,
+ )
+ if verdict.error is not None:
+ return _unevaluated(spec, verdict.error, threshold)
+
+ messages = list(verdict.structural_failures) + list(verdict.weight_failures)
+ measured = {
+ "verticesOutOfTolerance": verdict.weight_failure_count,
+ "worstAbsSumError": verdict.worst_sum_error,
+ "vertexCount": verdict.binding.vertex_count if verdict.binding else None,
+ }
+ if messages:
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ "skin_conditioning.validate_binding rejected the binding: " + messages[0],
+ delegatedFailures=messages,
+ delegatedTo="skin_conditioning.validate_binding",
+ )
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"skin_conditioning.validate_binding found no weight-sum failure across "
+ f"{measured['vertexCount']} vertices",
+ delegatedTo="skin_conditioning.validate_binding",
+ )
+
+
+def gate_g5(payload: Mapping[str, Any], verdict: _BindingVerdict | None = None) -> GateResult:
+ """maxSkinIndex <= bones - 1. Delegated in full to `skin_conditioning.validate_binding`.
+
+ The index check lives after the top-4 reduction because the reduction rewrites the indices:
+ being in range before it says nothing about being in range after.
+ """
+ spec = GATE_SPEC_BY_ID["G5"]
+ if verdict is None:
+ verdict = _evaluate_binding(payload)
+ if verdict is None:
+ return _unevaluated(
+ spec,
+ "payload has no `binding`; skin indices cannot be range-checked without them",
+ {"maxSkinIndex": "bones - 1"},
+ )
+ if verdict.error is not None:
+ return _unevaluated(spec, verdict.error, {"maxSkinIndex": "bones - 1"})
+
+ binding = verdict.binding
+ bones = binding.joint_count if binding else None
+ threshold = {"maxSkinIndex": (bones - 1) if isinstance(bones, int) else "bones - 1"}
+ max_index = max(binding.skin_indices) if binding and binding.skin_indices else None
+ measured = {
+ "maxSkinIndex": max_index,
+ "boneCount": bones,
+ "slotsOutOfRange": verdict.index_failure_count,
+ }
+
+ messages = list(verdict.structural_failures) + list(verdict.index_failures)
+ if messages:
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ "skin_conditioning.validate_binding rejected the binding: " + messages[0],
+ delegatedFailures=messages,
+ delegatedTo="skin_conditioning.validate_binding",
+ )
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"maxSkinIndex = {max_index} <= {bones - 1 if isinstance(bones, int) else '?'}",
+ delegatedTo="skin_conditioning.validate_binding",
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G6 — every visible mesh bound
+# ---------------------------------------------------------------------------------------------
+
+
+def gate_g6(payload: Mapping[str, Any]) -> GateResult:
+ """visibleMeshCount == visibleSkinnedMeshCount.
+
+ Catches a part left behind in bind pose: the figure animates, one shoulder pad does not, and
+ nothing about the frame looks broken until the arm moves far enough for the pad to be obviously
+ detached. Equality is the criterion as written, so more skinned than visible fails too
+ (ambiguity 6) -- the two counts disagree and one of them is wrong either way.
+ """
+ spec = GATE_SPEC_BY_ID["G6"]
+ threshold = "visibleMeshCount == visibleSkinnedMeshCount"
+ block = payload.get(spec.input_key)
+ if not isinstance(block, Mapping):
+ return _unevaluated(
+ spec,
+ f"payload has no {spec.input_key!r} block; the scene graph is walked in the host, and "
+ f"an unwalked scene is not a pass",
+ threshold,
+ )
+ visible = _positive_int(block.get("visibleMeshCount"))
+ skinned = _positive_int(block.get("visibleSkinnedMeshCount"))
+ if visible is None or skinned is None:
+ return _unevaluated(
+ spec,
+ f"{spec.input_key} needs both visibleMeshCount and visibleSkinnedMeshCount as "
+ f"non-negative integers; got {block.get('visibleMeshCount')!r} and "
+ f"{block.get('visibleSkinnedMeshCount')!r}",
+ threshold,
+ )
+ unbound = block.get("unboundMeshes")
+ named = [str(n) for n in unbound] if isinstance(unbound, (list, tuple)) else []
+ measured = {
+ "visibleMeshCount": visible,
+ "visibleSkinnedMeshCount": skinned,
+ "unboundMeshes": named,
+ }
+ if visible != skinned:
+ detail = f" ({', '.join(named)})" if named else ""
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ f"{visible} visible mesh(es) but {skinned} skinned{detail}; "
+ f"{abs(visible - skinned)} mesh(es) unaccounted for",
+ )
+ if named:
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ f"counts agree at {visible} but the harness also names unbound meshes "
+ f"({', '.join(named)}); the counts and the list contradict each other",
+ )
+ return _verdict(
+ spec, True, threshold, measured, f"all {visible} visible mesh(es) are skinned"
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G9 — no joint scale (delegated measurement: clip_features.measure_clip)
+# ---------------------------------------------------------------------------------------------
+
+
+def gate_g9(payload: Mapping[str, Any]) -> GateResult:
+ """scaleDelta == 0 unless the source has it.
+
+ scaleDelta is a tripwire, not a descriptor. A non-zero value means the source rig scales joints,
+ which changes what Stage R2 may legally do to skin weights -- proximity blending averages two
+ parts' bindings, and averaging across a scaled joint invalidates the blend rather than softening
+ it. The "unless" clause must be DECLARED (`sourceScalesJoints: true`) and then produces a pass
+ carrying a warning that names the clips (ambiguity 5). It is never a silent pass.
+ """
+ spec = GATE_SPEC_BY_ID["G9"]
+ declared = payload.get("sourceScalesJoints") is True
+ threshold = {"scaleDelta": 0.0, "sourceScalesJointsDeclared": declared}
+
+ clips = payload.get("clips")
+ if not isinstance(clips, (list, tuple)) or not clips:
+ return _unevaluated(
+ spec,
+ "payload has no sampled-clip `clips` list; scaleDelta is measured from the clips and "
+ "an absent one cannot be assumed to be zero",
+ threshold,
+ )
+ height = payload.get("figureHeight")
+ if not _finite(height) or float(height) <= 0.0:
+ return _unevaluated(
+ spec,
+ f"payload.figureHeight must be a finite positive number to measure clips; got {height!r}",
+ threshold,
+ )
+
+ per_clip: dict[str, float] = {}
+ try:
+ for clip in clips:
+ features = measure_clip(clip, float(height))
+ per_clip[features.source_name] = features.scale_delta
+ except Exception as exc:
+ return _unevaluated(
+ spec,
+ f"clip_features.measure_clip could not measure the payload: {exc}",
+ threshold,
+ )
+
+ scaling = {name: value for name, value in per_clip.items() if value > 0.0}
+ worst = max(per_clip.values()) if per_clip else 0.0
+ measured = {"maxScaleDelta": worst, "scaleDeltaByClip": per_clip, "clipsScaling": list(scaling)}
+
+ if not scaling:
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"scaleDelta == 0 on all {len(per_clip)} clip(s); no joint is scaled",
+ )
+ listed = ", ".join(f"{name} ({value:.6g})" for name, value in sorted(scaling.items()))
+ if declared:
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"pass with warning: {len(scaling)} clip(s) scale joints and the payload declares "
+ f"sourceScalesJoints = true",
+ warnings=[
+ f"source rig scales joints on {len(scaling)} clip(s): {listed}. This is admitted, "
+ f"not measured away -- Stage R2's proximity blend averages bindings across parts "
+ f"and that averaging is invalidated by a scaled joint. Whoever runs R2 must be told."
+ ],
+ )
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ f"scaleDelta > 0 on {len(scaling)} clip(s): {listed}. Nothing declares "
+ f"sourceScalesJoints, so this is an undeclared joint scale and Stage R2's weight blend "
+ f"cannot be trusted on this rig",
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G7 — medial/lateral (delegated to action_design.check_medial_lateral)
+# ---------------------------------------------------------------------------------------------
+
+
+def gate_g7(payload: Mapping[str, Any]) -> GateResult:
+ """leftAnchor.x > 0 > rightAnchor.x. Delegated to `action_design.check_medial_lateral`.
+
+ One comparison catches a mirrored rig, the failure where every left-hand action plays on the
+ right and nothing about it looks wrong in isolation.
+
+ AMBIGUITY 8 -- THE TAUTOLOGY. `action_design.Chains.gate_is_independent` records something the
+ R6 table does not: when the side labels were assigned by "left = +X" rather than supplied from
+ outside the geometry, the gate is comparing the geometry against a claim derived from that same
+ geometry, and the mirrored-rig case is unreachable. READING: an errorless run of a
+ non-independent gate is reported `unevaluated`, not `pass`, because a pass that could not have
+ failed is exactly the silent pass this module exists to prevent. A non-empty error list is still
+ a `fail` -- a degenerate pair is a real finding either way.
+ """
+ spec = GATE_SPEC_BY_ID["G7"]
+ threshold = "leftAnchor.x > 0 > rightAnchor.x"
+ block = payload.get(spec.input_key)
+ if isinstance(block, Chains):
+ chains: Chains | None = block
+ medial_tolerance = None
+ elif isinstance(block, Mapping):
+ joints = block.get("joints")
+ if not isinstance(joints, (list, tuple)) or not joints:
+ return _unevaluated(
+ spec,
+ f"{spec.input_key}.joints must be a non-empty joint hierarchy; chains are resolved "
+ f"from topology (R4) and there is nothing here to resolve",
+ threshold,
+ )
+ side_labels = block.get("sideLabels")
+ medial_tolerance = block.get("medialTolerance")
+ kwargs: dict[str, Any] = {}
+ if isinstance(side_labels, Mapping):
+ kwargs["side_labels"] = {str(k): str(v) for k, v in side_labels.items()}
+ if _finite(block.get("symmetryTolerance")):
+ kwargs["symmetry_tolerance"] = float(block["symmetryTolerance"])
+ try:
+ chains = resolve_chains(joints, **kwargs)
+ except ChainResolutionError as exc:
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ None,
+ f"action_design.resolve_chains could not resolve the chains: {exc}. R4 fails closed "
+ f"rather than guessing, and an unresolvable hierarchy cannot be gated",
+ delegatedTo="action_design.resolve_chains",
+ )
+ else:
+ return _unevaluated(
+ spec,
+ f"payload has no {spec.input_key!r} block (a joint hierarchy, optionally with "
+ f"sideLabels); the medial/lateral convention cannot be checked without anchors",
+ threshold,
+ )
+
+ tolerance = float(medial_tolerance) if _finite(medial_tolerance) else MEDIAL_AXIS_TOLERANCE
+ errors = check_medial_lateral(chains, medial_tolerance=tolerance)
+ measured = {
+ "armLeftAnchorX": chains.arm["l"].anchor_position[0],
+ "armRightAnchorX": chains.arm["r"].anchor_position[0],
+ "legLeftAnchorX": chains.leg["l"].anchor_position[0],
+ "legRightAnchorX": chains.leg["r"].anchor_position[0],
+ "sideSource": chains.side_source,
+ "gateIsIndependent": chains.gate_is_independent,
+ }
+ if errors:
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ "action_design.check_medial_lateral rejected the rig: " + errors[0],
+ delegatedFailures=errors,
+ delegatedTo="action_design.check_medial_lateral",
+ )
+ if not chains.gate_is_independent:
+ return _unevaluated(
+ spec,
+ f"chains resolved with side_source={chains.side_source!r}: the left/right labels were "
+ f"assigned from model X, the same geometry the gate compares them against, so a "
+ f"mirrored rig could not have been caught. Supply `sideLabels` (the source rig's own "
+ f"naming, which is the claim a mirrored rig gets wrong) to give the gate teeth",
+ threshold,
+ **measured,
+ )
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"left anchors are +X and right anchors are -X, checked against an independent side-label "
+ f"claim (side_source={chains.side_source!r})",
+ delegatedTo="action_design.check_medial_lateral",
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G8 — foot contact (delegated to action_design.foot_slide)
+# ---------------------------------------------------------------------------------------------
+
+
+def gate_g8(payload: Mapping[str, Any]) -> GateResult:
+ """footSlide <= 0.01H in stance. Delegated per clip to `action_design.foot_slide`.
+
+ "The single most valuable gate in the stage": a skating gait reads as floaty to every viewer
+ and almost nobody can name what is wrong with it, so it survives review and playtest notes and
+ is fixed only when somebody finally puts a number on the stance frames.
+
+ Positions are the payload's WORLD landmark positions, which is the frame `foot_slide` requires.
+ Handing it a hip-relative clip inverts the measurement -- with the root's planar motion removed,
+ a correctly planted foot slides backwards by exactly `travel` per cycle and the gate rejects the
+ one gait that was right.
+
+ Clips carrying no `stance` are recorded and warned about rather than failed: this module cannot
+ tell a gait clip from a gesture clip without re-classifying, and failing every non-gait clip for
+ lacking stance would make the gate unusable. The warning is there so the omission is visible.
+ """
+ spec = GATE_SPEC_BY_ID["G8"]
+ threshold = {"footSlide": FOOT_SLIDE_LIMIT, "units": "fraction of figure height H"}
+
+ clips = payload.get("clips")
+ if not isinstance(clips, (list, tuple)) or not clips:
+ return _unevaluated(
+ spec,
+ "payload has no sampled-clip `clips` list; footSlide is measured on stance frames and "
+ "there are none",
+ threshold,
+ )
+ height = payload.get("figureHeight")
+ if not _finite(height) or float(height) <= 0.0:
+ return _unevaluated(
+ spec,
+ f"payload.figureHeight must be a finite positive number; got {height!r}",
+ threshold,
+ )
+ height = float(height)
+
+ per_clip: dict[str, Any] = {}
+ without_stance: list[str] = []
+ failing: list[str] = []
+ unmeasured: list[str] = []
+ worst_value: float | None = None
+ worst_clip: str | None = None
+
+ for index, clip in enumerate(clips):
+ if not isinstance(clip, Mapping):
+ unmeasured.append(f"clips[{index}] is not an object")
+ continue
+ name = str(clip.get("sourceName", f"clips[{index}]"))
+ stance = clip.get("stance")
+ if not isinstance(stance, Mapping) or not stance:
+ without_stance.append(name)
+ continue
+ positions = clip.get("landmarkPositions")
+ times = clip.get("sampleTimes")
+ if not isinstance(positions, Mapping) or not isinstance(times, (list, tuple)):
+ unmeasured.append(f"{name}: stance declared but landmarkPositions/sampleTimes missing")
+ continue
+ try:
+ report = foot_slide(positions, times, stance, height, limit=FOOT_SLIDE_LIMIT)
+ except Exception as exc:
+ unmeasured.append(f"{name}: action_design.foot_slide could not measure it: {exc}")
+ continue
+ per_clip[name] = report.to_dict()
+ if report.max_slide_fraction is not None:
+ if worst_value is None or report.max_slide_fraction > worst_value:
+ worst_value = report.max_slide_fraction
+ worst_clip = name
+ if report.status == STATUS_FAIL:
+ failing.append(f"{name}: {report.reason}")
+ elif report.status == STATUS_UNEVALUATED:
+ unmeasured.append(f"{name}: {report.reason}")
+
+ measured = {
+ "maxFootSlideFraction": worst_value,
+ "worstClip": worst_clip,
+ "clipsMeasured": len(per_clip),
+ "perClip": per_clip,
+ }
+ warnings: list[str] = []
+ if without_stance:
+ warnings.append(
+ f"{len(without_stance)} clip(s) declare no stance intervals and were not gated: "
+ + ", ".join(without_stance)
+ + ". A gait among them would escape G8 entirely"
+ )
+ if unmeasured:
+ warnings.append("unmeasurable stance data: " + "; ".join(unmeasured))
+
+ if not per_clip:
+ return _unevaluated(
+ spec,
+ "no clip carried a measurable stance interval; Gate G8 with no stance data is not a "
+ "pass, it is an unasked question"
+ + (f" ({'; '.join(unmeasured)})" if unmeasured else "")
+ + (f" [clips without stance: {', '.join(without_stance)}]" if without_stance else ""),
+ threshold,
+ **{"perClip": per_clip, "clipsWithoutStance": without_stance},
+ )
+ if failing:
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ f"{len(failing)} clip(s) skate: " + "; ".join(failing),
+ warnings,
+ clipsWithoutStance=without_stance,
+ delegatedTo="action_design.foot_slide",
+ )
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"footSlide {worst_value:.6g}H <= {FOOT_SLIDE_LIMIT:.6g}H across {len(per_clip)} clip(s)"
+ if worst_value is not None
+ else f"footSlide within {FOOT_SLIDE_LIMIT:.6g}H across {len(per_clip)} clip(s)",
+ warnings,
+ clipsWithoutStance=without_stance,
+ delegatedTo="action_design.foot_slide",
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G10 — skin integrity sweep
+# ---------------------------------------------------------------------------------------------
+
+_SWEEP_AXES = ("clips", "times", "sides", "azimuths")
+
+
+def gate_g10(
+ payload: Mapping[str, Any], coverage: SweepCoverage = DEFAULT_SWEEP_COVERAGE
+) -> GateResult:
+ """background-through-split <= measured baseline, over a sweep that is actually a sweep.
+
+ FIVE POSES IS NOT COVERAGE. The spec says so in as many words, and the number behind it is
+ concrete: coincidence-welding looked correct until a sweep of 11 clips x 4 times x 3 azimuths =
+ 132 frames found cracks in 28 of them. A sweep is a claim about the frames nobody looked at, so
+ the per-axis breakdown is required and a thin axis FAILS however clean its hole count is
+ (ambiguity 3).
+
+ HOLES AND CREASES ARE TWO NUMBERS, ALWAYS. Stage R2 trades one against the other on purpose --
+ proximity blending took holes from 974 px to 287 px and pushed creases from 31,316 px to 36,470,
+ accepted because a hole shows the background and a crease shows skin. A single combined score
+ hides that trade and invites a later stage to "fix" the crease count by disabling the blend.
+ Creases are therefore REPORTED and never gated here; gating them would ask for exactly that.
+ """
+ spec = GATE_SPEC_BY_ID["G10"]
+ block = payload.get(spec.input_key)
+ roster = _clip_roster(payload)
+ roster_count = len(roster) if roster is not None else None
+ threshold: dict[str, Any] = {
+ "backgroundThroughSplitPx": "<= measured baseline",
+ "creasePx": "reported, never gated (see the R2 trade)",
+ "minimumAxes": coverage.to_dict(),
+ "clipsInRoster": roster_count,
+ }
+ if not isinstance(block, Mapping):
+ return _unevaluated(
+ spec,
+ f"payload has no {spec.input_key!r} block; G10 is a visual gate and needs a render "
+ f"harness. An unrun sweep is not a clean sweep",
+ threshold,
+ )
+
+ axes: dict[str, int] = {}
+ missing_axes: list[str] = []
+ for axis in _SWEEP_AXES:
+ value = _positive_int(block.get(axis))
+ if value is None:
+ missing_axes.append(axis)
+ else:
+ axes[axis] = value
+ frames = _positive_int(block.get("frames"))
+
+ if missing_axes or frames is None:
+ return _unevaluated(
+ spec,
+ f"the sweep declares no usable "
+ + (f"frame count; " if frames is None else "")
+ + (f"per-axis breakdown (missing {', '.join(missing_axes)}); " if missing_axes else "")
+ + "a bare total cannot show which axis was skipped, and five poses is not coverage",
+ threshold,
+ declaredFrames=frames,
+ declaredAxes=axes,
+ )
+
+ holes = block.get("backgroundThroughSplitPx")
+ creases = block.get("creasePx")
+ baseline = block.get("baseline")
+ baseline_holes = (
+ baseline.get("backgroundThroughSplitPx") if isinstance(baseline, Mapping) else None
+ )
+ baseline_creases = baseline.get("creasePx") if isinstance(baseline, Mapping) else None
+
+ if not _finite(holes):
+ return _unevaluated(
+ spec,
+ f"{spec.input_key}.backgroundThroughSplitPx is missing or not a finite number "
+ f"(got {holes!r}); there is no measurement to compare",
+ threshold,
+ declaredFrames=frames,
+ declaredAxes=axes,
+ )
+ if not _finite(baseline_holes):
+ return _unevaluated(
+ spec,
+ f"{spec.input_key}.baseline.backgroundThroughSplitPx is missing; the criterion is "
+ f"\"<= measured baseline\" and the baseline is the control run with the blend disabled. "
+ f"Borrowing another subject's number is not a measurement of this one",
+ threshold,
+ declaredFrames=frames,
+ declaredAxes=axes,
+ backgroundThroughSplitPx=float(holes),
+ )
+
+ product = axes["clips"] * axes["times"] * axes["sides"] * axes["azimuths"]
+ clip_axis_target = roster_count if roster_count is not None else axes["clips"]
+ required_frames = coverage.required_frames(clip_axis_target)
+
+ measured = {
+ "backgroundThroughSplitPx": float(holes),
+ "backgroundThroughSplitBlobs": block.get("backgroundThroughSplitBlobs"),
+ "creasePx": float(creases) if _finite(creases) else None,
+ "baselineBackgroundThroughSplitPx": float(baseline_holes),
+ "baselineCreasePx": float(baseline_creases) if _finite(baseline_creases) else None,
+ "frames": frames,
+ "axes": dict(axes),
+ "requiredFrames": required_frames,
+ "note": (
+ "holes and creases are two numbers on purpose; Stage R2 trades one against the other "
+ "and a single combined score hides that"
+ ),
+ }
+
+ problems: list[str] = []
+ if frames != product:
+ problems.append(
+ f"the sweep declares {frames} frames but its axes multiply to {product} "
+ f"({axes['clips']} clips x {axes['times']} times x {axes['sides']} sides x "
+ f"{axes['azimuths']} azimuths); one of the two numbers is wrong"
+ )
+ thin_axes = []
+ if axes["times"] < coverage.times:
+ thin_axes.append(f"{axes['times']} times (< {coverage.times})")
+ if axes["sides"] < coverage.sides:
+ thin_axes.append(f"{axes['sides']} sides (< {coverage.sides})")
+ if axes["azimuths"] < coverage.azimuths:
+ thin_axes.append(f"{axes['azimuths']} azimuths (< {coverage.azimuths})")
+ if thin_axes:
+ problems.append(
+ "sweep axes too thin: " + ", ".join(thin_axes) + " — five poses is not coverage"
+ )
+ if roster_count is not None and axes["clips"] < roster_count:
+ problems.append(
+ f"the sweep covered {axes['clips']} of {roster_count} clip(s); the frames that tear are "
+ f"in the clips nobody rendered"
+ )
+ if frames < required_frames:
+ problems.append(
+ f"{frames} frames is materially thinner than the {required_frames} its declared clip "
+ f"set allows ({clip_axis_target} clips x {coverage.times} times x {coverage.sides} "
+ f"sides x {coverage.azimuths} azimuths)"
+ )
+ if not (float(holes) <= float(baseline_holes)): # not(<=) also catches NaN
+ problems.append(
+ f"background through splits {float(holes):.6g} px exceeds the measured baseline "
+ f"{float(baseline_holes):.6g} px; the skin tears under motion"
+ )
+
+ warnings: list[str] = []
+ if not _finite(creases):
+ warnings.append(
+ "no creasePx reported. R2 trades holes against creases deliberately and both numbers "
+ "have to be visible, or a later stage will 'fix' one by undoing the other"
+ )
+ elif _finite(baseline_creases) and float(creases) > float(baseline_creases):
+ warnings.append(
+ f"creases rose from {float(baseline_creases):.6g} px to {float(creases):.6g} px "
+ f"(+{100.0 * (float(creases) / float(baseline_creases) - 1.0):.1f}%). This is the R2 "
+ f"trade, accepted on purpose — a hole shows the background, a crease shows skin — and "
+ f"it is reported, not gated. Do not 'fix' it by disabling the blend"
+ )
+
+ if problems:
+ return _verdict(spec, False, threshold, measured, "; ".join(problems), warnings)
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"background through splits {float(holes):.6g} px <= baseline "
+ f"{float(baseline_holes):.6g} px over {frames} frames "
+ f"({axes['clips']}x{axes['times']}x{axes['sides']}x{axes['azimuths']})",
+ warnings,
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G11 — mesh parity (delegated to mesh_parity.verify)
+# ---------------------------------------------------------------------------------------------
+
+
+def gate_g11(payload: Mapping[str, Any]) -> GateResult:
+ """Every frozen buffer byte-identical after binding. Delegated to `mesh_parity.verify`.
+
+ Rigging an already-built model is meant to be ADDITIVE: a skeleton appears, two vertex
+ attributes appear, some clips appear. Nothing about it requires touching a position, a normal,
+ a uv or an index. The animation pass is nevertheless exactly where meshes come back disjointed,
+ and by the time the damage shows it is buried under a rig built on top of it — so it is no
+ longer clear whether the mesh or the skinning is at fault. This gate answers that question
+ before it has to be asked.
+
+ THIS GATE ADDS NO PARITY RULE OF ITS OWN (ambiguity 10). `mesh_parity` decides what counts as a
+ change, including the manifest/payload disagreements about which meshes exist; re-deriving any
+ of it here is how a gate and the stage it gates start disagreeing about what "byte-identical"
+ meant. What this function owns is the verdict mapping and carrying the detail through.
+
+ AND IT MUST NOT FAIL A SUCCESSFUL RIG (ambiguity 11). `skinIndex` and `skinWeight` sit outside
+ FROZEN_BUFFERS on purpose — adding them is the whole legal purpose of the implementation phase.
+ They are reported in `measured.addedLegal` and never contribute to the verdict.
+ """
+ spec = GATE_SPEC_BY_ID["G11"]
+ threshold = {
+ "frozenBuffers": list(mesh_parity.FROZEN_BUFFERS),
+ "criterion": "byte-identical over packed float64/int64",
+ "notFrozen": ["skinIndex", "skinWeight"],
+ }
+ block = payload.get(spec.input_key)
+ if not isinstance(block, Mapping):
+ return _unevaluated(
+ spec,
+ f"payload has no {spec.input_key!r} block; geometry parity needs both a freeze manifest "
+ f"and the post-bind buffers, and unproven is not the same as unbroken",
+ threshold,
+ )
+
+ raw_manifest = block.get("manifest")
+ after = block.get("after")
+ missing: list[str] = []
+ if not isinstance(raw_manifest, Mapping):
+ missing.append("`manifest` (the freeze record taken before rigging)")
+ if not isinstance(after, Mapping):
+ missing.append("`after` (the post-bind buffer payload)")
+ if missing:
+ return _unevaluated(
+ spec,
+ f"{spec.input_key} is missing {' and '.join(missing)}; parity is a comparison and needs "
+ f"both halves. Geometry parity is unproven, which is not the same as unbroken",
+ threshold,
+ manifestPresent=isinstance(raw_manifest, Mapping),
+ afterPresent=isinstance(after, Mapping),
+ )
+
+ try:
+ manifest = mesh_parity.Manifest.from_dict(dict(raw_manifest))
+ except Exception as exc:
+ return _unevaluated(
+ spec,
+ f"the freeze manifest is unreadable: {exc}. A manifest that cannot be parsed proves "
+ f"nothing about the geometry either way",
+ threshold,
+ )
+ try:
+ report = mesh_parity.verify(manifest, dict(after))
+ except Exception as exc:
+ return _unevaluated(
+ spec,
+ f"the post-bind buffer payload is unreadable: {exc}",
+ threshold,
+ )
+
+ measured = {
+ "meshesFrozen": report.meshes_frozen,
+ "meshesCompared": report.meshes_compared,
+ "failureCount": report.failure_count,
+ "failures": [failure.to_dict() for failure in report.failures],
+ "addedLegalCount": report.addition_count,
+ "addedLegal": list(report.additions),
+ }
+ warnings: list[str] = []
+ if report.additions:
+ warnings.append(
+ f"{report.addition_count} attribute(s) added and legal: "
+ + ", ".join(report.additions)
+ + ". Adding skinIndex/skinWeight is the purpose of rigging, not a violation — reported "
+ "so the addition is visible, never gated"
+ )
+
+ if report.status == mesh_parity.STATUS_UNEVALUATED:
+ return _unevaluated(
+ spec,
+ f"mesh_parity.verify could not evaluate parity: {report.reason}",
+ threshold,
+ **measured,
+ )
+ if report.status == mesh_parity.STATUS_FAIL:
+ first = report.failures[0] if report.failures else None
+ headline = str(first) if first is not None else "parity failed with no failure detail"
+ if first is not None and first.differences:
+ difference = first.differences[0]
+ headline += (
+ f" (first differing element {difference.index}: {difference.frozen} -> "
+ f"{difference.current}, {first.differing_elements} element(s) differ)"
+ )
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ f"{report.failure_count} parity failure(s); rigging rewrote frozen geometry. {headline}",
+ warnings,
+ delegatedTo="mesh_parity.verify",
+ summary=report.summary(),
+ )
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"every frozen buffer byte-identical across {report.meshes_compared} of "
+ f"{report.meshes_frozen} frozen mesh(es)",
+ warnings,
+ delegatedTo="mesh_parity.verify",
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# G12 — rig reference
+# ---------------------------------------------------------------------------------------------
+
+
+def gate_g12(payload: Mapping[str, Any]) -> GateResult:
+ """The animation must address the GLB's own skeleton, or an explicitly usable correspondence.
+
+ Animation channels address GLB NODE indices and `JOINTS_0` addresses the SKIN's joint array.
+ Neither index space is valid against a procedurally authored skeleton, and neither fails loudly
+ when it is wrong: the channels bind, the mixer runs, and the vertices go somewhere. That is the
+ same silent class of failure as §0's — a plausible scene driven by the wrong numbers.
+
+ So there are exactly two acceptable answers, and the distinction between them is the whole
+ point of the gate:
+
+ * the rig came straight from the GLB, in which case the index spaces are the file's own; or
+ * a procedural skeleton coexists AND an explicit, USABLE correspondence maps it to the GLB's
+ joints. `Correspondence.usable` is False whenever ANY joint on EITHER side is unmatched,
+ because a partial map retargets the bones it knows and leaves the rest at bind pose. An
+ unmatched joint means the mapping was invented, and inventing it is what shreds a mesh.
+
+ A structural failure is a known-bad answer, not a missing one, so it FAILS rather than reporting
+ unevaluated (ambiguities 13 and 14).
+ """
+ spec = GATE_SPEC_BY_ID["G12"]
+ threshold = {
+ "source": "glb, or a correspondence with usable == true",
+ "structuralFailure": None,
+ "unsupportedInterpolationClips": [],
+ "supportedInterpolations": list(glb_rig_reference.SUPPORTED_INTERPOLATIONS),
+ }
+ block = payload.get(spec.input_key)
+ if not isinstance(block, Mapping):
+ return _unevaluated(
+ spec,
+ f"payload has no {spec.input_key!r} block; nothing states which skeleton the clip "
+ f"channels and skinIndex values address, and that is not something to assume",
+ threshold,
+ )
+
+ glb = block.get("glb")
+ if not isinstance(glb, Mapping):
+ return _unevaluated(
+ spec,
+ f"{spec.input_key} carries no `glb` report (from glb_rig_reference); there is no "
+ f"skeleton of record to check the animation against",
+ threshold,
+ )
+
+ source = block.get("source")
+ structural = glb.get("structuralFailure")
+ unsupported = glb.get("unsupportedInterpolationClips")
+ unsupported = list(unsupported) if isinstance(unsupported, (list, tuple)) else []
+ errors = glb.get("errors")
+ errors = list(errors) if isinstance(errors, (list, tuple)) else []
+ declared_ok = glb.get("ok")
+ # Ambiguity 12: `ok` is added by the CLI, not by GlbRig.to_dict(), so derive it when absent.
+ ok = bool(declared_ok) if isinstance(declared_ok, bool) else (not structural and not errors)
+ primary_skin = glb.get("primarySkinIndex")
+ correspondence = block.get("correspondence")
+
+ measured = {
+ "source": source,
+ "glbOk": ok,
+ "okWasDeclared": isinstance(declared_ok, bool),
+ "primarySkinIndex": primary_skin,
+ "structuralFailure": structural,
+ "unsupportedInterpolationClips": unsupported,
+ "errors": errors,
+ "correspondenceUsable": (
+ correspondence.get("usable") if isinstance(correspondence, Mapping) else None
+ ),
+ }
+
+ # A structural failure is a known-bad answer, not a missing one — it fails, never unevaluated.
+ if isinstance(structural, str) and structural.strip():
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ f"the GLB has a structural failure, so it has no usable skeleton of record: {structural}",
+ )
+ if unsupported:
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ f"{len(unsupported)} clip(s) use an interpolation outside "
+ f"{list(glb_rig_reference.SUPPORTED_INTERPOLATIONS)} "
+ f"({', '.join(str(name) for name in unsupported)}); a channel that cannot be evaluated "
+ f"addresses the skeleton no more usefully than one addressing the wrong skeleton",
+ )
+
+ if isinstance(correspondence, Mapping):
+ usable = correspondence.get("usable")
+ unmatched_bones = correspondence.get("unmatchedProceduralBones")
+ unmatched_bones = list(unmatched_bones) if isinstance(unmatched_bones, (list, tuple)) else []
+ unmatched_joints = correspondence.get("unmatchedGlbJoints")
+ unmatched_joints = (
+ list(unmatched_joints) if isinstance(unmatched_joints, (list, tuple)) else []
+ )
+ measured["unmatchedProceduralBones"] = unmatched_bones
+ measured["unmatchedGlbJoints"] = unmatched_joints
+ measured["correspondenceReason"] = correspondence.get("reason")
+ if usable is True:
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ "a procedural skeleton coexists and an explicit correspondence maps it to the GLB's "
+ "joints with nothing unmatched on either side: "
+ f"{correspondence.get('reason')}",
+ )
+ detail = ""
+ if unmatched_bones:
+ detail += f" unmatched procedural bones: {', '.join(str(b) for b in unmatched_bones)}."
+ if unmatched_joints:
+ named = ", ".join(
+ str(joint.get("name", joint.get("nodeName", joint)))
+ if isinstance(joint, Mapping)
+ else str(joint)
+ for joint in unmatched_joints
+ )
+ detail += f" unmatched GLB joints: {named}."
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ f"the procedural-to-GLB correspondence is not usable: "
+ f"{correspondence.get('reason')}.{detail} An unmatched joint on either side means the "
+ f"mapping was invented, and inventing it is what shreds a mesh",
+ )
+
+ if source == "glb":
+ problems: list[str] = []
+ if not ok:
+ problems.append(
+ "the GLB report is not ok"
+ + (f" ({'; '.join(str(e) for e in errors)})" if errors else "")
+ )
+ if primary_skin is None:
+ problems.append(
+ "the report names no primarySkin, so JOINTS_0 and the inverse binds have no "
+ "index space of record"
+ )
+ if problems:
+ return _verdict(spec, False, threshold, measured, "; ".join(problems))
+ return _verdict(
+ spec,
+ True,
+ threshold,
+ measured,
+ f"the rig came straight from the GLB (primary skin {primary_skin}), so the clip "
+ f"channels and skinIndex values address the file's own index spaces",
+ )
+
+ # Ambiguity 14: a procedural skeleton with no mapping is the defect, not absent input.
+ return _verdict(
+ spec,
+ False,
+ threshold,
+ measured,
+ f"rigReference declares source {source!r} and carries no `correspondence` block. A "
+ f"skeleton that is not the GLB's own needs an explicit mapping to it; without one the clip "
+ f"channels and skinIndex values address a different skeleton",
+ )
+
+
+# ---------------------------------------------------------------------------------------------
+# The runner
+# ---------------------------------------------------------------------------------------------
+
+
+def run_gates(
+ payload: Mapping[str, Any], sweep_coverage: SweepCoverage = DEFAULT_SWEEP_COVERAGE
+) -> GateReport:
+ """Run all ten R6 gates and return the report.
+
+ Nothing ships until all ten pass, and "pass" means `pass` -- an unevaluated gate makes
+ `GateReport.ok` False. Gates are independent: one failing never short-circuits another, because
+ a report that stops at the first failure hides the other nine answers a reader needs to decide
+ whether this is one bug or a broken harness.
+ """
+ if not isinstance(payload, Mapping):
+ raise TypeError(f"payload must be a mapping; got {type(payload).__name__}")
+
+ binding_verdict = _evaluate_binding(payload)
+ height = payload.get("figureHeight")
+
+ results = (
+ gate_g1(payload),
+ gate_g2(payload),
+ gate_g3(payload),
+ gate_g4(payload, binding_verdict),
+ gate_g5(payload, binding_verdict),
+ gate_g6(payload),
+ gate_g7(payload),
+ gate_g8(payload),
+ gate_g9(payload),
+ gate_g10(payload, sweep_coverage),
+ gate_g11(payload),
+ gate_g12(payload),
+ )
+ return GateReport(
+ results=results,
+ figure_height=float(height) if _finite(height) else None,
+ sweep_coverage=sweep_coverage,
+ )
+
+
+def main(argv: list[str]) -> int:
+ if len(argv) != 1 or argv[0] in {"-h", "--help"}:
+ print("usage: rig_gates.py <payload.json>", file=sys.stderr)
+ return 2
+ try:
+ raw = json.loads(Path(argv[0]).expanduser().read_text(encoding="utf-8"))
+ if not isinstance(raw, dict):
+ raise ValueError("payload root must be an object")
+ report = run_gates(raw)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ print(json.dumps(report.to_dict(), indent=2, ensure_ascii=False))
+ return 0 if report.ok else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage5_rig/skin_conditioning.py b/forge/stage5_rig/skin_conditioning.py
new file mode 100644
index 0000000..51eedf7
--- /dev/null
+++ b/forge/stage5_rig/skin_conditioning.py
@@ -0,0 +1,613 @@
+#!/usr/bin/env python3
+"""Stage R2 — skin conditioning by proximity weight blending.
+
+A character built from multiple overlapping parts tears open the moment it moves. Two vertices
+sitting on top of each other in bind pose but bound to DIFFERENT joints **must** separate as soon as
+those joints diverge; that is not a bug in the weights, it is what the weights say. This module is
+the fix: where two parts come within R of each other, every vertex is rebound to the weight field of
+its whole neighbourhood instead of to its own part alone, so neighbouring vertices travel together
+and the seam stops opening.
+
+ w_mixed = w_own + Sigma_q w_q * (1 - d_q/R)^2 q = every vertex within R, either part
+ w_final = renormalise( top4( w_mixed ) )
+
+The sum runs over the vertex's own binding AND every vertex within R of it, own part or foreign; the
+presence of at least one FOREIGN vertex within R is what decides whether a vertex is blended at all.
+That distinction matters and is not cosmetic: two coincident vertices then see exactly the same
+neighbourhood -- the sum for each contains the other with kernel weight (1 - 0/R)^2 = 1 -- so they
+come out with the same mixed field and the same reduced binding, which is precisely the tear this
+stage exists to close. Summing only over foreign neighbours would instead hand each vertex a weight
+field dominated by the OTHER part, and a symmetric seam would come out with the two parts' weights
+swapped rather than shared.
+
+THE TRADE, WHICH MUST BE STATED WHENEVER THIS STAGE RUNS
+--------------------------------------------------------
+Averaging two parts' bindings makes them travel together, which closes the hole, but it also pulls
+each vertex slightly off the path its own joints would take -- so creases get about 16% WORSE.
+Measured over a 176-frame sweep (11 clips x 4 times x 2 shoulders x 2 azimuths):
+
+ blend off background through splits 974 px in 30 blobs thin dark creases 31,316 px
+ blend R = 0.006H background through splits 287 px in 15 blobs thin dark creases 36,470 px
+
+This was accepted deliberately: **a hole shows the background, a crease shows skin.** A later stage
+must NOT "fix" the crease count by disabling the blend -- that trades a defect you can see through
+for a defect you can see, and the sweep above is the evidence, not an opinion.
+
+RESIDUAL, DOCUMENTED RATHER THAN HIDDEN
+---------------------------------------
+Creases are not eliminated by this method. Removing them entirely requires welding the parts into
+one continuous mesh with a single unified weight field, which changes the part structure and breaks
+per-part UI. That is a different topology contract, not a tuning of this one.
+
+WHAT DID NOT WORK
+-----------------
+Welding only exactly-coincident vertices (within 1e-4 H). It closed the neck-to-collarbone crack, but
+a sweep of 11 clips x 4 times x 3 azimuths = 132 frames still found cracks in 28 frames, 1,410 px of
+background showing through: adjacent parts mostly OVERLAP, they rarely share a rim, so coincidence
+welding finds almost nothing to weld. `weld_coincident` below is kept only so that negative result
+stays reproducible -- it is not part of the pipeline.
+
+Pure Python 3.10+ stdlib. No pip installs, no numpy.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+# R = 0.006H, `single-subject`: chosen against a control run on ONE figure, so it is a caller
+# overridable default and never a constant. The value actually used is recorded in the BlendReport.
+BLEND_RADIUS = 0.006
+WEIGHT_SUM_TOLERANCE = 2e-7
+MAX_INFLUENCES = 4
+# The rejected approach's tolerance, kept with the rejected approach.
+WELD_TOLERANCE = 1e-4
+# A reduction to top-4 always throws something away; this is the line above which the discarded mass
+# is worth counting. An 8-bit normalised weight buffer quantises to 1/255 ~= 3.9e-3, so anything
+# above a thousandth of the mixed mass can still survive quantisation and is a real loss. It is a
+# REPORTING threshold only -- nothing behaves differently on either side of it.
+DISCARD_REPORT_THRESHOLD = 1e-3
+# A gate failure list is for a human to read. Past this many the list stops being readable and the
+# count is the useful part.
+_MAX_REPORTED_FAILURES = 20
+
+TRADE_NOTE = (
+ "Proximity blending closes holes and makes creases ~16% worse (measured over 176 frames: "
+ "holes 974px/30 blobs -> 287px/15 blobs, creases 31,316px -> 36,470px). A hole shows the "
+ "background, a crease shows skin; the trade was accepted deliberately. Do not disable the "
+ "blend to bring the crease count back down."
+)
+RESIDUAL_NOTE = (
+ "Creases are not eliminated by this method. Removing them entirely needs one continuous mesh "
+ "with a unified weight field, which changes the part structure and breaks per-part UI."
+)
+
+# One cell per radius means the R-ball around any query point is covered by the 3x3x3 block of cells
+# centred on the point's own cell -- 27 buckets, whatever the vertex count.
+_CELL_OFFSETS: list[tuple[int, int, int]] = [
+ (dx, dy, dz) for dx in (-1, 0, 1) for dy in (-1, 0, 1) for dz in (-1, 0, 1)
+]
+
+
+@dataclass(frozen=True)
+class SkinBinding:
+ """A skinned vertex set: position, owning part, and 4 influences per vertex.
+
+ `skin_indices` and `skin_weights` are FLAT, four entries per vertex, matching the glTF accessor
+ layout the emitter writes -- so a binding can be round-tripped without a reshape that would have
+ to guess the stride.
+ """
+
+ positions: list[list[float]]
+ part_ids: list[Any]
+ skin_indices: list[int]
+ skin_weights: list[float]
+ joint_count: int
+
+ @property
+ def vertex_count(self) -> int:
+ return len(self.positions)
+
+ def influences(self, index: int) -> list[tuple[int, float]]:
+ base = index * MAX_INFLUENCES
+ return [
+ (self.skin_indices[base + slot], self.skin_weights[base + slot])
+ for slot in range(MAX_INFLUENCES)
+ ]
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "positions": [list(p) for p in self.positions],
+ "partIds": list(self.part_ids),
+ "skinIndices": list(self.skin_indices),
+ "skinWeights": list(self.skin_weights),
+ "jointCount": self.joint_count,
+ }
+
+ @staticmethod
+ def from_dict(payload: dict[str, Any]) -> "SkinBinding":
+ try:
+ return SkinBinding(
+ positions=[[float(c) for c in point] for point in payload["positions"]],
+ part_ids=list(payload["partIds"]),
+ skin_indices=[int(i) for i in payload["skinIndices"]],
+ skin_weights=[float(w) for w in payload["skinWeights"]],
+ joint_count=int(payload["jointCount"]),
+ )
+ except KeyError as exc:
+ raise ValueError(f"binding payload is missing {exc.args[0]!r}") from exc
+
+
+@dataclass(frozen=True)
+class BlendReport:
+ """What the blend actually did, including what it threw away."""
+
+ vertices_total: int
+ vertices_touched: int
+ vertices_interior: int
+ vertices_without_weight: int
+ figure_height: float
+ radius_fraction: float
+ radius_world: float
+ max_influences_seen: int
+ lossy_reductions: int
+ max_discarded_fraction: float
+ discard_threshold: float
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "verticesTotal": self.vertices_total,
+ "verticesTouched": self.vertices_touched,
+ "verticesInterior": self.vertices_interior,
+ "verticesWithoutWeight": self.vertices_without_weight,
+ "figureHeight": self.figure_height,
+ "radiusFraction": self.radius_fraction,
+ "radiusWorld": self.radius_world,
+ "maxInfluencesSeen": self.max_influences_seen,
+ "lossyReductions": self.lossy_reductions,
+ "maxDiscardedFraction": self.max_discarded_fraction,
+ "discardThreshold": self.discard_threshold,
+ "trade": TRADE_NOTE,
+ "residual": RESIDUAL_NOTE,
+ }
+
+
+class UniformGrid:
+ """A uniform spatial hash at exactly ONE CELL PER QUERY RADIUS.
+
+ Sizing the cell to the radius is the whole point: the R-ball around a query point cannot reach
+ past the 3x3x3 block of cells around it, so a query touches at most 27 buckets no matter how many
+ vertices exist. Brute force is O(n^2) and unusable past ~50k vertices; a smaller cell would make
+ the neighbourhood span more than 27 buckets and a larger one would drag in vertices that have to
+ be distance-tested and thrown away.
+ """
+
+ def __init__(self, positions: list[list[float]], cell_size: float):
+ if cell_size <= 0.0:
+ raise ValueError("cell_size must be positive")
+ self.cell_size = cell_size
+ self.buckets: dict[tuple[int, int, int], list[int]] = {}
+ self.buckets_visited = 0
+ self.max_buckets_per_query = 0
+ for index, point in enumerate(positions):
+ self.buckets.setdefault(self.cell_of(point), []).append(index)
+ self._positions = positions
+
+ def cell_of(self, point: list[float]) -> tuple[int, int, int]:
+ size = self.cell_size
+ return (
+ math.floor(point[0] / size),
+ math.floor(point[1] / size),
+ math.floor(point[2] / size),
+ )
+
+ def query(self, point: list[float], radius: float) -> list[tuple[int, float]]:
+ """Every vertex within `radius` of `point`, as (vertex index, distance).
+
+ `radius` may not exceed the cell size; a larger radius would need more than the 27 buckets
+ this walks and would silently miss neighbours instead of being slow, which is the worse
+ failure of the two.
+ """
+ if radius > self.cell_size:
+ raise ValueError(
+ f"radius {radius} exceeds cell size {self.cell_size}; the 27-bucket walk would "
+ "miss neighbours. Build the grid at one cell per radius."
+ )
+ x, y, z = self.cell_of(point)
+ found: list[tuple[int, float]] = []
+ visited = 0
+ for dx, dy, dz in _CELL_OFFSETS:
+ visited += 1
+ for index in self.buckets.get((x + dx, y + dy, z + dz), ()):
+ distance = math.dist(point, self._positions[index])
+ if distance <= radius:
+ found.append((index, distance))
+ self.buckets_visited += visited
+ self.max_buckets_per_query = max(self.max_buckets_per_query, visited)
+ return found
+
+
+def brute_force_query(
+ positions: list[list[float]], point: list[float], radius: float
+) -> list[tuple[int, float]]:
+ """The O(n^2) neighbour search the grid replaces, kept so the grid can be CHECKED against it.
+
+ Without it "the grid finds the same neighbours" is an assertion; with it a test can compare the
+ two on a small fixture and see that it is true.
+ """
+ found = []
+ for index, other in enumerate(positions):
+ distance = math.dist(point, other)
+ if distance <= radius:
+ found.append((index, distance))
+ return found
+
+
+def _check_shape(binding: SkinBinding) -> None:
+ count = binding.vertex_count
+ if count == 0:
+ raise ValueError("binding has no vertices")
+ if len(binding.part_ids) != count:
+ raise ValueError(
+ f"part_ids has {len(binding.part_ids)} entries for {count} vertices; one per vertex"
+ )
+ if len(binding.skin_indices) != count * MAX_INFLUENCES:
+ raise ValueError(
+ f"skin_indices has {len(binding.skin_indices)} entries; expected "
+ f"{count * MAX_INFLUENCES} ({MAX_INFLUENCES} per vertex, flat)"
+ )
+ if len(binding.skin_weights) != count * MAX_INFLUENCES:
+ raise ValueError(
+ f"skin_weights has {len(binding.skin_weights)} entries; expected "
+ f"{count * MAX_INFLUENCES} ({MAX_INFLUENCES} per vertex, flat)"
+ )
+ if binding.joint_count < 1:
+ raise ValueError("joint_count must be at least 1")
+
+
+def _dense_field(
+ binding: SkinBinding, neighbours: list[tuple[int, float]], radius: float
+) -> dict[int, float]:
+ """Expand the neighbourhood's 4-slot bindings into a DENSE vector over all joints.
+
+ Mixing the sparse 4-slot rows directly -- adding a neighbour's weight only where its joint
+ already occupies one of this vertex's four slots -- silently drops every influence that does not
+ already fit, which is most of them at a seam where two parts reference different joints. The
+ expansion is what makes the mix see all of them; the reduction back to 4 then happens ONCE, on
+ the finished field, where it can pick the four largest rather than the four that happened to be
+ there first.
+
+ Terms are summed with `math.fsum`, not `+=`: fsum is correctly rounded and therefore
+ order-independent, so the field does not depend on the order the grid handed the neighbours back.
+ """
+ terms: dict[int, list[float]] = {}
+ for index, distance in neighbours:
+ kernel = (1.0 - distance / radius) ** 2
+ base = index * MAX_INFLUENCES
+ for slot in range(MAX_INFLUENCES):
+ weight = binding.skin_weights[base + slot]
+ if weight <= 0.0:
+ # A zero-weight slot carries no influence; recording its joint would inflate the
+ # influence count with joints that do not actually move the vertex.
+ continue
+ terms.setdefault(binding.skin_indices[base + slot], []).append(weight * kernel)
+ return {joint: math.fsum(values) for joint, values in terms.items()}
+
+
+def _reduce(dense: dict[int, float]) -> tuple[list[int], list[float], float]:
+ """Keep the four largest influences and renormalise. Returns (indices, weights, discarded)."""
+ # Ties broken by joint index so the result is a function of the field alone.
+ ordered = sorted(dense.items(), key=lambda item: (-item[1], item[0]))
+ kept = ordered[:MAX_INFLUENCES]
+ total = math.fsum(weight for _, weight in dense.items())
+ kept_total = math.fsum(weight for _, weight in kept)
+ if kept_total <= 0.0:
+ return [0] * MAX_INFLUENCES, [0.0] * MAX_INFLUENCES, 0.0
+ indices = [0] * MAX_INFLUENCES
+ weights = [0.0] * MAX_INFLUENCES
+ for slot, (joint, weight) in enumerate(kept):
+ indices[slot] = joint
+ weights[slot] = weight / kept_total
+ # Put the rounding residual on the dominant slot. Four divisions do not have to sum to exactly
+ # 1.0 in float, and Gate R2 is |1 - sum(w)| <= 2e-7 -- close enough to the tolerance to be worth
+ # removing at the source rather than hoping.
+ weights[0] += 1.0 - math.fsum(weights)
+ discarded = (total - kept_total) / total if total > 0.0 else 0.0
+ return indices, weights, discarded
+
+
+def blend_weights(
+ binding: SkinBinding,
+ figure_height: float,
+ radius: float = BLEND_RADIUS,
+) -> tuple[SkinBinding, BlendReport]:
+ """Proximity weight blending. Returns a NEW binding and a report; the input is never mutated.
+
+ `radius` is a FRACTION of figure height H, so the same value works at any scale; the world-space
+ radius actually used is `radius * figure_height` and is recorded in the report.
+
+ A vertex with no vertex from another part within R is INTERIOR and keeps its source binding
+ exactly -- the same indices and the same float weights, not a recomputed approximation of them.
+ Interior vertices are the overwhelming majority, and re-deriving them would introduce a
+ difference the whole model would carry for no reason.
+
+ Every result is buffered and committed after all reads finish. Reading a partly blended field
+ would make each vertex depend on the ones visited before it, which makes the output a function of
+ the vertex ORDER rather than of the geometry -- reproducible only by accident.
+ """
+ _check_shape(binding)
+ if figure_height <= 0.0:
+ raise ValueError("figure_height must be positive")
+ if radius <= 0.0:
+ raise ValueError("radius must be positive")
+
+ world_radius = radius * figure_height
+ grid = UniformGrid(binding.positions, world_radius)
+
+ # WRITE AFTER ALL READS: nothing below assigns into the output arrays.
+ pending: dict[int, tuple[list[int], list[float]]] = {}
+ touched = 0
+ interior = 0
+ without_weight = 0
+ max_influences_seen = 0
+ lossy = 0
+ max_discarded = 0.0
+
+ for index in range(binding.vertex_count):
+ neighbours = grid.query(binding.positions[index], world_radius)
+ own_part = binding.part_ids[index]
+ if not any(binding.part_ids[other] != own_part for other, _ in neighbours):
+ interior += 1
+ continue
+ dense = _dense_field(binding, neighbours, world_radius)
+ max_influences_seen = max(max_influences_seen, len(dense))
+ if not dense or math.fsum(dense.values()) <= 0.0:
+ # Every influence in the neighbourhood is zero, so there is no field to blend. Keeping
+ # the source binding is the only answer that does not invent one.
+ without_weight += 1
+ continue
+ indices, weights, discarded = _reduce(dense)
+ max_discarded = max(max_discarded, discarded)
+ if discarded > DISCARD_REPORT_THRESHOLD:
+ lossy += 1
+ pending[index] = (indices, weights)
+ touched += 1
+
+ out_indices: list[int] = []
+ out_weights: list[float] = []
+ for index in range(binding.vertex_count):
+ base = index * MAX_INFLUENCES
+ result = pending.get(index)
+ if result is None:
+ out_indices.extend(binding.skin_indices[base : base + MAX_INFLUENCES])
+ out_weights.extend(binding.skin_weights[base : base + MAX_INFLUENCES])
+ continue
+ out_indices.extend(result[0])
+ out_weights.extend(result[1])
+
+ blended = SkinBinding(
+ positions=[list(point) for point in binding.positions],
+ part_ids=list(binding.part_ids),
+ skin_indices=out_indices,
+ skin_weights=out_weights,
+ joint_count=binding.joint_count,
+ )
+ report = BlendReport(
+ vertices_total=binding.vertex_count,
+ vertices_touched=touched,
+ vertices_interior=interior,
+ vertices_without_weight=without_weight,
+ figure_height=figure_height,
+ radius_fraction=radius,
+ radius_world=world_radius,
+ max_influences_seen=max_influences_seen,
+ lossy_reductions=lossy,
+ max_discarded_fraction=max_discarded,
+ discard_threshold=DISCARD_REPORT_THRESHOLD,
+ )
+ return blended, report
+
+
+def weld_coincident(
+ binding: SkinBinding,
+ figure_height: float,
+ tolerance: float = WELD_TOLERANCE,
+) -> tuple[SkinBinding, int]:
+ """THE REJECTED APPROACH, kept so its failure stays measurable. Do not ship this.
+
+ Averages the bindings of vertices lying within `tolerance` * H of each other. It closed one
+ visible crack and left 28 of 132 swept frames still cracked, because adjacent parts mostly
+ OVERLAP rather than share a rim -- so on a real seam there is usually nothing within 1e-4 H to
+ weld and the pass is a no-op. `blend_weights` is what replaced it.
+
+ Returns the welded binding and the number of groups that actually spanned more than one part.
+ """
+ _check_shape(binding)
+ if figure_height <= 0.0:
+ raise ValueError("figure_height must be positive")
+ world_tolerance = tolerance * figure_height
+ grid = UniformGrid(binding.positions, world_tolerance)
+
+ parent = list(range(binding.vertex_count))
+
+ def find(node: int) -> int:
+ while parent[node] != node:
+ parent[node] = parent[parent[node]]
+ node = parent[node]
+ return node
+
+ for index in range(binding.vertex_count):
+ for other, _ in grid.query(binding.positions[index], world_tolerance):
+ a, b = find(index), find(other)
+ if a != b:
+ parent[max(a, b)] = min(a, b)
+
+ groups: dict[int, list[int]] = {}
+ for index in range(binding.vertex_count):
+ groups.setdefault(find(index), []).append(index)
+
+ pending: dict[int, tuple[list[int], list[float]]] = {}
+ welded_groups = 0
+ for members in groups.values():
+ if len(members) < 2:
+ continue
+ if len({binding.part_ids[member] for member in members}) < 2:
+ continue
+ welded_groups += 1
+ dense = _dense_field(binding, [(member, 0.0) for member in members], world_tolerance)
+ indices, weights, _ = _reduce(dense)
+ for member in members:
+ pending[member] = (indices, weights)
+
+ out_indices: list[int] = []
+ out_weights: list[float] = []
+ for index in range(binding.vertex_count):
+ base = index * MAX_INFLUENCES
+ result = pending.get(index)
+ if result is None:
+ out_indices.extend(binding.skin_indices[base : base + MAX_INFLUENCES])
+ out_weights.extend(binding.skin_weights[base : base + MAX_INFLUENCES])
+ continue
+ out_indices.extend(result[0])
+ out_weights.extend(result[1])
+
+ return (
+ SkinBinding(
+ positions=[list(point) for point in binding.positions],
+ part_ids=list(binding.part_ids),
+ skin_indices=out_indices,
+ skin_weights=out_weights,
+ joint_count=binding.joint_count,
+ ),
+ welded_groups,
+ )
+
+
+def validate_binding(binding: SkinBinding) -> list[str]:
+ """Gate R2. Returns human-readable failures; an empty list is a pass.
+
+ |1 - sum(w)| <= 2e-7 for every vertex
+ maxSkinIndex <= joint_count - 1
+
+ Both exist because of what they catch, not for tidiness: a weight sum off by a percent inflates
+ or shrinks a limb every frame it is posed, and a single out-of-range index reads a garbage matrix
+ and sends one vertex to infinity. The index check is here rather than only at bind time because
+ the reduction to top-4 rewrites the indices, so being in range before it says nothing.
+ """
+ failures: list[str] = []
+
+ count = binding.vertex_count
+ if count == 0:
+ return ["binding has no vertices"]
+ if len(binding.part_ids) != count:
+ failures.append(
+ f"part_ids has {len(binding.part_ids)} entries for {count} vertices; expected one each"
+ )
+ if len(binding.skin_indices) != count * MAX_INFLUENCES:
+ failures.append(
+ f"skin_indices has {len(binding.skin_indices)} entries; expected "
+ f"{count * MAX_INFLUENCES}"
+ )
+ if len(binding.skin_weights) != count * MAX_INFLUENCES:
+ failures.append(
+ f"skin_weights has {len(binding.skin_weights)} entries; expected "
+ f"{count * MAX_INFLUENCES}"
+ )
+ if binding.joint_count < 1:
+ failures.append(f"joint_count is {binding.joint_count}; expected at least 1")
+ if failures:
+ # The per-vertex checks below index into these arrays; running them on a malformed binding
+ # would report an exception instead of the shape problem that caused it.
+ return failures
+
+ sum_failures = 0
+ range_failures = 0
+ worst_sum_error = 0.0
+ max_index = 0
+ for index in range(count):
+ base = index * MAX_INFLUENCES
+ weights = binding.skin_weights[base : base + MAX_INFLUENCES]
+ error = abs(1.0 - math.fsum(weights))
+ if not (error <= WEIGHT_SUM_TOLERANCE): # not(<=) also catches NaN
+ sum_failures += 1
+ worst_sum_error = max(worst_sum_error, error if error == error else float("inf"))
+ if len(failures) < _MAX_REPORTED_FAILURES:
+ failures.append(
+ f"vertex {index}: |1 - sum(w)| = {error:.3e} exceeds {WEIGHT_SUM_TOLERANCE:.1e} "
+ f"(weights {weights})"
+ )
+ for slot in range(MAX_INFLUENCES):
+ joint = binding.skin_indices[base + slot]
+ max_index = max(max_index, joint)
+ if joint < 0 or joint > binding.joint_count - 1:
+ range_failures += 1
+ if len(failures) < _MAX_REPORTED_FAILURES:
+ failures.append(
+ f"vertex {index} slot {slot}: skin index {joint} outside "
+ f"[0, {binding.joint_count - 1}]"
+ )
+
+ if sum_failures + range_failures > len(failures):
+ failures.append(
+ f"... {sum_failures} weight-sum failures (worst {worst_sum_error:.3e}) and "
+ f"{range_failures} index-range failures in total; maxSkinIndex = {max_index}, "
+ f"joint_count = {binding.joint_count}"
+ )
+ return failures
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(
+ description="Stage R2: blend skin weights across part seams by proximity."
+ )
+ parser.add_argument("binding", type=Path, help="JSON binding payload")
+ parser.add_argument(
+ "--radius",
+ type=float,
+ default=None,
+ help=f"blend radius as a fraction of figure height (default {BLEND_RADIUS}, single-subject)",
+ )
+ parser.add_argument(
+ "--figure-height",
+ type=float,
+ default=None,
+ help="figure height H, if the payload does not carry `figureHeight`",
+ )
+ parser.add_argument("--out", type=Path, help="also write the result here")
+ args = parser.parse_args(argv)
+
+ try:
+ payload = json.loads(args.binding.read_text())
+ source = SkinBinding.from_dict(payload)
+ height = args.figure_height if args.figure_height is not None else payload.get("figureHeight")
+ if height is None:
+ raise ValueError("no figure height: pass --figure-height or add `figureHeight`")
+ radius = args.radius
+ if radius is None:
+ radius = float(payload.get("blendRadius", BLEND_RADIUS))
+ blended, report = blend_weights(source, float(height), radius)
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+ failures = validate_binding(blended)
+ result = {
+ "schemaVersion": 1,
+ "kind": "blended-skin-binding",
+ "binding": blended.to_dict(),
+ "report": report.to_dict(),
+ "gateR2": {"passed": not failures, "failures": failures},
+ }
+ if args.out:
+ args.out.write_text(json.dumps(result))
+ print(json.dumps(result, indent=2))
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/state.py b/forge/state.py
index 93496c8..e875231 100644
--- a/forge/state.py
+++ b/forge/state.py
@@ -26,7 +26,11 @@ def build_parser() -> argparse.ArgumentParser:
init = commands.add_parser("init")
init.add_argument("--state", type=Path, default=Path(".img2threejs/state.json"))
init.add_argument("--reference", required=True)
- init.add_argument("--profile", choices=("generic", "cs2", "character"), default="generic")
+ init.add_argument(
+ "--profile",
+ choices=("generic", "cs2", "character", "animated-character"),
+ default="generic",
+ )
init.add_argument("--spec", default="")
init.add_argument("--max-per-pass", type=int, default=3)
init.add_argument("--max-total", type=int, default=6)
diff --git a/forge/tests/test_action_design.py b/forge/tests/test_action_design.py
new file mode 100644
index 0000000..b495c12
--- /dev/null
+++ b/forge/tests/test_action_design.py
@@ -0,0 +1,757 @@
+#!/usr/bin/env python3
+"""Tests for Stage R4 action design, built around the round trip that is the whole point.
+
+`test_walk_round_trip_classifier_independently_reports_walk` and its run counterpart are the
+argument for this module. §R4 says a designed clip is accepted only when "the classifier from
+§2 must agree the clip is what it claims to be", so the test derives gait parameters from
+`walk_targets`, authors tracks from them, measures those tracks with §1, and asks §2 what it
+just looked at — without ever telling it. Then it raises the speed per the spec's run recipe
+and asks again, and the answer has to change on its own. Anything less is a test that the
+authoring code returns the number the authoring code put in.
+
+Falls back to a local §1/§2 implementation when `clip_features.py` is not importable, so this
+suite is self-contained. `test_the_fallback_classifier_matches_the_spec_validation_table`
+pins that fallback to the spec's own published measurements rather than to what it happens to
+compute, because a fallback nothing checks is a second bug waiting to agree with the first.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage5_rig"))
+
+from action_design import ( # noqa: E402
+ FOOT_SLIDE_LIMIT,
+ POSE_RETURN_DEGREES,
+ ChainResolutionError,
+ JointNode,
+ PRIMITIVES,
+ accepts,
+ band_features,
+ build_payload,
+ check_medial_lateral,
+ classifier_verdict,
+ default_classifier,
+ default_measure,
+ foot_slide,
+ gait_parameters,
+ hip_relative_clip,
+ resolve_chains,
+ run_targets,
+ synthesise_gait_tracks,
+ walk_targets,
+)
+
+MODULE = ROOT / "stage5_rig" / "action_design.py"
+
+
+# ---------------------------------------------------------------------------------------------
+# §1 / §2 fallback — used only when clip_features.py is absent.
+#
+# This is a deliberate, minimal transcription of the spec's own tables, kept in the TEST so the
+# suite is self-contained while `clip_features.py` (owned by another author) lands. It is NOT a
+# second implementation for production use: action_design imports the real one and this file
+# prefers it whenever it is importable.
+# ---------------------------------------------------------------------------------------------
+
+
+class _FallbackFeatures:
+ """§1's feature vector, normalised by H exactly as `clip_features.measure_clip` does."""
+
+ def __init__(self, clip, figure_height):
+ height = float(figure_height)
+ positions = clip["landmarkPositions"]
+ hip = positions["hip"]
+ start = hip[0]
+ self.duration = float(clip["duration"])
+ self.travel = max(math.hypot(p[0] - start[0], p[2] - start[2]) for p in hip) / height
+ self.rise = (max(p[1] for p in hip) - min(p[1] for p in hip)) / height
+ self.speed = self.travel / self.duration
+ self.landmark_ranges = {
+ name: tuple((max(p[axis] for p in track) - min(p[axis] for p in track)) / height for axis in range(3))
+ for name, track in positions.items()
+ }
+ self.hand_range = self._pooled(positions, ("hand.l", "hand.r"), height)
+ self.foot_range = self._pooled(positions, ("foot.l", "foot.r"), height)
+ self.head_rise = self.landmark_ranges["head"][1]
+ self.scale_delta = max(clip["jointScaleDelta"]) if clip["jointScaleDelta"] else 0.0
+ self.pose_return = clip.get("poseReturn")
+
+ @staticmethod
+ def _pooled(positions, names, height):
+ pooled = [p for name in names for p in positions[name]]
+ return max((max(p[axis] for p in pooled) - min(p[axis] for p in pooled)) for axis in range(3)) / height
+
+
+def _fallback_measure(clip, figure_height):
+ return _FallbackFeatures(clip, figure_height)
+
+
+def _fallback_classify(features):
+ """§2's threshold table, verbatim. Returns every matching label plus a primary class."""
+ labels = []
+ if features.travel < 0.02 and features.rise < 0.02:
+ labels.append("idle")
+ in_place = features.travel < 0.30
+ if in_place:
+ labels.append("in-place")
+ if 0.30 <= features.speed < 0.60:
+ labels.append("walk")
+ if 0.60 <= features.speed < 1.50:
+ labels.append("run")
+ if features.speed >= 1.50:
+ labels.append("dash")
+ if features.rise >= 0.15 and features.travel < 0.50:
+ labels.append("jump")
+ if features.rise >= 0.15 and features.travel >= 0.50:
+ labels.append("leap")
+ if features.foot_range < 0.10:
+ labels.append("planted")
+ if in_place and features.hand_range >= 0.40:
+ labels.append("gesture")
+ precedence = ("dash", "run", "walk", "leap", "jump", "idle", "in-place")
+ primary = next((label for label in precedence if label in labels), None)
+ return primary, tuple(labels)
+
+
+MEASURE = default_measure() or _fallback_measure
+CLASSIFY = default_classifier() or _fallback_classify
+USING_REAL_CLIP_FEATURES = default_measure() is not None
+
+
+def measure(clip, figure_height):
+ return MEASURE(clip, figure_height)
+
+
+def classify(features):
+ return CLASSIFY(features)
+
+
+# ---------------------------------------------------------------------------------------------
+# Synthetic humanoid hierarchy with DELIBERATELY UNINFORMATIVE joint names.
+#
+# Every joint is `node_NN`, in an order that does not follow the body. If `resolve_chains` can
+# still find the arms, the legs and the spine, it found them from the shape of the graph, which
+# is what §R4 ("Resolve from topology") and Stage R0 ("Do not infer from names") require.
+# ---------------------------------------------------------------------------------------------
+
+HUMANOID = [
+ JointNode("node_00", None, (0.0, 0.50, 0.0)), # root
+ JointNode("node_17", "node_00", (0.0, 0.00, 0.0)), # pelvis: the first branch
+ JointNode("node_04", "node_17", (0.0, 0.10, 0.0)), # lower spine (medial)
+ JointNode("node_29", "node_17", (0.09, -0.02, 0.0)), # +X thigh
+ JointNode("node_08", "node_17", (-0.09, -0.02, 0.0)), # -X thigh
+ JointNode("node_31", "node_29", (0.0, -0.22, 0.0)),
+ JointNode("node_02", "node_31", (0.0, -0.22, 0.02)), # +X foot leaf
+ JointNode("node_11", "node_08", (0.0, -0.22, 0.0)),
+ JointNode("node_23", "node_11", (0.0, -0.22, 0.02)), # -X foot leaf
+ JointNode("node_19", "node_04", (0.0, 0.14, 0.0)), # chest: the second branch
+ JointNode("node_06", "node_19", (0.0, 0.10, 0.0)), # neck (medial)
+ JointNode("node_21", "node_06", (0.0, 0.10, 0.0)), # head leaf
+ JointNode("node_13", "node_19", (0.05, 0.06, 0.0)), # +X clavicle
+ JointNode("node_27", "node_19", (-0.05, 0.06, 0.0)), # -X clavicle
+ JointNode("node_09", "node_13", (0.10, 0.0, 0.0)),
+ JointNode("node_15", "node_09", (0.24, 0.0, 0.0)),
+ JointNode("node_03", "node_15", (0.22, 0.0, 0.0)), # +X hand leaf
+ JointNode("node_25", "node_27", (-0.10, 0.0, 0.0)),
+ JointNode("node_12", "node_25", (-0.24, 0.0, 0.0)),
+ JointNode("node_07", "node_12", (-0.22, 0.0, 0.0)), # -X hand leaf
+]
+
+# The side claim, as it would come off the source rig's own naming. Deliberately kept apart from
+# the geometry: this is what a mirrored rig gets wrong, and comparing it against the geometry is
+# the entire content of the medial/lateral gate.
+TRUE_SIDE_LABELS = {"node_13": "l", "node_27": "r", "node_29": "l", "node_08": "r"}
+
+
+def mirrored_humanoid():
+ """The same rig with every X negated — a mirrored build, plausible from every angle."""
+ return [
+ JointNode(node.id, node.parent, (-node.local_position[0], node.local_position[1], node.local_position[2]))
+ for node in HUMANOID
+ ]
+
+
+H = 1.0
+
+
+def authored(band, figure_height=H, source_name="authored"):
+ """targets -> gait parameters -> authored clip, the first two arrows of §R4's loop."""
+ params = gait_parameters(band, figure_height)
+ return params, synthesise_gait_tracks(params, source_name=source_name)
+
+
+class WalkRunRoundTrip(unittest.TestCase):
+ """§R4's loop, run end to end: target features -> author -> measure -> compare."""
+
+ def test_walk_round_trip_classifier_independently_reports_walk(self) -> None:
+ band = walk_targets(H)
+ params, clip = authored(band, source_name="authored-walk")
+
+ features = measure(clip, H)
+ primary, labels = classifier_verdict(classify(features))
+ print(
+ f"\n[walk round trip] speed={features.speed:.4f} travel={features.travel:.4f} "
+ f"rise={features.rise:.4f} -> {primary!r} {list(labels)}"
+ )
+
+ self.assertEqual(
+ primary,
+ "walk",
+ f"§2 was handed the authored clip's measurements with no hint and reported {primary!r} "
+ f"(labels {list(labels)}); §R4 requires it to agree the clip is a walk",
+ )
+ self.assertNotIn("run", labels)
+ self.assertNotIn("idle", labels)
+ self.assertNotIn("planted", labels, "a walk whose feet read as planted is not a walk")
+
+ check = band.contains(band_features(clip, H, measure=measure))
+ self.assertTrue(check.ok, f"authored walk fell outside its own target band: {check.summary()}")
+ self.assertEqual(check.unevaluated, (), check.summary())
+
+ def test_run_recipe_makes_the_classifier_say_run_not_walk(self) -> None:
+ """§R4: "The classifier must then report `run`, not `walk`, without being told."""
+ walk_band, run_band = walk_targets(H), run_targets(H)
+
+ # The spec's run recipe: three changes and nothing else.
+ self.assertGreater(run_band.target("speed"), walk_band.target("speed"))
+ self.assertLess(run_band.target("contact"), 0.5)
+ self.assertGreater(run_band.target("handRange"), walk_band.target("handRange"))
+
+ params, clip = authored(run_band, source_name="authored-run")
+ self.assertGreater(params.flight_fraction, 0.0, "contact below 0.5 must produce a flight phase")
+ self.assertEqual(params.double_support_fraction, 0.0)
+
+ features = measure(clip, H)
+ primary, labels = classifier_verdict(classify(features))
+ print(f"\n[run round trip] speed={features.speed:.4f} -> {primary!r} {list(labels)}")
+
+ self.assertEqual(primary, "run", f"§2 reported {primary!r} (labels {list(labels)}), expected run")
+ self.assertNotIn(
+ "walk",
+ labels,
+ "raising the speed per the run recipe must move the clip out of the walk band entirely, "
+ "not merely add a run label alongside it",
+ )
+
+ check = run_band.contains(band_features(clip, H, measure=measure))
+ self.assertTrue(check.ok, f"authored run fell outside its own target band: {check.summary()}")
+
+ def test_walk_and_run_do_not_share_a_classification(self) -> None:
+ """The two authored clips must land in different classes, from the same code path."""
+ _, walk_clip = authored(walk_targets(H))
+ _, run_clip = authored(run_targets(H))
+ walk_primary, _ = classifier_verdict(classify(measure(walk_clip, H)))
+ run_primary, _ = classifier_verdict(classify(measure(run_clip, H)))
+ self.assertNotEqual(walk_primary, run_primary)
+ self.assertEqual((walk_primary, run_primary), ("walk", "run"))
+
+
+class FootContact(unittest.TestCase):
+ def test_a_stance_foot_that_drifts_fails_the_gate_and_a_planted_one_passes(self) -> None:
+ """§R4's most valuable gate, shown failing and passing on the same gait.
+
+ The drifting version is a legitimate-looking animation: the foot is in the right place
+ at every keyframe, the timing is unchanged, and the only thing wrong with it is that
+ the contact constraint is not enforced. That is exactly the defect that "reads as
+ 'floaty' or 'skating' to every viewer while being hard to name by eye".
+ """
+ params, clip = authored(walk_targets(H))
+ report = foot_slide(clip["landmarkPositions"], clip["sampleTimes"], clip["stance"], H)
+ print(f"\n[footSlide, contact enforced] {report.status}: {report.reason}")
+ self.assertEqual(report.status, "pass")
+ self.assertEqual(report.max_slide_fraction, 0.0, "an enforced contact constraint means exactly zero slide")
+ self.assertGreater(len(report.per_stance), 0)
+
+ drifted = json.loads(json.dumps(clip))
+ stance_end = params.contact_fraction * params.duration
+ moved = 0
+ for index, t in enumerate(drifted["sampleTimes"]):
+ if t <= stance_end + 1e-9:
+ drifted["landmarkPositions"]["foot.l"][index][2] += 0.05 * H * (t / stance_end if stance_end else 0.0)
+ moved += 1
+ self.assertGreater(moved, 1, "the drift has to touch at least two stance frames to be measurable")
+
+ drifted_report = foot_slide(
+ drifted["landmarkPositions"], drifted["sampleTimes"], drifted["stance"], H
+ )
+ print(f"[footSlide, 0.05H drift] {drifted_report.status}: {drifted_report.reason}")
+ self.assertEqual(drifted_report.status, "fail")
+ self.assertGreater(drifted_report.max_slide_fraction, FOOT_SLIDE_LIMIT)
+ self.assertAlmostEqual(drifted_report.max_slide_fraction, 0.05, places=9)
+ self.assertEqual(drifted_report.worst.landmark, "foot.l")
+
+ def test_no_stance_data_is_unevaluated_not_a_pass(self) -> None:
+ _, clip = authored(walk_targets(H))
+ report = foot_slide(clip["landmarkPositions"], clip["sampleTimes"], {}, H)
+ self.assertEqual(report.status, "unevaluated")
+ self.assertFalse(report.ok)
+ self.assertIsNone(report.max_slide_fraction)
+ self.assertIn("stance", report.reason)
+
+
+class MedialLateralGate(unittest.TestCase):
+ def test_catches_a_mirrored_rig(self) -> None:
+ """`leftAnchor.x > 0 > rightAnchor.x`, on a rig where it does not hold.
+
+ The mirrored rig is built by negating every X. Nothing about it looks wrong: the
+ proportions are identical, both arms swing, and it animates cleanly. The only visible
+ symptom is that every left-hand action plays on the right.
+ """
+ good = resolve_chains(HUMANOID, side_labels=TRUE_SIDE_LABELS)
+ self.assertTrue(good.gate_is_independent, "with side_labels the gate must be able to fail")
+ self.assertEqual(check_medial_lateral(good), [], "the correctly built rig must pass cleanly")
+
+ mirrored = resolve_chains(mirrored_humanoid(), side_labels=TRUE_SIDE_LABELS)
+ errors = check_medial_lateral(mirrored)
+ print("\n[medial/lateral] " + "\n ".join(errors))
+ self.assertTrue(errors, "a mirrored rig must be rejected")
+
+ self.assertLess(
+ mirrored.arm["l"].anchor_position[0], 0.0, "precondition: the mirrored rig's left anchor is at negative x"
+ )
+ self.assertTrue(any("arm.l" in message and "expected x > 0" in message for message in errors), errors)
+ self.assertTrue(any("arm.r" in message and "expected x < 0" in message for message in errors), errors)
+ self.assertTrue(any("leg.l" in message for message in errors), errors)
+
+ def test_without_side_labels_the_gate_reports_that_it_cannot_fail(self) -> None:
+ """A pass that could not have been a fail is not evidence, and says so."""
+ mirrored = resolve_chains(mirrored_humanoid())
+ self.assertEqual(mirrored.side_source, "model-x")
+ self.assertFalse(mirrored.gate_is_independent)
+ self.assertEqual(check_medial_lateral(mirrored), [])
+ self.assertTrue(any("gate_is_independent is False" in note for note in mirrored.notes), mirrored.notes)
+
+ def test_medial_axis_check_is_opt_in_and_catches_an_off_midline_spine(self) -> None:
+ chains = resolve_chains(HUMANOID, side_labels=TRUE_SIDE_LABELS)
+ # Shift the NECK only, so the head leaves the midline while both lateral pairs stay
+ # exactly where they were. A whole-rig shift would move the arm anchors too, and the
+ # lateral half of the gate would fire instead of the medial half under test.
+ offset = [
+ JointNode(
+ n.id,
+ n.parent,
+ (n.local_position[0] + (0.3 if n.id == "node_06" else 0.0), n.local_position[1], n.local_position[2]),
+ )
+ for n in HUMANOID
+ ]
+ shifted = resolve_chains(offset, side_labels=TRUE_SIDE_LABELS)
+ self.assertEqual(check_medial_lateral(chains, medial_tolerance=0.02 * H), [])
+ self.assertEqual(check_medial_lateral(shifted), [], "off by default: no absolute tolerance is defensible")
+ self.assertTrue(any("MEDIAL_AXIS" in e for e in check_medial_lateral(shifted, medial_tolerance=0.02 * H)))
+
+
+class ChainResolutionFromTopology(unittest.TestCase):
+ def test_resolves_arms_legs_and_spine_without_reading_a_single_joint_name(self) -> None:
+ """Every joint in the fixture is called `node_NN`. Only the graph's shape can resolve it."""
+ chains = resolve_chains(HUMANOID, side_labels=TRUE_SIDE_LABELS)
+
+ self.assertTrue(
+ all(joint.startswith("node_") for chain in chains.all_chains() for joint in chain.joint_ids),
+ "fixture precondition: no joint name carries any information about what it is",
+ )
+
+ self.assertEqual(chains.arm["l"].joint_ids, ("node_13", "node_09", "node_15", "node_03"))
+ self.assertEqual(chains.arm["r"].joint_ids, ("node_27", "node_25", "node_12", "node_07"))
+ self.assertEqual(chains.leg["l"].joint_ids, ("node_29", "node_31", "node_02"))
+ self.assertEqual(chains.leg["r"].joint_ids, ("node_08", "node_11", "node_23"))
+ self.assertEqual(
+ chains.spine.joint_ids,
+ ("node_00", "node_17", "node_04", "node_19", "node_06", "node_21"),
+ "spine runs root -> hip branch -> shoulder branch -> head leaf",
+ )
+ self.assertEqual(chains.spine.leaf, "node_21", "the spine ends at the head leaf")
+ self.assertEqual(chains["arm.l"].leaf, "node_03", "arm chains end at a hand leaf")
+ self.assertEqual(chains["leg.r"].leaf, "node_23", "leg chains end at a foot leaf")
+
+ def test_symmetry_pairs_come_from_mirrored_local_x(self) -> None:
+ chains = resolve_chains(HUMANOID)
+ for group in (chains.arm, chains.leg):
+ left_x = chains.world_positions[group["l"].anchor][0]
+ right_x = chains.world_positions[group["r"].anchor][0]
+ self.assertAlmostEqual(left_x, -right_x, places=9)
+
+ def test_a_hierarchy_with_no_shoulder_branch_is_rejected_not_guessed(self) -> None:
+ legs_only = [node for node in HUMANOID if node.id not in {"node_13", "node_27", "node_09", "node_15", "node_03", "node_25", "node_12", "node_07"}]
+ with self.assertRaises(ChainResolutionError) as caught:
+ resolve_chains(legs_only)
+ self.assertIn("arm.l", str(caught.exception))
+
+ def test_two_roots_are_rejected(self) -> None:
+ with self.assertRaises(ChainResolutionError):
+ resolve_chains(HUMANOID + [JointNode("node_99", None, (0.0, 0.0, 0.0))])
+
+
+class GaitIsAPhaseMachine(unittest.TestCase):
+ def test_stance_intervals_are_explicit_and_wrap(self) -> None:
+ params = gait_parameters(walk_targets(H), H)
+ left, right = params.phase("leg.l"), params.phase("leg.r")
+ self.assertEqual(left.stance_intervals(), ((0.0, params.contact_fraction * params.duration),))
+ self.assertEqual(len(right.stance_intervals()), 2, "the trailing leg's stance wraps across t=0")
+ total = sum(hi - lo for hi, lo in ((b, a) for a, b in right.stance_intervals()))
+ self.assertAlmostEqual(total, params.contact_fraction * params.duration, places=12)
+
+ def test_double_support_is_the_specs_own_arithmetic(self) -> None:
+ walk = gait_parameters(walk_targets(H), H)
+ self.assertAlmostEqual(walk.contact_fraction, 0.60, places=12)
+ self.assertAlmostEqual(walk.double_support_fraction, 0.20, places=12)
+ self.assertEqual(walk.flight_fraction, 0.0)
+ run = gait_parameters(run_targets(H), H)
+ self.assertAlmostEqual(run.flight_fraction, 0.20, places=12)
+
+ def test_the_foot_world_position_is_literally_constant_during_stance(self) -> None:
+ """Not "nearly constant" — a sine-wave foot would move at every instant but the turns."""
+ params, clip = authored(walk_targets(H))
+ times = clip["sampleTimes"]
+ for side in ("l", "r"):
+ phase = params.phase(f"leg.{side}")
+ track = clip["landmarkPositions"][f"foot.{side}"]
+ by_plant: dict[int, set[tuple[float, float, float]]] = {}
+ for index, t in enumerate(times):
+ if phase.is_stance(t):
+ by_plant.setdefault(phase.plant_index(t)[0], set()).add(tuple(track[index]))
+ self.assertTrue(by_plant)
+ for plant, seen in by_plant.items():
+ self.assertEqual(len(seen), 1, f"foot.{side} moved during plant {plant}: {seen}")
+
+ def test_gait_parameters_scale_with_figure_height(self) -> None:
+ """The band is in fractions of H; the authored parameters are in model units."""
+ small = gait_parameters(walk_targets(H), 1.0)
+ large = gait_parameters(walk_targets(H), 2.5)
+ self.assertAlmostEqual(large.travel / small.travel, 2.5, places=12)
+ self.assertAlmostEqual(large.hip_rise / small.hip_rise, 2.5, places=12)
+ self.assertAlmostEqual(large.duration, small.duration, places=12)
+ big_clip = synthesise_gait_tracks(large)
+ self.assertEqual(
+ classifier_verdict(classify(measure(big_clip, 2.5)))[0],
+ "walk",
+ "a walk on a 2.5-unit-tall figure must still classify as a walk",
+ )
+
+ def test_primitives_table_carries_the_specs_parameters(self) -> None:
+ self.assertEqual(set(PRIMITIVES), {"gait", "ballistic", "reach", "additive"})
+ self.assertEqual(
+ PRIMITIVES["gait"].parameters,
+ ("cadence", "stride", "contactFraction", "hipRise", "armCounterSwing"),
+ )
+ self.assertEqual(
+ PRIMITIVES["ballistic"].parameters,
+ ("takeoffVelocity", "apexRise", "flightTime", "landAbsorption"),
+ )
+ self.assertEqual(
+ PRIMITIVES["reach"].parameters, ("targetSocket", "windupFraction", "followThrough", "return")
+ )
+ self.assertEqual(PRIMITIVES["additive"].parameters, ("amplitude", "period", "jointMask"))
+
+
+class TargetBands(unittest.TestCase):
+ def test_contains_names_the_feature_that_fell_outside(self) -> None:
+ """"Outside the band" is not actionable; "rise=0.19H is above [0.015, 0.025]" is."""
+ band = walk_targets(H)
+ good = band_features(authored(band)[1], H, measure=measure)
+
+ limping = dict(good, rise=0.19)
+ check = band.contains(limping)
+ print(f"\n[band] {check.summary()}")
+ self.assertFalse(check.ok)
+ self.assertEqual(len(check.outside), 1)
+ miss = check.outside[0]
+ self.assertEqual(miss.feature, "rise")
+ self.assertEqual(miss.side, "above")
+ self.assertEqual(miss.value, 0.19)
+ self.assertIn("rise", str(miss))
+ self.assertIn("0.19", str(miss))
+ self.assertIn("rise", check.summary())
+
+ below = band.contains(dict(good, handRange=0.01))
+ self.assertEqual([m.feature for m in below.outside], ["handRange"])
+ self.assertEqual(below.outside[0].side, "below")
+
+ both = band.contains(dict(good, rise=0.19, handRange=0.01))
+ self.assertEqual(sorted(m.feature for m in both.outside), ["handRange", "rise"])
+
+ def test_a_missing_feature_is_unevaluated_not_inside(self) -> None:
+ band = walk_targets(H)
+ good = band_features(authored(band)[1], H, measure=measure)
+ partial = {k: v for k, v in good.items() if k != "contact"}
+ check = band.contains(partial)
+ self.assertTrue(check.ok, "nothing measured fell outside")
+ self.assertEqual([name for name, _ in check.unevaluated], ["contact"])
+ self.assertNotIn("contact", check.inside)
+
+ def test_speed_band_mirrors_the_classifier_boundary_exclusively(self) -> None:
+ """§2 writes `speed < 0.60H/s`; a band with an inclusive 0.60 would accept a run."""
+ walk = walk_targets(H).ranges["speed"]
+ self.assertTrue(walk.hi_exclusive)
+ self.assertTrue(walk.contains(0.5999))
+ self.assertFalse(walk.contains(0.60))
+ self.assertEqual((walk.lo, walk.hi, walk.target), (0.30, 0.60, 0.40))
+
+ run = run_targets(H).ranges["speed"]
+ self.assertEqual((run.lo, run.hi), (0.60, 1.50))
+ self.assertTrue(run.hi_exclusive)
+
+ def test_the_worked_walk_example_is_encoded_verbatim(self) -> None:
+ band = walk_targets(H)
+ self.assertEqual((band.ranges["duration"].lo, band.ranges["duration"].hi), (1.0, 1.2))
+ self.assertEqual((band.ranges["rise"].lo, band.ranges["rise"].hi), (0.015, 0.025))
+ self.assertEqual((band.ranges["handRange"].lo, band.ranges["handRange"].hi), (0.15, 0.25))
+ self.assertEqual(band.ranges["contact"].target, 0.60)
+ self.assertEqual((band.ranges["scaleDelta"].lo, band.ranges["scaleDelta"].hi), (0.0, 0.0))
+ self.assertEqual(band.ranges["poseReturn"].hi, POSE_RETURN_DEGREES)
+ # travel = speed x duration, at the spec's 0.40H/s target
+ self.assertAlmostEqual(band.ranges["travel"].lo, 0.40 * 1.0, places=12)
+ self.assertAlmostEqual(band.ranges["travel"].hi, 0.40 * 1.2, places=12)
+ # footRange ~= travel / 2
+ self.assertAlmostEqual(band.ranges["footRange"].target, 0.5 * 0.5 * (0.40 + 0.48), places=12)
+
+ def test_run_targets_change_only_the_three_things_the_spec_changes(self) -> None:
+ walk, run = walk_targets(H), run_targets(H)
+ changed = {name for name in walk.ranges if walk.ranges[name] != run.ranges[name]}
+ self.assertEqual(
+ changed,
+ {"speed", "contact", "handRange", "travel", "footRange"},
+ "speed, contact and handRange are the spec's three; travel and footRange are derived from speed",
+ )
+
+
+class GateR4(unittest.TestCase):
+ def _accepted_walk(self, **overrides):
+ band = walk_targets(H)
+ params, clip = authored(band)
+ features = dict(band_features(clip, H, measure=measure))
+ features.update(overrides.pop("features", {}))
+ kwargs = dict(
+ classifier=classify,
+ classifier_input=measure(clip, H),
+ foot_slide_result=foot_slide(clip["landmarkPositions"], clip["sampleTimes"], clip["stance"], H),
+ source_ranges={"node_29": (-0.4, 0.4)},
+ authored_ranges={"node_29": (-0.2, 0.2)},
+ )
+ kwargs.update(overrides)
+ return accepts(features, band, "walk", **kwargs)
+
+ def test_a_correctly_authored_walk_passes_every_criterion(self) -> None:
+ acceptance = self._accepted_walk(declared_loop=None)
+ for criterion in acceptance.criteria:
+ print(f"\n[R4] {criterion.name}: {criterion.status} — {criterion.reason}")
+ self.assertTrue(acceptance.accepted, [c.reason for c in acceptance.failures])
+ self.assertEqual(acceptance.verdict, "accepted-with-unevaluated")
+ self.assertEqual(
+ [c.name for c in acceptance.unevaluated],
+ ["pose-return-loop"],
+ "the clip declares no loop flag, and §4 forbids guessing false",
+ )
+ self.assertEqual(acceptance.criterion("classifier-agreement").status, "pass")
+ self.assertEqual(acceptance.criterion("foot-slide").status, "pass")
+
+ def test_rejects_a_clip_with_scale_delta_above_zero_even_when_everything_else_passes(self) -> None:
+ """Gate R4: `scaleDelta == 0`. §1 calls it a tripwire, not a descriptor."""
+ clean = self._accepted_walk(declared_loop=None)
+ self.assertTrue(clean.accepted)
+
+ scaled = self._accepted_walk(declared_loop=None, features={"scaleDelta": 1e-6})
+ print(f"\n[R4 scaleDelta] {scaled.criterion('no-joint-scale').reason}")
+ self.assertFalse(scaled.accepted, "a non-zero scaleDelta must reject the clip on its own")
+ self.assertEqual(scaled.verdict, "rejected")
+ self.assertEqual(
+ sorted(c.name for c in scaled.failures),
+ ["band-containment", "no-joint-scale"],
+ "the scale tripwire fires, and the band's own scaleDelta == 0 range fires with it",
+ )
+ for name in ("classifier-agreement", "foot-slide"):
+ self.assertEqual(scaled.criterion(name).status, "pass", "every other criterion still passes")
+
+ def test_joint_range_is_unevaluated_not_passed_when_no_source_clips_exist(self) -> None:
+ """"no joint exceeds its measured range from the source clips, **where source clips exist**"."""
+ acceptance = self._accepted_walk(declared_loop=None, source_ranges=None, authored_ranges=None)
+ criterion = acceptance.criterion("joint-range-vs-source")
+ print(f"\n[R4 joint range] {criterion.status}: {criterion.reason}")
+ self.assertEqual(criterion.status, "unevaluated")
+ self.assertNotEqual(criterion.status, "pass")
+ self.assertIn("no source clips", criterion.reason)
+ self.assertTrue(acceptance.accepted, "an unevaluated criterion is not a failure")
+ self.assertFalse(acceptance.complete, "but it does mean the gate was not fully answered")
+
+ def test_joint_range_fails_when_an_authored_joint_exceeds_its_source_range(self) -> None:
+ acceptance = self._accepted_walk(
+ declared_loop=None,
+ source_ranges={"node_29": (-0.4, 0.4)},
+ authored_ranges={"node_29": (-0.9, 0.4)},
+ )
+ criterion = acceptance.criterion("joint-range-vs-source")
+ self.assertEqual(criterion.status, "fail")
+ self.assertIn("node_29", criterion.reason)
+ self.assertFalse(acceptance.accepted)
+
+ def test_classifier_disagreement_rejects_the_clip(self) -> None:
+ """The acceptance test is the classifier, so a clip it calls something else is rejected."""
+ band = run_targets(H)
+ _, run_clip = authored(band)
+ features = band_features(run_clip, H, measure=measure)
+ acceptance = accepts(
+ features,
+ band,
+ "walk", # the clip claims to be a walk; the measurements say otherwise
+ classifier=classify,
+ classifier_input=measure(run_clip, H),
+ )
+ criterion = acceptance.criterion("classifier-agreement")
+ print(f"\n[R4 classifier] {criterion.reason}")
+ self.assertEqual(criterion.status, "fail")
+ self.assertIn("does not agree", criterion.reason)
+ self.assertFalse(acceptance.accepted)
+
+ def test_a_declared_loop_is_held_to_the_pose_return_bound(self) -> None:
+ good = self._accepted_walk(declared_loop=True)
+ self.assertEqual(good.criterion("pose-return-loop").status, "pass")
+ bad = self._accepted_walk(declared_loop=True, features={"poseReturn": 4.0})
+ self.assertEqual(bad.criterion("pose-return-loop").status, "fail")
+ self.assertFalse(bad.accepted)
+
+ def test_missing_foot_slide_is_unevaluated_not_a_pass(self) -> None:
+ acceptance = self._accepted_walk(declared_loop=None, foot_slide_result=None)
+ criterion = acceptance.criterion("foot-slide")
+ self.assertEqual(criterion.status, "unevaluated")
+ self.assertIn("has not been asked", criterion.reason)
+
+ def test_missing_classifier_is_unevaluated_and_says_why_that_matters(self) -> None:
+ band = walk_targets(H)
+ _, clip = authored(band)
+ acceptance = accepts(band_features(clip, H, measure=measure), band, "walk", classifier=lambda _f: None)
+ self.assertEqual(acceptance.criterion("classifier-agreement").status, "fail")
+
+
+class HipRelativeFrame(unittest.TestCase):
+ def test_removing_root_motion_keeps_vertical_motion(self) -> None:
+ _, clip = authored(walk_targets(H))
+ relative = hip_relative_clip(clip)
+ world_features, relative_features = measure(clip, H), measure(relative, H)
+ self.assertAlmostEqual(relative_features.travel, 0.0, places=12)
+ self.assertAlmostEqual(relative_features.rise, world_features.rise, places=12)
+ self.assertLess(relative_features.foot_range, world_features.foot_range)
+
+ def test_foot_slide_on_a_hip_relative_clip_would_reject_a_correct_gait(self) -> None:
+ """The reason `hip_relative_clip` carries a warning: this is the wrong frame for G8."""
+ _, clip = authored(walk_targets(H))
+ relative = hip_relative_clip(clip)
+ world = foot_slide(clip["landmarkPositions"], clip["sampleTimes"], clip["stance"], H)
+ wrong_frame = foot_slide(relative["landmarkPositions"], relative["sampleTimes"], relative["stance"], H)
+ self.assertEqual(world.status, "pass")
+ self.assertEqual(wrong_frame.status, "fail", "documenting the trap, not endorsing it")
+
+
+class FallbackAndHelpers(unittest.TestCase):
+ def test_the_fallback_classifier_matches_the_specs_validation_table(self) -> None:
+ """§2's published measurements, run through whichever classifier this suite is using.
+
+ Pins the local fallback to the spec rather than to itself. Without this, a fallback
+ that quietly disagreed with §2 would let the round-trip tests pass on a classifier
+ nobody had checked.
+ """
+
+ class Row:
+ def __init__(self, travel, rise, speed, hand_range=0.0, foot_range=1.0):
+ self.travel, self.rise, self.speed = travel, rise, speed
+ self.hand_range, self.foot_range = hand_range, foot_range
+ self.duration, self.head_rise, self.scale_delta, self.pose_return = 1.0, 0.0, 0.0, 0.0
+
+ table = [
+ ("walk-forward", Row(1.133, 0.019, 0.400), "walk"),
+ ("run-forward", Row(1.465, 0.021, 0.799), "run"),
+ ("dash-forward", Row(2.906, 0.02, 2.250), "dash"),
+ ("jump-in-place", Row(0.272, 0.248, 0.0), "jump"),
+ ("leap-forward", Row(2.826, 0.517, 0.0), "leap"),
+ ("idle-still", Row(0.013, 0.0001, 0.0), "idle"),
+ ]
+ for name, row, expected in table:
+ primary, labels = classifier_verdict(classify(row))
+ self.assertEqual(primary, expected, f"{name}: got {primary!r} (labels {list(labels)})")
+
+ _, arms_only = classifier_verdict(classify(Row(0.01, 0.008, 0.0, hand_range=0.55, foot_range=0.02)))
+ self.assertIn("planted", arms_only)
+ self.assertIn("gesture", arms_only)
+
+ def test_classifier_verdict_normalises_every_plausible_return_shape(self) -> None:
+ self.assertEqual(classifier_verdict("walk"), ("walk", ("walk",)))
+ self.assertEqual(classifier_verdict(["in-place", "walk"])[0], "walk")
+ self.assertEqual(classifier_verdict(("run", ["run", "in-place"])), ("run", ("run", "in-place")))
+ self.assertEqual(classifier_verdict({"primary": "dash", "labels": ["dash"]}), ("dash", ("dash",)))
+ self.assertEqual(classifier_verdict(None), (None, ()))
+ self.assertEqual(classifier_verdict([]), (None, ()), "an empty match stays empty; no class is invented")
+
+ def test_sample_times_do_not_double_count_the_loop_point(self) -> None:
+ _, clip = authored(walk_targets(H))
+ times = clip["sampleTimes"]
+ self.assertEqual(len(times), 25)
+ self.assertEqual(times[0], 0.0)
+ self.assertLess(times[-1], clip["duration"])
+
+ def test_authored_clips_validate_against_the_contract_payload_shape(self) -> None:
+ _, clip = authored(walk_targets(H))
+ payload = build_payload([clip], H)
+ self.assertEqual(payload["figureHeight"], H)
+ for landmark in payload["landmarks"]:
+ self.assertEqual(len(clip["landmarkPositions"][landmark]), len(clip["sampleTimes"]))
+ self.assertEqual(len(clip["jointScaleDelta"]), len(clip["sampleTimes"]))
+ self.assertEqual(max(clip["jointScaleDelta"]), 0.0)
+ if USING_REAL_CLIP_FEATURES:
+ from clip_features import load_payload # noqa: PLC0415
+
+ load_payload(payload) # raises if the shape is wrong
+
+
+class Cli(unittest.TestCase):
+ def _run(self, document, intended, *extra):
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "clip.json"
+ path.write_text(json.dumps(document), encoding="utf-8")
+ return subprocess.run(
+ [sys.executable, str(MODULE), str(path), intended, *extra],
+ capture_output=True,
+ text=True,
+ timeout=120,
+ )
+
+ def test_cli_accepts_a_good_walk_and_exits_zero(self) -> None:
+ if not USING_REAL_CLIP_FEATURES:
+ self.skipTest("the payload path of the CLI needs clip_features.measure_clip")
+ _, clip = authored(walk_targets(H))
+ proc = self._run(build_payload([clip], H), "walk")
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ report = json.loads(proc.stdout)
+ self.assertEqual(report["gate"], "R4")
+ self.assertTrue(report["accepted"])
+
+ def test_cli_exits_one_on_rejection(self) -> None:
+ document = {
+ "figureHeight": H,
+ "features": {
+ "duration": 1.1, "travel": 0.42, "rise": 0.02, "speed": 0.384,
+ "handRange": 0.20, "footRange": 0.26, "contact": 0.6,
+ "poseReturn": 0.0, "scaleDelta": 0.004,
+ },
+ }
+ proc = self._run(document, "walk")
+ self.assertEqual(proc.returncode, 1, proc.stdout)
+ report = json.loads(proc.stdout)
+ self.assertEqual(report["verdict"], "rejected")
+ self.assertIn("no-joint-scale", [c["criterion"] for c in report["criteria"] if c["status"] == "fail"])
+
+
+if __name__ == "__main__":
+ print(
+ f"clip_features {'IS' if USING_REAL_CLIP_FEATURES else 'is NOT'} importable; "
+ f"using the {'real' if USING_REAL_CLIP_FEATURES else 'local fallback'} §1/§2 implementation"
+ )
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_clip_features.py b/forge/tests/test_clip_features.py
new file mode 100644
index 0000000..4c2ef8f
--- /dev/null
+++ b/forge/tests/test_clip_features.py
@@ -0,0 +1,619 @@
+#!/usr/bin/env python3
+"""Tests for the §1-§4 clip vocabulary, built around the defects it exists to remove.
+
+The centrepiece is `TheSpecValidationTable`. It does not hand `classify` a struct full of numbers --
+anyone can make a classifier agree with a struct they typed. It SYNTHESISES landmark tracks that
+should measure to the numbers the spec's own validation table reports, measures them with
+`measure_clip`, and only then classifies. Synthesise -> measure -> classify is the whole round trip;
+break the measurement and the table stops reproducing, which is exactly what a silent unit change or
+a dropped normalisation would do.
+
+The second target is the loop rule. 1.5.1 shipped a rule that contradicted its own data, so
+`test_the_1_5_1_rule_would_have_rejected_the_clip_it_was_derived_from` executes both rules on the
+same clip and asserts they disagree. Describing the contradiction in a comment would let it come
+back; running it cannot.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import math
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage5_rig"))
+
+from clip_features import ( # noqa: E402
+ AUTO,
+ DEFAULT_THRESHOLDS,
+ REQUIRED_LANDMARKS,
+ ClipFeatures,
+ Thresholds,
+ _legacy_loop_rule_1_5_1,
+ classify,
+ decide_loop,
+ load_payload,
+ main,
+ measure_clip,
+ name_clip,
+ report,
+)
+
+SAMPLES = 25 # §1: "Sample the clip at N = 25 evenly spaced times"
+HIP_Y = 0.50 # hip height, fraction of H
+HEAD_OFFSET = 0.42 # head above hip, fraction of H
+
+
+def wave(index: int, samples: int = SAMPLES, cycles: int = 2) -> float:
+ """A sine over the clip that hits exactly +1 and -1 at N = 25 with two cycles.
+
+ Exactness matters: `rise` is a max-minus-min, so if the wave never quite reached its extremes the
+ synthesised clip would measure slightly under its target and every assertion below would need a
+ fudge factor large enough to hide a real error.
+ """
+ return math.sin(2.0 * math.pi * cycles * index / (samples - 1))
+
+
+def synth_clip(
+ source_name: str,
+ *,
+ duration: float,
+ travel: float,
+ rise: float,
+ hand_swing: float = 0.10,
+ stance_half_width: float = 0.06,
+ feet_follow_hip: bool = True,
+ foot_jitter: float = 0.0,
+ hip_returns: bool = False,
+ pose_return: float | None = 0.0,
+ scale_delta: float = 0.0,
+ height: float = 1.0,
+ samples: int = SAMPLES,
+) -> dict:
+ """Build a sampled clip whose §1 measurements are known in advance.
+
+ `travel` and `rise` are stated as fractions of H and the tracks are then multiplied by `height`,
+ which is what makes the H-scale invariance test meaningful: the same call at height 2.0 produces
+ genuinely doubled world coordinates, not a rescaled feature struct.
+
+ `hip_returns` walks the hip out and back so it ends where it started -- the `idle-gesture` shape
+ that broke the 1.5.1 loop rule.
+ """
+ times, hip, head, hand_l, hand_r, foot_l, foot_r = [], [], [], [], [], [], []
+ for index in range(samples):
+ unit = index / (samples - 1)
+ swing = wave(index, samples)
+ hip_x = travel * (math.sin(math.pi * unit) if hip_returns else unit)
+ hip_y = HIP_Y + 0.5 * rise * swing
+ foot_base = hip_x if feet_follow_hip else 0.0
+ times.append(duration * unit)
+ hip.append([hip_x * height, hip_y * height, 0.0])
+ head.append([hip_x * height, (hip_y + HEAD_OFFSET) * height, 0.0])
+ hand_l.append([(hip_x + hand_swing * swing) * height, (hip_y + 0.05) * height, 0.02 * height])
+ hand_r.append([(hip_x - hand_swing * swing) * height, (hip_y + 0.05) * height, -0.02 * height])
+ foot_l.append([(foot_base + stance_half_width + foot_jitter * swing) * height, 0.0, 0.0])
+ foot_r.append([(foot_base - stance_half_width - foot_jitter * swing) * height, 0.0, 0.0])
+
+ clip = {
+ "sourceName": source_name,
+ "duration": duration,
+ "sampleTimes": times,
+ "landmarkPositions": {
+ "hip": hip,
+ "head": head,
+ "hand.l": hand_l,
+ "hand.r": hand_r,
+ "foot.l": foot_l,
+ "foot.r": foot_r,
+ },
+ # One non-zero sample is enough to trip the wire; scaleDelta is a max over samples.
+ "jointScaleDelta": [scale_delta if index == samples // 2 else 0.0 for index in range(samples)],
+ }
+ if pose_return is not None:
+ clip["poseReturn"] = pose_return
+ return clip
+
+
+def payload_of(clips: list[dict], height: float = 1.0) -> dict:
+ return {"figureHeight": height, "landmarks": list(REQUIRED_LANDMARKS), "clips": clips}
+
+
+def measure(clip: dict, height: float = 1.0) -> ClipFeatures:
+ return measure_clip(clip, height)
+
+
+# The spec's own validation table (§2). `duration` is chosen so that travel / duration reproduces the
+# quoted speed exactly; the dashes in the spec's table are filled with values that keep the clip in
+# the class the table assigns it and are never asserted as if they came from the source.
+VALIDATION_TABLE: list[dict] = [
+ {
+ "name": "walk-forward", "travel": 1.133, "rise": 0.019, "speed": 0.400,
+ "duration": 1.133 / 0.400, "primary": "walk", "kwargs": {"hand_swing": 0.10},
+ },
+ {
+ "name": "run-forward", "travel": 1.465, "rise": 0.021, "speed": 0.799,
+ "duration": 1.465 / 0.799, "primary": "run", "kwargs": {"hand_swing": 0.18},
+ },
+ {
+ "name": "dash-forward", "travel": 2.906, "rise": 0.030, "speed": 2.250,
+ "duration": 2.906 / 2.250, "primary": "dash", "kwargs": {"hand_swing": 0.22},
+ },
+ {
+ "name": "jump-in-place", "travel": 0.272, "rise": 0.248, "speed": 0.272,
+ "duration": 1.0, "primary": "jump", "kwargs": {"hand_swing": 0.05},
+ },
+ {
+ "name": "leap-forward", "travel": 2.826, "rise": 0.517, "speed": 2.826 / 1.4,
+ "duration": 1.4, "primary": "leap", "kwargs": {"hand_swing": 0.20},
+ },
+ {
+ "name": "idle-still", "travel": 0.013, "rise": 0.0001, "speed": 0.0065,
+ "duration": 2.0, "primary": "idle",
+ "kwargs": {"hand_swing": 0.01, "feet_follow_hip": False, "stance_half_width": 0.02, "foot_jitter": 0.005},
+ },
+ {
+ "name": "arms-only", "travel": 0.050, "rise": 0.008, "speed": 0.050 / 1.5,
+ "duration": 1.5, "primary": "in-place",
+ "kwargs": {"hand_swing": 0.30, "feet_follow_hip": False, "stance_half_width": 0.02, "foot_jitter": 0.005},
+ },
+]
+
+
+def table_clip(row: dict, height: float = 1.0) -> dict:
+ return synth_clip(
+ row["name"],
+ duration=row["duration"],
+ travel=row["travel"],
+ rise=row["rise"],
+ height=height,
+ **row["kwargs"],
+ )
+
+
+class TheSpecValidationTable(unittest.TestCase):
+ """Synthesise -> measure -> classify, against the seven clips §2 validates itself on."""
+
+ def test_synthesised_clips_measure_the_numbers_the_spec_table_reports(self) -> None:
+ for row in VALIDATION_TABLE:
+ with self.subTest(clip=row["name"]):
+ features = measure(table_clip(row))
+ self.assertAlmostEqual(features.travel, row["travel"], places=9)
+ self.assertAlmostEqual(features.rise, row["rise"], places=9)
+ self.assertAlmostEqual(features.speed, row["speed"], places=9)
+ self.assertAlmostEqual(features.duration, row["duration"], places=9)
+ self.assertEqual(features.sample_count, SAMPLES)
+
+ def test_each_clip_lands_in_the_class_the_table_says(self) -> None:
+ for row in VALIDATION_TABLE:
+ with self.subTest(clip=row["name"]):
+ classification = classify(measure(table_clip(row)))
+ self.assertEqual(classification.primary, row["primary"])
+ self.assertIn(row["primary"], classification.labels)
+ self.assertIn(row["primary"], classification.reasons)
+
+ def test_a_leap_outranks_the_speed_class_it_also_matches(self) -> None:
+ # leap-forward covers 2.826H in 1.4s, which is genuinely dash speed. Both labels are true and
+ # both are returned; `dash` as the primary would lose the fact that it left the ground.
+ classification = classify(measure(table_clip(VALIDATION_TABLE[4])))
+ self.assertIn("dash", classification.labels)
+ self.assertIn("leap", classification.labels)
+ self.assertEqual(classification.primary, "leap")
+
+ def test_arms_only_carries_all_three_labels_at_once(self) -> None:
+ row = VALIDATION_TABLE[6]
+ classification = classify(measure(table_clip(row)))
+ # Exactly these three: the table says "planted + gesture", and a clip whose hips travel
+ # 0.050H is also `in-place`. Nothing else may creep in.
+ self.assertEqual(set(classification.labels), {"in-place", "planted", "gesture"})
+ self.assertEqual(classification.primary, "in-place")
+
+ def test_the_same_motion_at_H_2_classifies_identically(self) -> None:
+ """H-scale invariance. Every feature is a fraction of H, so doubling the rig must change
+ nothing -- a normalisation dropped anywhere turns every threshold into a unit-dependent
+ accident."""
+ for row in VALIDATION_TABLE:
+ with self.subTest(clip=row["name"]):
+ unit = measure(table_clip(row, height=1.0), 1.0)
+ doubled = measure(table_clip(row, height=2.0), 2.0)
+ for attribute in ("travel", "rise", "speed", "hand_range", "foot_range", "head_rise", "hip_return"):
+ self.assertAlmostEqual(
+ getattr(doubled, attribute), getattr(unit, attribute), places=9,
+ msg=f"{attribute} is not H-invariant",
+ )
+ self.assertEqual(classify(doubled).labels, classify(unit).labels)
+ self.assertEqual(classify(doubled).primary, classify(unit).primary)
+
+
+class TheLoopRule(unittest.TestCase):
+ """§4. The rule 1.5.1 got wrong, and the data that proves it wrong."""
+
+ def wandering_clip(self) -> ClipFeatures:
+ # `idle-gesture`: travel 0.121H -- six times the idle threshold -- and correctly loopable,
+ # because the hip walks out and comes back and the pose returns.
+ return measure(
+ synth_clip(
+ "NlaTrack.007", duration=2.0, travel=0.121, rise=0.010,
+ hand_swing=0.30, hip_returns=True, pose_return=0.2,
+ feet_follow_hip=False, stance_half_width=0.02,
+ )
+ )
+
+ def test_a_clip_that_wanders_and_returns_loops(self) -> None:
+ features = self.wandering_clip()
+ self.assertAlmostEqual(features.travel, 0.121, places=9)
+ self.assertLess(features.hip_return, 1e-9)
+ decision = decide_loop(features)
+ self.assertIs(decision.loop, True)
+ self.assertIn("poseReturn", decision.reason)
+
+ def test_the_1_5_1_rule_would_have_rejected_the_clip_it_was_derived_from(self) -> None:
+ """The contradiction, executed rather than described.
+
+ 1.5.1: "a clip that neither travels nor rises can repeat seamlessly". idle-gesture travels
+ 0.121H and loops. Both rules run on the same features here, and they must disagree -- if this
+ test ever goes green by agreement, the corrected rule has been reverted.
+ """
+ features = self.wandering_clip()
+ self.assertFalse(_legacy_loop_rule_1_5_1(features))
+ self.assertIs(decide_loop(features).loop, True)
+ self.assertGreater(features.travel, DEFAULT_THRESHOLDS.idle_travel * 6)
+
+ def test_a_clip_that_ends_mid_stride_does_not_loop(self) -> None:
+ # Ends 0.013H from where it started -- a centimetre on a 1 m figure. Small enough to look
+ # fine in a viewport, large enough to pop every time the clip wraps.
+ features = measure(
+ synth_clip("NlaTrack.004", duration=1.0, travel=0.013, rise=0.012, pose_return=0.2)
+ )
+ self.assertAlmostEqual(features.hip_return, 0.013, places=6)
+ self.assertGreater(features.hip_return, decide_loop(features).hip_tolerance)
+ decision = decide_loop(features)
+ self.assertIs(decision.loop, False)
+ self.assertIn("hip(T)", decision.reason)
+ # And note what the OLD rule would have said: travel 0.013 < 0.02 and rise 0.012 < 0.02, so
+ # it would have called this one loopable. The two rules fail in BOTH directions.
+ self.assertTrue(_legacy_loop_rule_1_5_1(features))
+
+ def test_pose_return_over_the_limit_rejects_even_when_the_hip_comes_home(self) -> None:
+ features = measure(
+ synth_clip("NlaTrack.009", duration=1.0, travel=0.20, rise=0.01, hip_returns=True, pose_return=8.0)
+ )
+ decision = decide_loop(features)
+ self.assertIs(decision.loop, False)
+ self.assertIn("poseReturn", decision.reason)
+
+ def test_missing_pose_return_is_none_not_false(self) -> None:
+ """Undecidable is a third answer.
+
+ A host that cannot measure per-joint deltas omits the key. Reporting False would look
+ conservative and be a lie: every loopable clip on that host silently becomes one-shot, and
+ nothing downstream can tell "measured, does not loop" from "nobody looked".
+ """
+ features = measure(
+ synth_clip("NlaTrack.002", duration=1.0, travel=0.05, rise=0.01, pose_return=None)
+ )
+ self.assertIsNone(features.pose_return)
+ decision = decide_loop(features)
+ self.assertIsNone(decision.loop)
+ self.assertIsNot(decision.loop, False)
+ self.assertEqual(decision.reason, "poseReturn not measured")
+
+ def test_the_hip_tolerance_is_the_one_the_contract_names(self) -> None:
+ features = measure(synth_clip("NlaTrack.010", duration=1.0, travel=0.05, rise=0.01, pose_return=0.0))
+ self.assertEqual(decide_loop(features).hip_tolerance, 0.01)
+ self.assertEqual(decide_loop(features).pose_return_limit, 0.5)
+
+
+class TheScaleTripwire(unittest.TestCase):
+ """§1. `scaleDelta` is a tripwire, not a descriptor -- it must be visible before anything else."""
+
+ def test_scale_delta_above_zero_raises_the_flag(self) -> None:
+ features = measure(
+ synth_clip("NlaTrack.005", duration=1.0, travel=0.05, rise=0.01, scale_delta=0.004)
+ )
+ self.assertAlmostEqual(features.scale_delta, 0.004, places=12)
+ self.assertTrue(features.scales_joints)
+
+ def test_a_clean_clip_leaves_the_flag_down(self) -> None:
+ features = measure(synth_clip("NlaTrack.006", duration=1.0, travel=0.05, rise=0.01))
+ self.assertEqual(features.scale_delta, 0.0)
+ self.assertFalse(features.scales_joints)
+
+ def test_the_report_names_every_clip_that_trips_it(self) -> None:
+ payload = load_payload(
+ payload_of(
+ [
+ synth_clip("clean", duration=1.0, travel=0.05, rise=0.01),
+ synth_clip("scaled", duration=1.0, travel=0.05, rise=0.01, scale_delta=0.02),
+ ]
+ )
+ )
+ result = report(payload)
+ self.assertTrue(result["scaleTripwire"]["tripped"])
+ self.assertEqual(result["scaleTripwire"]["clips"], ["scaled"])
+
+ def test_the_cli_exits_1_when_a_clip_trips_the_tripwire(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "payload.json"
+ path.write_text(
+ json.dumps(
+ payload_of([synth_clip("scaled", duration=1.0, travel=0.05, rise=0.01, scale_delta=0.02)])
+ )
+ )
+ buffer = io.StringIO()
+ with redirect_stdout(buffer):
+ code = main([str(path)])
+ self.assertEqual(code, 1)
+ self.assertTrue(json.loads(buffer.getvalue())["scaleTripwire"]["tripped"])
+
+ def test_the_cli_exits_0_on_a_clean_payload_and_prints_a_report(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "payload.json"
+ path.write_text(json.dumps(payload_of([table_clip(row) for row in VALIDATION_TABLE])))
+ buffer = io.StringIO()
+ with redirect_stdout(buffer):
+ code = main([str(path)])
+ self.assertEqual(code, 0)
+ result = json.loads(buffer.getvalue())
+ self.assertEqual(result["clipCount"], len(VALIDATION_TABLE))
+ self.assertEqual(
+ [entry["classification"]["primary"] for entry in result["clips"]],
+ [row["primary"] for row in VALIDATION_TABLE],
+ )
+
+ def test_the_cli_exits_1_on_an_invalid_payload(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "payload.json"
+ path.write_text(json.dumps({"figureHeight": 1.0, "clips": []}))
+ buffer = io.StringIO()
+ errors = io.StringIO()
+ with redirect_stdout(buffer), redirect_stderr(errors):
+ code = main([str(path)])
+ self.assertEqual(code, 1)
+ self.assertIn("clips must be a non-empty list", errors.getvalue())
+ self.assertEqual(buffer.getvalue(), "")
+
+
+class TheVocabulary(unittest.TestCase):
+ """§1 definitions that a plausible-looking wrong implementation would still pass the table with."""
+
+ def hand_built(self, hands: tuple[list, list], feet: tuple[list, list]) -> ClipFeatures:
+ samples = len(hands[0])
+ hip = [[0.0, 0.5, 0.0] for _ in range(samples)]
+ clip = {
+ "sourceName": "hand-built",
+ "duration": 1.0,
+ "sampleTimes": [index / (samples - 1) for index in range(samples)],
+ "landmarkPositions": {
+ "hip": hip,
+ "head": [[0.0, 0.92, 0.0] for _ in range(samples)],
+ "hand.l": hands[0],
+ "hand.r": hands[1],
+ "foot.l": feet[0],
+ "foot.r": feet[1],
+ },
+ "jointScaleDelta": [0.0] * samples,
+ "poseReturn": 0.0,
+ }
+ return measure(clip)
+
+ def test_hand_and_foot_ranges_pool_both_sides(self) -> None:
+ # hand.l spans x in [0.0, 0.2]; hand.r spans x in [-0.3, -0.1]. Per-hand the largest range is
+ # 0.2, pooled it is 0.5. §1 says "over both hands", so 0.5 is the answer.
+ hand_l = [[0.0, 0.6, 0.0], [0.2, 0.6, 0.0]]
+ hand_r = [[-0.1, 0.6, 0.0], [-0.3, 0.6, 0.0]]
+ foot_l = [[0.015, 0.0, 0.0], [0.015, 0.0, 0.0]]
+ foot_r = [[-0.015, 0.0, 0.0], [-0.015, 0.0, 0.0]]
+ features = self.hand_built((hand_l, hand_r), (foot_l, foot_r))
+ self.assertAlmostEqual(features.hand_range, 0.5, places=12)
+ self.assertAlmostEqual(features.foot_range, 0.03, places=12)
+
+ def test_landmark_ranges_expose_the_per_foot_reading_pooling_hides(self) -> None:
+ """Pooling puts stance width inside footRange; the per-landmark ranges let a caller see past it.
+
+ Two feet standing perfectly still 0.12H apart pool to footRange 0.12H and miss `planted`
+ despite not moving at all. That is what the vocabulary says, so that is what it returns -- and
+ `landmark_ranges` carries the number that shows the feet never moved.
+ """
+ foot_l = [[0.06, 0.0, 0.0], [0.06, 0.0, 0.0]]
+ foot_r = [[-0.06, 0.0, 0.0], [-0.06, 0.0, 0.0]]
+ hands = ([[0.0, 0.6, 0.0], [0.0, 0.6, 0.0]], [[0.0, 0.6, 0.0], [0.0, 0.6, 0.0]])
+ features = self.hand_built(hands, (foot_l, foot_r))
+ self.assertAlmostEqual(features.foot_range, 0.12, places=12)
+ self.assertNotIn("planted", classify(features).labels)
+ per_foot = max(max(features.landmark_ranges[foot]) for foot in ("foot.l", "foot.r"))
+ self.assertEqual(per_foot, 0.0)
+
+ def test_hand_range_is_world_space_so_root_travel_is_inside_it(self) -> None:
+ """The pitfall §R4's design targets will walk a caller straight into.
+
+ §R4 quotes handRange 0.15-0.25H as the walk target, meaning the counter-swing. §1 measures
+ world positions, so a walk that covers 1.13H measures handRange a little OVER 1.13H: the
+ root dominates and the swing barely shows. The two numbers are not the same quantity, and
+ reading the §R4 band against this one would fail every walk ever authored. This is why
+ `gesture` is gated on `in-place` -- the hand threshold only means what it says once the root
+ is known to be still. An R4 check that wants the counter-swing alone must subtract the hip.
+ """
+ row = VALIDATION_TABLE[0] # walk-forward, hand_swing 0.10 -> 0.20H of counter-swing
+ features = measure(table_clip(row))
+ self.assertGreater(features.hand_range, row["travel"])
+ self.assertGreater(features.hand_range, 4 * 0.25) # far outside §R4's 0.15-0.25H band
+ # Above the gesture threshold on the number alone, and correctly not a gesture.
+ self.assertGreater(features.hand_range, DEFAULT_THRESHOLDS.gesture_hand_range)
+ self.assertNotIn("gesture", classify(features).labels)
+
+ def test_travel_is_planar_so_a_vertical_hop_is_not_travel(self) -> None:
+ features = measure(synth_clip("hop", duration=1.0, travel=0.0, rise=0.30))
+ self.assertEqual(features.travel, 0.0)
+ self.assertAlmostEqual(features.rise, 0.30, places=9)
+ self.assertEqual(classify(features).primary, "jump")
+
+ def test_travel_counts_the_z_axis_too(self) -> None:
+ samples = 5
+ hip = [[0.0, 0.5, 0.4 * index / (samples - 1)] for index in range(samples)]
+ clip = {
+ "sourceName": "sidestep",
+ "duration": 1.0,
+ "sampleTimes": [index / (samples - 1) for index in range(samples)],
+ "landmarkPositions": {
+ "hip": hip,
+ "head": [[point[0], point[1] + 0.42, point[2]] for point in hip],
+ "hand.l": [[0.1, 0.55, point[2]] for point in hip],
+ "hand.r": [[-0.1, 0.55, point[2]] for point in hip],
+ "foot.l": [[0.015, 0.0, point[2]] for point in hip],
+ "foot.r": [[-0.015, 0.0, point[2]] for point in hip],
+ },
+ "jointScaleDelta": [0.0] * samples,
+ "poseReturn": 0.0,
+ }
+ self.assertAlmostEqual(measure(clip).travel, 0.4, places=12)
+
+ def test_head_rise_is_the_head_not_the_hip(self) -> None:
+ features = measure(synth_clip("crouch", duration=1.0, travel=0.0, rise=0.20))
+ # In this fixture the head rides the hip exactly, so the two agree -- which is what makes it
+ # a usable pin: headRise reading anything else means it sampled the wrong landmark.
+ self.assertAlmostEqual(features.head_rise, features.rise, places=12)
+
+
+class Naming(unittest.TestCase):
+ """§3. What a name is allowed to claim."""
+
+ def features_for(self, row_index: int) -> ClipFeatures:
+ return measure(table_clip(VALIDATION_TABLE[row_index]))
+
+ def test_a_measured_name_is_not_inferred_and_quotes_its_numbers(self) -> None:
+ features = self.features_for(1) # run-forward
+ named = name_clip(features, "run-forward")
+ self.assertFalse(named.inferred)
+ self.assertEqual(named.id, "run-forward")
+ self.assertEqual(named.measured, "speed 0.799 H/s, rise 0.021H")
+
+ def test_an_intent_word_sets_inferred(self) -> None:
+ # No kinematic feature distinguishes a strike from a stumble.
+ features = self.features_for(6) # arms-only
+ self.assertTrue(name_clip(features, "strike-overhead").inferred)
+ self.assertTrue(name_clip(features, "taunt").inferred)
+ self.assertFalse(name_clip(features, "arms-only-feet-planted").inferred)
+
+ def test_inferred_can_be_overridden_because_no_word_list_is_complete(self) -> None:
+ features = self.features_for(6)
+ self.assertTrue(name_clip(features, "reaching-forward", inferred=True).inferred)
+ self.assertFalse(name_clip(features, "strike-overhead", inferred=False).inferred)
+
+ def test_source_name_survives_renaming(self) -> None:
+ clip = table_clip(VALIDATION_TABLE[0])
+ clip["sourceName"] = "NlaTrack.003"
+ named = name_clip(measure(clip), "walk-forward")
+ self.assertEqual(named.source_name, "NlaTrack.003")
+ self.assertEqual(named.label, "walk-forward")
+
+ def test_the_measured_string_mentions_the_labels_that_fired(self) -> None:
+ features = self.features_for(6) # arms-only: in-place + planted + gesture
+ named = name_clip(features, "arms-only-feet-planted")
+ self.assertIn("footRange", named.measured)
+ self.assertIn("handRange", named.measured)
+
+ def test_loop_is_decided_from_the_features_unless_supplied(self) -> None:
+ features = measure(
+ synth_clip("NlaTrack.008", duration=1.0, travel=0.05, rise=0.01, hip_returns=True, pose_return=0.1)
+ )
+ self.assertIs(name_clip(features, "sway", loop=AUTO).loop, True)
+ self.assertIs(name_clip(features, "sway", loop=False).loop, False)
+ undecidable = measure(
+ synth_clip("NlaTrack.011", duration=1.0, travel=0.05, rise=0.01, pose_return=None)
+ )
+ self.assertIsNone(name_clip(undecidable, "sway").loop)
+
+
+class Thresholding(unittest.TestCase):
+ """§2 thresholds are `single-subject` starting values, so they must be replaceable and recorded."""
+
+ def test_classification_records_the_thresholds_it_used(self) -> None:
+ features = measure(table_clip(VALIDATION_TABLE[0]))
+ self.assertIs(classify(features).thresholds, DEFAULT_THRESHOLDS)
+ custom = Thresholds(walk_speed=0.9, provenance="second rig")
+ self.assertIs(classify(features, custom).thresholds, custom)
+
+ def test_raising_the_walk_floor_declassifies_the_walk_clip(self) -> None:
+ features = measure(table_clip(VALIDATION_TABLE[0])) # 0.400 H/s
+ self.assertEqual(classify(features).primary, "walk")
+ self.assertIsNone(classify(features, Thresholds(walk_speed=0.5, run_speed=0.9)).primary)
+
+ def test_a_clip_in_a_gap_gets_no_primary_class(self) -> None:
+ """travel 0.40H is too far to be `in-place`, speed 0.20 H/s too slow to be `walk`.
+
+ `primary` is None and `labels` is empty. Nearest-neighbour guessing here would make the
+ threshold table stop being evidence -- the gaps are the finding.
+ """
+ features = measure(synth_clip("gap", duration=2.0, travel=0.40, rise=0.05))
+ classification = classify(features)
+ self.assertEqual(classification.labels, ())
+ self.assertIsNone(classification.primary)
+
+
+class PayloadValidation(unittest.TestCase):
+ """A bad payload must name the clip and the field. Eleven clips and a bare "length mismatch"
+ costs an afternoon of bisecting JSON."""
+
+ def test_rejects_a_clip_whose_sample_times_and_positions_disagree(self) -> None:
+ clip = synth_clip("NlaTrack.003", duration=1.0, travel=0.05, rise=0.01)
+ clip["landmarkPositions"]["hip"] = clip["landmarkPositions"]["hip"][:-1]
+ with self.assertRaises(ValueError) as caught:
+ load_payload(payload_of([clip]))
+ message = str(caught.exception)
+ self.assertIn("NlaTrack.003", message)
+ self.assertIn("hip", message)
+ self.assertIn("25", message)
+ self.assertIn("24", message)
+
+ def test_rejects_a_missing_landmark(self) -> None:
+ clip = synth_clip("NlaTrack.001", duration=1.0, travel=0.05, rise=0.01)
+ del clip["landmarkPositions"]["foot.r"]
+ with self.assertRaisesRegex(ValueError, r"NlaTrack\.001.*foot\.r"):
+ load_payload(payload_of([clip]))
+
+ def test_rejects_a_missing_joint_scale_delta_rather_than_assuming_zero(self) -> None:
+ clip = synth_clip("NlaTrack.001", duration=1.0, travel=0.05, rise=0.01)
+ del clip["jointScaleDelta"]
+ with self.assertRaisesRegex(ValueError, r"NlaTrack\.001.*jointScaleDelta"):
+ load_payload(payload_of([clip]))
+
+ def test_rejects_a_non_finite_coordinate(self) -> None:
+ clip = synth_clip("NlaTrack.001", duration=1.0, travel=0.05, rise=0.01)
+ clip["landmarkPositions"]["hand.l"][3] = [0.0, float("nan"), 0.0]
+ with self.assertRaisesRegex(ValueError, r"NlaTrack\.001.*hand\.l"):
+ load_payload(payload_of([clip]))
+
+ def test_rejects_a_zero_or_negative_figure_height(self) -> None:
+ clip = synth_clip("NlaTrack.001", duration=1.0, travel=0.05, rise=0.01)
+ with self.assertRaisesRegex(ValueError, "figureHeight"):
+ load_payload(payload_of([clip], height=0.0))
+
+ def test_rejects_a_zero_duration(self) -> None:
+ clip = synth_clip("NlaTrack.001", duration=1.0, travel=0.05, rise=0.01)
+ clip["duration"] = 0.0
+ with self.assertRaisesRegex(ValueError, r"NlaTrack\.001.*duration"):
+ load_payload(payload_of([clip]))
+
+ def test_accepts_a_payload_that_omits_pose_return_entirely(self) -> None:
+ clip = synth_clip("NlaTrack.001", duration=1.0, travel=0.05, rise=0.01, pose_return=None)
+ loaded = load_payload(payload_of([clip]))
+ self.assertIsNone(loaded["clips"][0]["poseReturn"])
+
+ def test_a_path_and_a_dict_take_the_same_route(self) -> None:
+ payload = payload_of([table_clip(VALIDATION_TABLE[0])])
+ with tempfile.TemporaryDirectory() as directory:
+ path = Path(directory) / "payload.json"
+ path.write_text(json.dumps(payload))
+ from_path = load_payload(path)
+ self.assertEqual(from_path, load_payload(payload))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_emit_animation_runtime.py b/forge/tests/test_emit_animation_runtime.py
new file mode 100644
index 0000000..1418df6
--- /dev/null
+++ b/forge/tests/test_emit_animation_runtime.py
@@ -0,0 +1,272 @@
+#!/usr/bin/env python3
+"""Tests for the Stage R5 runtime emitter (forge/stage5_rig/emit_animation_runtime.py).
+
+This is a code generator: the correct level to assert on is the EMITTED TEXT,
+not a re-implementation of TypeScript semantics in Python. Each test traces to
+a specific rule in docs/pipelines/character-rigging-animation-1.5.2.md Stage
+R1 / Stage R5, or to one of the Appendix failures — see the docstring on each
+test for which one.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage5_rig"))
+
+from emit_animation_runtime import ( # noqa: E402
+ BINDING_EPSILON,
+ MINIMUM_GATE_R1_SAMPLES,
+ emit_animation_runtime,
+)
+
+
+def _clip(id_: str, label: str = "", source_name: str = "", duration: float = 1.0, loop: bool | None = False) -> dict:
+ return {
+ "id": id_,
+ "label": label or id_,
+ "sourceName": source_name or id_,
+ "duration": duration,
+ "loop": loop,
+ }
+
+
+SAMPLE_CLIPS = [
+ _clip("walk-forward", duration=1.133, loop=True),
+ _clip("idle-still", duration=2.0, loop=False),
+ _clip("mystery-strip", duration=0.75, loop=None),
+]
+
+
+class EmitAnimationRuntimeTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.source = emit_animation_runtime(SAMPLE_CLIPS)
+
+ # -- Stage R1: bind space (Appendix failure 1 / failure 3) ---------------
+
+ def test_bind_call_is_identity_always(self) -> None:
+ self.assertIn("bind(skeleton, new THREE.Matrix4())", self.source)
+
+ def test_display_offset_uses_bounds_only(self) -> None:
+ start = self.source.index("function computeDisplayOffset")
+ end = self.source.index("\n}\n", start)
+ body = self.source[start:end]
+ self.assertIn("centre.x", body)
+ self.assertIn("bounds.min.y", body)
+ self.assertIn("centre.z", body)
+ # Appendix failure 3: armature translation double-counted into the
+ # display offset. The offset must come from mesh bounds alone.
+ self.assertNotIn("armature.matrixWorld", body)
+ self.assertNotIn("armature.position", body)
+
+ def test_bind_at_identity_does_not_read_armature_transform(self) -> None:
+ start = self.source.index("export function bindAtIdentity")
+ end = self.source.index("\n}\n", start)
+ body = self.source[start:end]
+ self.assertNotIn("armature.matrixWorld", body)
+ self.assertNotIn("armature.position", body)
+
+ def test_appendix_failures_are_documented(self) -> None:
+ # The three concrete things that were tried and measured, per the
+ # spec's Stage R1 table -- kept as code comments so the mistake isn't
+ # repeated silently.
+ self.assertIn("blank frame", self.source)
+ self.assertIn("0.5", self.source)
+ self.assertIn("floating", self.source)
+ self.assertIn("armature translation", self.source)
+
+ # -- Stage R5.1: ticker collection vs lazy geometry (Appendix failure 2) -
+
+ def test_refresh_tickers_is_exported_and_not_inlined_into_start(self) -> None:
+ self.assertIn("export function refreshTickers", self.source)
+ self.assertNotIn("function start(", self.source)
+
+ def test_lazy_character_wiring_calls_refresh(self) -> None:
+ self.assertIn("export function onCharacterReady", self.source)
+ start = self.source.index("export function onCharacterReady")
+ end = self.source.index("\n}\n", start)
+ self.assertIn("refreshTickers(", self.source[start:end])
+
+ def test_animation_ui_is_a_mount_function(self) -> None:
+ self.assertIn("export function mountAnimationUI(", self.source)
+ # Must not run at module scope -- it has to be callable after the
+ # controller exists, per Stage R5.1.
+ self.assertNotIn("mountAnimationUI();", self.source)
+
+ # -- Stage R5.2: presentation offsets vs animated pose --------------------
+
+ def test_tick_loop_orders_explode_offset_around_ticks(self) -> None:
+ start = self.source.index("export function tickAll")
+ end = self.source.index("\n}\n", start)
+ body = self.source[start:end]
+ remove_index = body.index("removeExplodeOffsetHook()")
+ loop_index = body.index("for (const tick of tickers)")
+ apply_index = body.index("applyExplodeOffsetHook()")
+ self.assertLess(remove_index, loop_index)
+ self.assertLess(loop_index, apply_index)
+
+ def test_no_cached_rest_pose_restore_in_tick_path(self) -> None:
+ start = self.source.index("export function tickAll")
+ end = self.source.index("\n}\n", start)
+ body = self.source[start:end]
+ self.assertNotIn("restoreRestPose", body)
+ self.assertNotIn("restoreBindPose", body)
+ self.assertNotIn("rest pose", body.lower())
+
+ # -- Stage R5.3: controller contract --------------------------------------
+
+ def test_play_orders_stop_restore_reset_loopmode_play(self) -> None:
+ start = self.source.index(" play(name: string): void {")
+ end = self.source.index("\n }\n", start)
+ body = self.source[start:end]
+ stop_index = body.index("this.mixer.stopAllAction()")
+ restore_index = body.index("this.restoreBindPose()")
+ reset_index = body.index("action.reset()")
+ loop_index = body.index("resolveLoopMode(")
+ play_index = body.index("action.play()")
+ self.assertLess(stop_index, restore_index)
+ self.assertLess(restore_index, reset_index)
+ self.assertLess(reset_index, loop_index)
+ self.assertLess(loop_index, play_index)
+
+ def test_seek_plays_then_pauses_sets_time_and_updates(self) -> None:
+ start = self.source.index(" seek(name: string, t: number): void {")
+ end = self.source.index("\n }\n", start)
+ body = self.source[start:end]
+ play_call_index = body.index("this.play(name)")
+ paused_index = body.index("action.paused = true")
+ time_index = body.index("action.time = t")
+ update_index = body.index("this.mixer.update(0)")
+ matrix_index = body.index("this.root.updateMatrixWorld(true)")
+ self.assertLess(play_call_index, paused_index)
+ self.assertLess(paused_index, time_index)
+ self.assertLess(time_index, update_index)
+ self.assertLess(update_index, matrix_index)
+
+ def test_stop_orders_stop_restore_then_idle(self) -> None:
+ start = self.source.index(" stop(): void {")
+ end = self.source.index("\n }\n", start)
+ body = self.source[start:end]
+ stop_index = body.index("this.mixer.stopAllAction()")
+ restore_index = body.index("this.restoreBindPose()")
+ idle_index = body.index("this.active = 'idle'")
+ self.assertLess(stop_index, restore_index)
+ self.assertLess(restore_index, idle_index)
+
+ def test_advance_updates_mixer_then_matrix_world(self) -> None:
+ start = self.source.index(" advance(dt: number): void {")
+ end = self.source.index("\n }\n", start)
+ body = self.source[start:end]
+ mixer_index = body.index("this.mixer.update(dt)")
+ matrix_index = body.index("this.root.updateMatrixWorld(true)")
+ self.assertLess(mixer_index, matrix_index)
+
+ # -- loop mode ------------------------------------------------------------
+
+ def test_loop_true_emits_looprepeat_infinity(self) -> None:
+ self.assertIn("clip.loop === true", self.source)
+ self.assertIn("THREE.LoopRepeat, repetitions: Infinity", self.source)
+
+ def test_loop_false_emits_looponce_clamped(self) -> None:
+ self.assertIn("clip.loop === false", self.source)
+ # LoopOnce appears at least twice: once for the false branch, once
+ # for the null (unmeasured) branch.
+ self.assertGreaterEqual(self.source.count("THREE.LoopOnce"), 2)
+ self.assertIn("clampWhenFinished: true", self.source)
+
+ def test_loop_null_emits_looponce_with_not_measured_comment(self) -> None:
+ null_branch_start = self.source.index("clip.loop === null")
+ # The explanatory comment sits immediately above the null-branch
+ # return in resolveLoopMode(); look at a window around it.
+ window = self.source[max(0, null_branch_start - 400) : null_branch_start + 200]
+ self.assertIn("not measured", window)
+ self.assertIn("LoopOnce", window)
+
+ def test_clips_data_round_trips_loop_null_as_json_null(self) -> None:
+ # json.dumps(None) -> "null"; must not become the string "None".
+ self.assertIn('"loop": null', self.source)
+ self.assertNotIn("None", self.source)
+
+ # -- Gate R1 harness --------------------------------------------------------
+
+ def test_binding_epsilon_is_two_to_the_negative_23(self) -> None:
+ self.assertEqual(BINDING_EPSILON, 2**-23)
+ self.assertTrue(
+ "Math.pow(2, -23)" in self.source or "2 ** -23" in self.source,
+ "expected BINDING_EPSILON to be emitted as Math.pow(2, -23) or 2 ** -23",
+ )
+ self.assertIn("export const BINDING_EPSILON", self.source)
+
+ def test_gate_r1_seeks_at_least_five_times_per_clip(self) -> None:
+ self.assertIn("export function runGateR1", self.source)
+ start = self.source.index("export function runGateR1")
+ # Grab the full function through its default-parameter sample count.
+ header_end = self.source.index("{", start)
+ header = self.source[start:header_end]
+ # Default sample count baked into the signature must be >= 5.
+ self.assertIn("sampleCount: number = 5", header)
+ body_end = self.source.index("\n}\n", header_end)
+ body = self.source[header_end:body_end]
+ self.assertIn("Math.max(", body)
+ self.assertIn("controller.seek(", body)
+
+ def test_gate_sample_count_below_minimum_is_rejected(self) -> None:
+ with self.assertRaises(ValueError):
+ emit_animation_runtime(SAMPLE_CLIPS, {"gate_sample_count": MINIMUM_GATE_R1_SAMPLES - 1})
+
+ def test_gate_r1_docstring_states_its_purpose(self) -> None:
+ gate_function_index = self.source.index("export function runGateR1")
+ only_check_index = self.source.index("ONLY check")
+ # The "this is the ONLY check that ... drives nothing" explanation
+ # must sit ahead of (documenting) the harness, and name what it
+ # distinguishes: a clip that plays vs. one that merely exists.
+ self.assertLess(only_check_index, gate_function_index)
+ nearby = self.source[only_check_index : only_check_index + 300]
+ self.assertIn("drives", nearby)
+
+ # -- escaping ---------------------------------------------------------------
+
+ def test_special_characters_in_label_are_json_escaped_and_contained(self) -> None:
+ tricky_label = 'say "hi"\\like `this`'
+ tricky_source_name = 'Nla"Track\\`.003'
+ clips = [_clip("weird-clip", label=tricky_label, source_name=tricky_source_name, loop=None)]
+ source = emit_animation_runtime(clips)
+
+ # The label/sourceName must appear only inside a properly escaped
+ # JSON string -- i.e. the raw backslash-quote sequence from Python's
+ # literal must not appear verbatim (it must be doubled/escaped), and
+ # the module must still be syntactically balanced around it.
+ self.assertIn('\\"hi\\"', source) # escaped quote survives
+ self.assertIn("\\\\like", source) # escaped backslash survives
+ self.assertIn("`this`", source) # backtick is inert in a "..." string
+
+ # Sanity: the CLIPS array is still well-formed JSON-ish and the
+ # following export statement is intact, i.e. nothing broke out of
+ # the string literal into the surrounding module.
+ clips_start = source.index("export const CLIPS")
+ next_export = source.index("export const BINDING_EPSILON")
+ clips_block = source[clips_start:next_export]
+ self.assertIn('"id": "weird-clip"', clips_block)
+
+ # -- module map / no stray dependency ---------------------------------------
+
+ def test_clips_export_matches_input_ids(self) -> None:
+ for clip in SAMPLE_CLIPS:
+ self.assertIn(f'"id": "{clip["id"]}"', self.source)
+
+ def test_rejects_clip_missing_required_key(self) -> None:
+ with self.assertRaises(ValueError):
+ emit_animation_runtime([{"id": "x", "label": "x", "sourceName": "x", "duration": 1.0}])
+
+ def test_rejects_non_boolean_loop(self) -> None:
+ with self.assertRaises(ValueError):
+ emit_animation_runtime([_clip("x", loop="yes")]) # type: ignore[arg-type]
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_emit_animation_runtime_tsc_smoke.py b/forge/tests/test_emit_animation_runtime_tsc_smoke.py
new file mode 100644
index 0000000..81b81b9
--- /dev/null
+++ b/forge/tests/test_emit_animation_runtime_tsc_smoke.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python3
+"""Cleanup-safe showcase TypeScript smoke coverage for the Stage R5 runtime emitter.
+
+Gated exactly like test_showcase_tsc_smoke.py: skips (does not fail) when
+IMG2THREEJS_SHOWCASE_ROOT is unset, so a clean CI checkout without a
+img2threejs-showcase checkout sees a skip, not a failure. Set
+IMG2THREEJS_REQUIRE_SHOWCASE=1 to make the missing-checkout case a hard
+failure instead (see showcase_test_support.showcase_root()).
+
+Emits a sample module covering the loop true/false/null cases and runs the
+showcase's own `npx tsc --noEmit` against it -- no tsc dependency is added
+here; this test only exercises whatever the showcase checkout already has
+installed.
+"""
+
+from __future__ import annotations
+
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+
+if __package__:
+ from .showcase_test_support import showcase_root
+else:
+ from showcase_test_support import showcase_root
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage5_rig"))
+
+from emit_animation_runtime import emit_animation_runtime # noqa: E402
+
+SAMPLE_CLIPS = [
+ {"id": "walk-forward", "label": "Walk Forward", "sourceName": "NlaTrack", "duration": 1.133, "loop": True},
+ {"id": "idle-still", "label": "Idle Still", "sourceName": "NlaTrack.001", "duration": 2.0, "loop": False},
+ {"id": "mystery-strip", "label": "Mystery Strip", "sourceName": "NlaTrack.002", "duration": 0.75, "loop": None},
+]
+
+
+class EmitAnimationRuntimeTscSmokeTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.showcase_root = showcase_root()
+ self.smoke_source = self.showcase_root / "src" / "__animation_runtime_smoke__.ts"
+
+ def tearDown(self) -> None:
+ # Clean up even when the assertion above failed -- never leave the
+ # temp file behind in someone else's showcase checkout.
+ if getattr(self, "smoke_source", None) is not None and self.smoke_source.exists():
+ self.smoke_source.unlink()
+
+ def _run_tsc(self) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(
+ ["npx", "tsc", "--noEmit"],
+ cwd=self.showcase_root,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+
+ def test_emitted_runtime_typechecks_with_no_diagnostics(self) -> None:
+ self.assertFalse(self.smoke_source.exists())
+ try:
+ source = emit_animation_runtime(SAMPLE_CLIPS)
+ self.smoke_source.write_text(source, encoding="utf-8")
+ self.assertTrue(self.smoke_source.exists())
+
+ result = self._run_tsc()
+ combined_output = result.stdout + result.stderr
+ self.assertEqual(result.returncode, 0, combined_output)
+ self.assertEqual(combined_output.strip(), "", combined_output)
+ finally:
+ if self.smoke_source.exists():
+ self.smoke_source.unlink()
+
+ self.assertFalse(self.smoke_source.exists())
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_glb_rig_reference.py b/forge/tests/test_glb_rig_reference.py
new file mode 100644
index 0000000..b447e13
--- /dev/null
+++ b/forge/tests/test_glb_rig_reference.py
@@ -0,0 +1,857 @@
+#!/usr/bin/env python3
+"""Tests for reading a GLB's own rig, built around the defect the module exists to remove.
+
+The centrepiece is `TheSkinOrderDefect`. Everything else in this file is downstream of one claim:
+that `skin.joints` -- not the node array, not a depth-first traversal -- is the ordering authority
+for bones and inverse binds (§R0.3). So the fixture rig deliberately scrambles its skin order away
+from its node order, and the first test asserts BOTH that the reader returns skin order AND that
+traversal order would have produced a different, wrong mapping. Reading it in the wrong order is
+how a rigged mesh comes out disjointed, and a test that only checked "we got six joints" would pass
+through that defect untouched.
+
+Every GLB here is synthesised in-process: real 12-byte header, real JSON chunk, real BIN chunk. The
+suite depends on no external asset.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import math
+import struct
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
+from typing import Any, Sequence
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage5_rig"))
+sys.path.insert(0, str(ROOT.parent))
+
+import clip_features # noqa: E402
+from glb_rig_reference import ( # noqa: E402
+ CORRESPONDENCE_TOLERANCE,
+ INVERSE_BIND_OMITTED,
+ UnsupportedInterpolation,
+ correspondence,
+ derive_figure_height,
+ joint_rest_positions,
+ main,
+ normalize_quat,
+ read_rig,
+ sample_clips,
+ slerp,
+)
+
+GLB_MAGIC = b"glTF"
+JSON_CHUNK = 0x4E4F534A
+BIN_CHUNK = 0x004E4942
+
+
+# ---------------------------------------------------------------------------------------------
+# Minimal GLB writer -- the one investment that keeps every test asset-free
+# ---------------------------------------------------------------------------------------------
+
+
+class BinChunk:
+ """Accumulates float data and hands back accessor indices, so a test names data, not offsets."""
+
+ def __init__(self) -> None:
+ self.data = bytearray()
+ self.views: list[dict[str, Any]] = []
+ self.accessors: list[dict[str, Any]] = []
+
+ def add(self, values: Sequence[float], element_type: str, count: int, **extra: Any) -> int:
+ while len(self.data) % 4:
+ self.data.append(0)
+ offset = len(self.data)
+ payload = struct.pack(f"<{len(values)}f", *values)
+ self.data.extend(payload)
+ self.views.append({"buffer": 0, "byteOffset": offset, "byteLength": len(payload)})
+ accessor: dict[str, Any] = {
+ "bufferView": len(self.views) - 1,
+ "componentType": 5126,
+ "count": count,
+ "type": element_type,
+ }
+ accessor.update(extra)
+ self.accessors.append(accessor)
+ return len(self.accessors) - 1
+
+
+def pack_glb(document: dict[str, Any], binary: bytes) -> bytes:
+ """Write a real binary glTF: 12-byte header, padded JSON chunk, padded BIN chunk."""
+ json_bytes = json.dumps(document).encode("utf-8")
+ json_bytes += b" " * (-len(json_bytes) % 4)
+ bin_bytes = bytes(binary)
+ bin_bytes += b"\x00" * (-len(bin_bytes) % 4)
+ body = struct.pack("<II", len(json_bytes), JSON_CHUNK) + json_bytes
+ if bin_bytes:
+ body += struct.pack("<II", len(bin_bytes), BIN_CHUNK) + bin_bytes
+ return struct.pack("<4sII", GLB_MAGIC, 2, 12 + len(body)) + body
+
+
+def translation_matrix(x: float, y: float, z: float) -> list[float]:
+ """Column-major 4x4 -- translation lives at indices 12, 13, 14."""
+ return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1]
+
+
+def quat_z(degrees: float) -> tuple[float, float, float, float]:
+ half = math.radians(degrees) / 2.0
+ return (0.0, 0.0, math.sin(half), math.cos(half))
+
+
+def nlerp(a: Sequence[float], b: Sequence[float], t: float) -> tuple[float, float, float, float]:
+ """The normalised lerp that a naive implementation would use instead of slerp."""
+ return normalize_quat(tuple(a[i] + (b[i] - a[i]) * t for i in range(4))) # type: ignore[arg-type]
+
+
+# ---------------------------------------------------------------------------------------------
+# The fixture rig
+#
+# Node order (0..7) and skin order are DELIBERATELY different. Node names are exporter-style
+# ("node_3"), never anatomical, so no test can accidentally pass by matching a name.
+# ---------------------------------------------------------------------------------------------
+
+# node index -> local translation
+NODE_LAYOUT: dict[int, tuple[str, tuple[float, float, float], list[int]]] = {
+ 0: ("node_0", (0.0, 0.0, 0.0), [1, 7]),
+ 1: ("node_1", (0.0, 0.5, 0.0), [2, 3, 4, 5, 6]), # hip
+ 2: ("node_2", (0.0, 0.4, 0.0), []), # head
+ 3: ("node_3", (-0.3, 0.1, 0.0), []), # hand.l
+ 4: ("node_4", (0.3, 0.1, 0.0), []), # hand.r
+ 5: ("node_5", (-0.1, -0.5, 0.0), []), # foot.l
+ 6: ("node_6", (0.1, -0.5, 0.0), []), # foot.r
+ 7: ("node_7", (0.0, 0.0, 0.0), []), # skinned mesh node
+}
+
+# Skin order is head, foot.l, hip, foot.r, hand.l, hand.r -- nothing like node order.
+SKIN_JOINTS = [2, 5, 1, 6, 3, 4]
+TRAVERSAL_ORDER = [1, 2, 3, 4, 5, 6] # what a depth-first walk of the joint nodes would produce
+
+LANDMARK_NODES = {"hip": 1, "head": 2, "hand.l": 3, "hand.r": 4, "foot.l": 5, "foot.r": 6}
+
+# World rest positions implied by NODE_LAYOUT, used by the correspondence tests.
+JOINT_WORLD = {
+ 1: (0.0, 0.5, 0.0),
+ 2: (0.0, 0.9, 0.0),
+ 3: (-0.3, 0.6, 0.0),
+ 4: (0.3, 0.6, 0.0),
+ 5: (-0.1, 0.0, 0.0),
+ 6: (0.1, 0.0, 0.0),
+}
+
+
+def build_glb(
+ path: Path,
+ *,
+ skin_joints: Sequence[int] = SKIN_JOINTS,
+ inverse_binds: bool = True,
+ extra_skin_joints: Sequence[int] | None = None,
+ animations: Sequence[dict[str, Any]] | None = None,
+) -> Path:
+ """Write the fixture rig. `animations` entries are {"name", "channels": [channel spec]}.
+
+ A channel spec is {"node", "path", "times", "values", "interpolation"}; `values` is flat.
+ """
+ chunk = BinChunk()
+ # A 1.0-high mesh so figure height H measures to 1.0 from the file's own bounds.
+ positions = chunk.add(
+ [-0.5, 0.0, -0.5, 0.5, 0.0, -0.5, 0.0, 1.0, 0.0],
+ "VEC3",
+ 3,
+ min=[-0.5, 0.0, -0.5],
+ max=[0.5, 1.0, 0.5],
+ )
+
+ nodes: list[dict[str, Any]] = []
+ for index in sorted(NODE_LAYOUT):
+ name, translation, children = NODE_LAYOUT[index]
+ node: dict[str, Any] = {"name": name, "translation": list(translation)}
+ if children:
+ node["children"] = list(children)
+ nodes.append(node)
+ nodes[7]["mesh"] = 0
+ nodes[7]["skin"] = 0
+
+ skins: list[dict[str, Any]] = [{"name": "skin_0", "joints": list(skin_joints)}]
+ if inverse_binds:
+ # Each matrix encodes the node index of the joint it belongs to, so an index-for-index
+ # check has something to catch. (A real inverse bind is the inverse world bind matrix;
+ # this stands in for one because the module under test only pairs, never interprets.)
+ flat: list[float] = []
+ for node_index in skin_joints:
+ flat.extend(translation_matrix(node_index * 100.0, 0.0, 0.0))
+ skins[0]["inverseBindMatrices"] = chunk.add(flat, "MAT4", len(skin_joints))
+ if extra_skin_joints is not None:
+ skins.append({"name": "skin_1", "joints": list(extra_skin_joints)})
+
+ animation_records: list[dict[str, Any]] = []
+ for animation in animations or []:
+ samplers: list[dict[str, Any]] = []
+ channels: list[dict[str, Any]] = []
+ for spec in animation["channels"]:
+ times = list(spec["times"])
+ values = list(spec["values"])
+ element_type = {"translation": "VEC3", "scale": "VEC3", "rotation": "VEC4"}[spec["path"]]
+ components = 4 if element_type == "VEC4" else 3
+ input_accessor = chunk.add(times, "SCALAR", len(times), min=[min(times)], max=[max(times)])
+ output_accessor = chunk.add(values, element_type, len(values) // components)
+ samplers.append(
+ {
+ "input": input_accessor,
+ "output": output_accessor,
+ "interpolation": spec.get("interpolation", "LINEAR"),
+ }
+ )
+ channels.append(
+ {"sampler": len(samplers) - 1, "target": {"node": spec["node"], "path": spec["path"]}}
+ )
+ animation_records.append(
+ {"name": animation["name"], "samplers": samplers, "channels": channels}
+ )
+
+ document: dict[str, Any] = {
+ "asset": {"version": "2.0", "generator": "test_glb_rig_reference"},
+ "scene": 0,
+ "scenes": [{"nodes": [0]}],
+ "nodes": nodes,
+ "meshes": [{"name": "body", "primitives": [{"attributes": {"POSITION": positions}}]}],
+ "skins": skins,
+ "buffers": [{"byteLength": len(chunk.data)}],
+ "bufferViews": chunk.views,
+ "accessors": chunk.accessors,
+ }
+ if animation_records:
+ document["animations"] = animation_records
+ path.write_bytes(pack_glb(document, bytes(chunk.data)))
+ return path
+
+
+def hip_walk_animation(name: str = "clip_walk") -> dict[str, Any]:
+ """Hip slides 1.0H forward in x over one second -- travel 1.0H, speed 1.0 H/s."""
+ return {
+ "name": name,
+ "channels": [
+ {
+ "node": 1,
+ "path": "translation",
+ "times": [0.0, 1.0],
+ "values": [0.0, 0.5, 0.0, 1.0, 0.5, 0.0],
+ }
+ ],
+ }
+
+
+class GlbFixtureMixin:
+ def setUp(self) -> None: # noqa: D102
+ self._tmp = tempfile.TemporaryDirectory()
+ self.tmp = Path(self._tmp.name)
+ self.addCleanup(self._tmp.cleanup)
+
+ def write(self, **kwargs: Any) -> Path:
+ name = kwargs.pop("name", "rig.glb")
+ return build_glb(self.tmp / name, **kwargs)
+
+
+# ---------------------------------------------------------------------------------------------
+# The defect
+# ---------------------------------------------------------------------------------------------
+
+
+class TheSkinOrderDefect(GlbFixtureMixin, unittest.TestCase):
+ """§R0.3: bones[i] is the node for skin.joints[i]. The ordering is the skin's, never the
+ traversal's. This is the mechanism behind a mesh that comes out disjointed, so it is asserted
+ from both sides: what the reader returns, and what the wrong reading would have returned."""
+
+ def test_joints_are_returned_in_skin_order_and_traversal_order_would_be_wrong(self) -> None:
+ rig = read_rig(self.write())
+
+ returned = [joint.node_index for joint in rig.joints]
+ self.assertEqual(returned, SKIN_JOINTS, "joints must come back in skin.joints order")
+ self.assertEqual(
+ [joint.skin_joint_index for joint in rig.joints],
+ list(range(len(SKIN_JOINTS))),
+ "skinJointIndex must be the slot in skin.joints, densely and in order",
+ )
+
+ # The wrong reading, spelled out: a depth-first walk of the same joint nodes.
+ self.assertNotEqual(
+ returned,
+ TRAVERSAL_ORDER,
+ "the fixture must actually differ from traversal order or this test proves nothing",
+ )
+ # Every slot where the two orders disagree is a bone that would deform the wrong vertices.
+ disagreements = [
+ slot for slot, node_index in enumerate(returned) if node_index != TRAVERSAL_ORDER[slot]
+ ]
+ self.assertEqual(len(disagreements), 6)
+ self.assertEqual(
+ rig.to_dict()["skins"][0]["jointOrder"],
+ "skin.joints (§R0.3: the ordering is the skin's, never the traversal's)",
+ )
+
+ def test_joint_node_names_are_never_used_to_order_or_identify(self) -> None:
+ rig = read_rig(self.write())
+ # Exporter names carry no anatomy. The reader keeps them verbatim and orders by the skin.
+ self.assertEqual(
+ [joint.node_name for joint in rig.joints],
+ [f"node_{index}" for index in SKIN_JOINTS],
+ )
+
+
+class InverseBindPairing(GlbFixtureMixin, unittest.TestCase):
+ def test_inverse_bind_matrices_align_index_for_index_with_skin_joints(self) -> None:
+ rig = read_rig(self.write())
+ self.assertEqual(len(rig.inverse_bind_matrices), len(rig.joints))
+ for joint, matrix in zip(rig.joints, rig.inverse_bind_matrices):
+ # The fixture encodes the joint's node index in the matrix's translation.
+ self.assertAlmostEqual(matrix[12], joint.node_index * 100.0, places=4)
+ self.assertEqual(rig.inverse_bind_source, "accessor:1")
+
+ def test_an_omitted_accessor_is_reported_not_silently_filled(self) -> None:
+ rig = read_rig(self.write(inverse_binds=False, name="no-ibm.glb"))
+ self.assertEqual(rig.inverse_bind_source, INVERSE_BIND_OMITTED)
+ # glTF says identity, so identity is what is returned -- but the provenance says which.
+ self.assertEqual(len(rig.inverse_bind_matrices), len(SKIN_JOINTS))
+ for matrix in rig.inverse_bind_matrices:
+ self.assertEqual(list(matrix), [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])
+ self.assertEqual(rig.to_dict()["inverseBindSource"], INVERSE_BIND_OMITTED)
+
+
+class DeformVersusTechnical(GlbFixtureMixin, unittest.TestCase):
+ """§R0.1: a node is a Bone IFF it appears in skin.joints. Clips target technical nodes too."""
+
+ def test_channels_targeting_non_joint_nodes_are_counted_and_named(self) -> None:
+ path = self.write(
+ animations=[
+ {
+ "name": "clip_mixed",
+ "channels": [
+ # node 1 is in skin.joints; node 0 (the container) is not.
+ {"node": 1, "path": "translation", "times": [0.0, 1.0],
+ "values": [0.0, 0.5, 0.0, 0.0, 0.6, 0.0]},
+ {"node": 0, "path": "translation", "times": [0.0, 1.0],
+ "values": [0.0, 0.0, 0.0, 0.0, 0.0, 1.0]},
+ ],
+ }
+ ]
+ )
+ rig = read_rig(path)
+ report = rig.deform_vs_technical
+ self.assertEqual(report["status"], "evaluated")
+ self.assertEqual(report["channelsTargetingJoints"], 1)
+ self.assertEqual(report["channelsTargetingTechnicalNodes"], 1)
+ self.assertEqual([entry["nodeIndex"] for entry in report["technicalNodes"]], [0])
+ self.assertEqual([entry["nodeIndex"] for entry in report["deformNodes"]], [1])
+ self.assertTrue(
+ any("corrupts the skeleton's index space" in warning for warning in rig.warnings),
+ rig.warnings,
+ )
+
+ def test_with_no_skin_the_classification_is_unevaluated_not_a_pass(self) -> None:
+ # A GLB with clips but no skin has no membership test to run. CONTRACT_1.5.2: an absent
+ # input reports `unevaluated`, never silently a pass.
+ chunk = BinChunk()
+ positions = chunk.add(
+ [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], "VEC3", 3,
+ min=[0.0, 0.0, 0.0], max=[1.0, 1.0, 0.0],
+ )
+ times = chunk.add([0.0, 1.0], "SCALAR", 2, min=[0.0], max=[1.0])
+ values = chunk.add([0.0, 0.0, 0.0, 0.0, 1.0, 0.0], "VEC3", 2)
+ document = {
+ "asset": {"version": "2.0"},
+ "scene": 0,
+ "scenes": [{"nodes": [0]}],
+ "nodes": [{"name": "node_0", "mesh": 0}],
+ "meshes": [{"primitives": [{"attributes": {"POSITION": positions}}]}],
+ "animations": [
+ {
+ "name": "clip_static",
+ "samplers": [{"input": times, "output": values, "interpolation": "LINEAR"}],
+ "channels": [{"sampler": 0, "target": {"node": 0, "path": "translation"}}],
+ }
+ ],
+ "buffers": [{"byteLength": len(chunk.data)}],
+ "bufferViews": chunk.views,
+ "accessors": chunk.accessors,
+ }
+ path = self.tmp / "skinless.glb"
+ path.write_bytes(pack_glb(document, bytes(chunk.data)))
+ rig = read_rig(path)
+ self.assertEqual(rig.deform_vs_technical["status"], "unevaluated")
+ self.assertIsNone(rig.deform_vs_technical["channelsTargetingTechnicalNodes"])
+ self.assertIn("no skin", rig.deform_vs_technical["reason"])
+ self.assertIsNotNone(rig.structural_failure)
+
+
+class MultipleSkins(GlbFixtureMixin, unittest.TestCase):
+ def test_two_skins_leave_no_primary_and_nothing_is_guessed(self) -> None:
+ rig = read_rig(self.write(extra_skin_joints=[3, 4], name="two-skins.glb"))
+ self.assertEqual(len(rig.skins), 2)
+ self.assertIsNone(rig.primary_skin)
+ self.assertEqual(rig.joints, ())
+ self.assertEqual(rig.inverse_bind_matrices, ())
+ self.assertIn("2 skins", rig.structural_failure or "")
+ # Both skins are still reported in full -- refusing to choose is not refusing to read.
+ self.assertEqual([skin.skin_index for skin in rig.skins], [0, 1])
+ self.assertEqual([joint.node_index for joint in rig.skins[1].joints], [3, 4])
+
+ def test_the_cli_exits_1_on_multiple_skins(self) -> None:
+ path = self.write(extra_skin_joints=[3, 4], name="two-skins.glb")
+ buffer = io.StringIO()
+ with redirect_stdout(buffer):
+ code = main([str(path)])
+ self.assertEqual(code, 1)
+ result = json.loads(buffer.getvalue())
+ self.assertFalse(result["ok"])
+ self.assertIsNone(result["primarySkinIndex"])
+ self.assertEqual(result["joints"], [])
+ self.assertTrue(any("skins" in error for error in result["errors"]), result["errors"])
+
+ def test_naming_one_skin_makes_the_cli_succeed(self) -> None:
+ path = self.write(extra_skin_joints=[3, 4], name="two-skins.glb")
+ buffer = io.StringIO()
+ with redirect_stdout(buffer):
+ code = main([str(path), "--skin", "0"])
+ self.assertEqual(code, 0)
+ result = json.loads(buffer.getvalue())
+ self.assertEqual(result["primarySkinIndex"], 0)
+ self.assertEqual([joint["nodeIndex"] for joint in result["joints"]], SKIN_JOINTS)
+
+ def test_the_cli_exits_1_when_the_glb_has_no_skin(self) -> None:
+ chunk = BinChunk()
+ positions = chunk.add(
+ [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0], "VEC3", 3,
+ min=[0.0, 0.0, 0.0], max=[1.0, 1.0, 0.0],
+ )
+ document = {
+ "asset": {"version": "2.0"},
+ "scene": 0,
+ "scenes": [{"nodes": [0]}],
+ "nodes": [{"name": "node_0", "mesh": 0}],
+ "meshes": [{"primitives": [{"attributes": {"POSITION": positions}}]}],
+ "buffers": [{"byteLength": len(chunk.data)}],
+ "bufferViews": chunk.views,
+ "accessors": chunk.accessors,
+ }
+ path = self.tmp / "skinless.glb"
+ path.write_bytes(pack_glb(document, bytes(chunk.data)))
+ buffer = io.StringIO()
+ with redirect_stdout(buffer):
+ code = main([str(path)])
+ self.assertEqual(code, 1)
+ self.assertIn("no skin", json.loads(buffer.getvalue())["errors"][0])
+
+
+# ---------------------------------------------------------------------------------------------
+# Correspondence
+# ---------------------------------------------------------------------------------------------
+
+
+def bones_at_joints(offset: dict[int, tuple[float, float, float]] | None = None) -> list[dict[str, Any]]:
+ """Procedural bones with real anatomical ids, sitting on the GLB's measured joint positions."""
+ labels = {1: "hip", 2: "head", 3: "upper-arm-l", 4: "upper-arm-r", 5: "foot-l", 6: "foot-r"}
+ offset = offset or {}
+ bones = []
+ for node_index, label in labels.items():
+ base = JOINT_WORLD[node_index]
+ shift = offset.get(node_index, (0.0, 0.0, 0.0))
+ bones.append({"id": label, "position": [base[i] + shift[i] for i in range(3)]})
+ return bones
+
+
+class CorrespondenceTests(GlbFixtureMixin, unittest.TestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.rig = read_rig(self.write())
+
+ def test_the_fixtures_rest_positions_are_what_the_layout_says(self) -> None:
+ positions = joint_rest_positions(self.rig)
+ for joint in self.rig.joints:
+ for axis in range(3):
+ self.assertAlmostEqual(
+ positions[joint.skin_joint_index][axis], JOINT_WORLD[joint.node_index][axis], places=6
+ )
+
+ def test_a_bone_0_01H_away_matches_and_one_0_20H_away_does_not(self) -> None:
+ near = correspondence(self.rig, bones_at_joints({1: (0.01, 0.0, 0.0)}), figure_height=1.0)
+ hip = next(match for match in near.matches if match.bone_id == "hip")
+ self.assertEqual(hip.node_index, 1)
+ self.assertAlmostEqual(hip.distance_h, 0.01, places=6)
+ self.assertAlmostEqual(hip.confidence, 0.8, places=6)
+ self.assertTrue(near.usable, near.reason)
+
+ far = correspondence(self.rig, bones_at_joints({1: (0.20, 0.0, 0.0)}), figure_height=1.0)
+ hip = next(match for match in far.matches if match.bone_id == "hip")
+ self.assertIsNone(hip.node_index)
+ self.assertIsNone(hip.distance_h)
+ self.assertEqual(hip.confidence, 0.0)
+ self.assertIn(f"{CORRESPONDENCE_TOLERANCE}H", hip.reason)
+
+ def test_an_unmatched_procedural_bone_makes_it_unusable_with_a_stated_reason(self) -> None:
+ bones = bones_at_joints() + [{"id": "tail-tip", "position": [0.0, -5.0, 0.0]}]
+ result = correspondence(self.rig, bones, figure_height=1.0)
+ self.assertFalse(result.usable)
+ self.assertEqual(result.unmatched_procedural_bones, ("tail-tip",))
+ self.assertIn("tail-tip", result.reason)
+ self.assertIn("not usable for retargeting", result.reason)
+
+ def test_an_unmatched_glb_joint_makes_it_unusable_with_a_stated_reason(self) -> None:
+ bones = [bone for bone in bones_at_joints() if bone["id"] != "foot-r"]
+ result = correspondence(self.rig, bones, figure_height=1.0)
+ self.assertFalse(result.usable)
+ self.assertEqual(result.unmatched_procedural_bones, ())
+ self.assertEqual([joint["nodeIndex"] for joint in result.unmatched_glb_joints], [6])
+ self.assertIn("node_6", result.reason)
+ self.assertIn("not usable for retargeting", result.reason)
+
+ def test_correspondence_never_matches_by_name(self) -> None:
+ bones = bones_at_joints()
+ glb_names = {joint.node_name for joint in self.rig.joints}
+ bone_ids = {str(bone["id"]) for bone in bones}
+ self.assertEqual(
+ glb_names & bone_ids,
+ set(),
+ "the fixture must share no name between the two rigs or this proves nothing",
+ )
+ result = correspondence(self.rig, bones, figure_height=1.0)
+ self.assertTrue(result.usable, result.reason)
+ self.assertEqual(
+ {match.bone_id: match.node_name for match in result.matches},
+ {
+ "hip": "node_1",
+ "head": "node_2",
+ "upper-arm-l": "node_3",
+ "upper-arm-r": "node_4",
+ "foot-l": "node_5",
+ "foot-r": "node_6",
+ },
+ )
+ self.assertEqual(result.to_dict()["matchedBy"], "measured model-space position (never node names)")
+
+ def test_two_bones_cannot_claim_the_same_glb_joint(self) -> None:
+ bones = bones_at_joints() + [{"id": "hip-duplicate", "position": [0.001, 0.5, 0.0]}]
+ result = correspondence(self.rig, bones, figure_height=1.0)
+ claimed = [match.skin_joint_index for match in result.matches if match.skin_joint_index is not None]
+ self.assertEqual(len(claimed), len(set(claimed)))
+ self.assertIn("hip-duplicate", result.unmatched_procedural_bones)
+ self.assertFalse(result.usable)
+
+ def test_figure_height_is_measured_from_the_file_when_not_supplied(self) -> None:
+ height, source = derive_figure_height(self.rig)
+ self.assertAlmostEqual(height, 1.0, places=6)
+ self.assertEqual(source, "meshPositionBoundsYExtent")
+ result = correspondence(self.rig, bones_at_joints())
+ self.assertAlmostEqual(result.figure_height, 1.0, places=6)
+
+ def test_no_primary_skin_means_no_correspondence_and_a_reason(self) -> None:
+ rig = read_rig(self.write(extra_skin_joints=[3, 4], name="two-skins.glb"))
+ result = correspondence(rig, bones_at_joints(), figure_height=1.0)
+ self.assertFalse(result.usable)
+ self.assertIn("skins", result.reason)
+ self.assertEqual(len(result.unmatched_procedural_bones), 6)
+
+
+# ---------------------------------------------------------------------------------------------
+# Sampling: the handoff into clip_features IS the deliverable
+# ---------------------------------------------------------------------------------------------
+
+
+class SampledClipHandoff(GlbFixtureMixin, unittest.TestCase):
+ def test_the_payload_is_accepted_by_clip_features_and_measures(self) -> None:
+ rig = read_rig(self.write(animations=[hip_walk_animation()]))
+ payload = sample_clips(rig, LANDMARK_NODES)
+
+ loaded = clip_features.load_payload(payload)
+ self.assertAlmostEqual(loaded["figureHeight"], 1.0, places=6)
+ self.assertEqual(len(loaded["clips"]), 1)
+
+ features = clip_features.measure_clip(loaded["clips"][0], loaded["figureHeight"])
+ self.assertEqual(features.sample_count, 25)
+ self.assertAlmostEqual(features.duration, 1.0, places=6)
+ self.assertAlmostEqual(features.travel, 1.0, places=6)
+ self.assertAlmostEqual(features.speed, 1.0, places=6)
+ self.assertAlmostEqual(features.rise, 0.0, places=9)
+ self.assertFalse(features.scales_joints)
+ self.assertEqual(clip_features.classify(features).primary, "run")
+ self.assertEqual(features.source_name, "clip_walk")
+
+ def test_the_payload_carries_its_own_provenance(self) -> None:
+ rig = read_rig(self.write(animations=[hip_walk_animation()]))
+ payload = sample_clips(rig, LANDMARK_NODES, sample_count=7)
+ self.assertEqual(len(payload["clips"][0]["sampleTimes"]), 7)
+ self.assertEqual(payload["provenance"]["jointCount"], 6)
+ self.assertEqual(payload["provenance"]["figureHeightSource"], "meshPositionBoundsYExtent")
+ self.assertNotIn("stance", payload["clips"][0])
+ self.assertIn("omitted", payload["provenance"]["stance"])
+
+ def test_missing_landmarks_are_refused_before_a_payload_is_built(self) -> None:
+ rig = read_rig(self.write(animations=[hip_walk_animation()]))
+ partial = {name: index for name, index in LANDMARK_NODES.items() if name != "foot.r"}
+ with self.assertRaises(ValueError) as caught:
+ sample_clips(rig, partial)
+ self.assertIn("foot.r", str(caught.exception))
+
+ def test_joint_scale_delta_reports_a_scaling_rig(self) -> None:
+ # §1: scaleDelta is a tripwire. A rig that scales joints must be surfaced before anything
+ # else proceeds, so it has to reach the payload as a real number.
+ rig = read_rig(
+ self.write(
+ animations=[
+ {
+ "name": "clip_scale",
+ "channels": [
+ {
+ "node": 1,
+ "path": "scale",
+ "times": [0.0, 1.0],
+ "values": [1.0, 1.0, 1.0, 1.25, 1.0, 1.0],
+ }
+ ],
+ }
+ ]
+ )
+ )
+ payload = sample_clips(rig, LANDMARK_NODES, sample_count=5)
+ self.assertAlmostEqual(max(payload["clips"][0]["jointScaleDelta"]), 0.25, places=6)
+ features = clip_features.measure_clip(
+ clip_features.load_payload(payload)["clips"][0], 1.0
+ )
+ self.assertTrue(features.scales_joints)
+
+
+class Interpolation(GlbFixtureMixin, unittest.TestCase):
+ def _hip_x(self, interpolation: str) -> list[float]:
+ rig = read_rig(
+ self.write(
+ animations=[
+ {
+ "name": f"clip_{interpolation.lower()}",
+ "channels": [
+ {
+ "node": 1,
+ "path": "translation",
+ "times": [0.0, 1.0],
+ "values": [0.0, 0.5, 0.0, 2.0, 0.5, 0.0],
+ "interpolation": interpolation,
+ }
+ ],
+ }
+ ],
+ name=f"{interpolation}.glb",
+ )
+ )
+ payload = sample_clips(rig, LANDMARK_NODES, sample_count=3)
+ return [point[0] for point in payload["clips"][0]["landmarkPositions"]["hip"]]
+
+ def test_step_holds_its_value_between_keys_and_linear_interpolates(self) -> None:
+ step = self._hip_x("STEP")
+ linear = self._hip_x("LINEAR")
+ self.assertEqual(step[0], 0.0)
+ self.assertEqual(step[1], 0.0, "STEP must hold the previous key's value at t = 0.5")
+ self.assertAlmostEqual(step[2], 2.0, places=6)
+ self.assertAlmostEqual(linear[1], 1.0, places=6, msg="LINEAR must interpolate at t = 0.5")
+ self.assertNotAlmostEqual(step[1], linear[1], places=3)
+
+ def test_the_rotation_path_uses_slerp_not_a_normalised_lerp(self) -> None:
+ # A 170-degree arc sampled at t = 0.25, where slerp and nlerp visibly disagree. (At t = 0.5
+ # they coincide by symmetry, which is why the quarter point is the honest place to look.)
+ start = (0.0, 0.0, 0.0, 1.0)
+ end = quat_z(170.0)
+ rig = read_rig(
+ self.write(
+ animations=[
+ {
+ "name": "clip_turn",
+ "channels": [
+ {
+ "node": 1,
+ "path": "rotation",
+ "times": [0.0, 1.0],
+ "values": list(start) + list(end),
+ }
+ ],
+ }
+ ],
+ name="turn.glb",
+ )
+ )
+ payload = sample_clips(rig, LANDMARK_NODES, sample_count=5)
+ head = payload["clips"][0]["landmarkPositions"]["head"][1] # t = 0.25
+
+ def head_position(q: Sequence[float]) -> tuple[float, float]:
+ # Every rotation here is about Z, so the angle reads straight off the quaternion.
+ # The head sits at local (0, 0.4, 0) under the hip at world (0, 0.5, 0).
+ angle = 2.0 * math.atan2(q[2], q[3])
+ return (-0.4 * math.sin(angle), 0.5 + 0.4 * math.cos(angle))
+
+ expected_slerp = head_position(slerp(start, end, 0.25))
+ expected_nlerp = head_position(nlerp(start, end, 0.25))
+ self.assertAlmostEqual(head[0], expected_slerp[0], places=6)
+ self.assertAlmostEqual(head[1], expected_slerp[1], places=6)
+ self.assertGreater(
+ abs(expected_slerp[0] - expected_nlerp[0]),
+ 0.01,
+ "the fixture must put slerp and nlerp measurably apart or this proves nothing",
+ )
+ self.assertGreater(abs(head[0] - expected_nlerp[0]), 0.01)
+
+ def test_slerp_and_nlerp_disagree_on_the_arc_this_module_cares_about(self) -> None:
+ start = (0.0, 0.0, 0.0, 1.0)
+ end = quat_z(170.0)
+ a = slerp(start, end, 0.25)
+ b = nlerp(start, end, 0.25)
+ angle_a = math.degrees(2.0 * math.atan2(a[2], a[3]))
+ angle_b = math.degrees(2.0 * math.atan2(b[2], b[3]))
+ self.assertAlmostEqual(angle_a, 42.5, places=4)
+ self.assertGreater(abs(angle_a - angle_b), 5.0)
+
+ def test_cubicspline_is_reported_unsupported_and_never_read_as_linear(self) -> None:
+ start = [0.0, 0.5, 0.0]
+ end = [2.0, 0.5, 0.0]
+ # CUBICSPLINE output is [inTangent, value, outTangent] per key.
+ values = [0.0, 0.0, 0.0] + start + [0.0, 0.0, 0.0] + [0.0, 0.0, 0.0] + end + [0.0, 0.0, 0.0]
+ rig = read_rig(
+ self.write(
+ animations=[
+ {
+ "name": "clip_spline",
+ "channels": [
+ {
+ "node": 1,
+ "path": "translation",
+ "times": [0.0, 1.0],
+ "values": values,
+ "interpolation": "CUBICSPLINE",
+ }
+ ],
+ }
+ ],
+ name="spline.glb",
+ )
+ )
+ # Visible from `read_rig` alone, before anyone asks for samples.
+ self.assertEqual(rig.unsupported_interpolation_clips, ("clip_spline",))
+ self.assertEqual(rig.clips[0].channels[0].interpolation, "CUBICSPLINE")
+
+ with self.assertRaises(UnsupportedInterpolation) as caught:
+ sample_clips(rig, LANDMARK_NODES)
+ self.assertEqual(caught.exception.clip_name, "clip_spline")
+ self.assertEqual(caught.exception.interpolation, "CUBICSPLINE")
+ self.assertIn("rather than approximated as LINEAR", str(caught.exception))
+
+ def test_the_cli_exits_1_when_sampling_hits_cubicspline(self) -> None:
+ values = [0.0] * 3 + [0.0, 0.5, 0.0] + [0.0] * 6 + [2.0, 0.5, 0.0] + [0.0] * 3
+ path = self.write(
+ animations=[
+ {
+ "name": "clip_spline",
+ "channels": [
+ {
+ "node": 1,
+ "path": "translation",
+ "times": [0.0, 1.0],
+ "values": values,
+ "interpolation": "CUBICSPLINE",
+ }
+ ],
+ }
+ ],
+ name="spline.glb",
+ )
+ buffer = io.StringIO()
+ with redirect_stdout(buffer):
+ code = main([str(path), "--sample-clips", "--landmarks", json.dumps(LANDMARK_NODES)])
+ self.assertEqual(code, 1)
+ result = json.loads(buffer.getvalue())
+ self.assertFalse(result["ok"])
+ self.assertNotIn("sampledClips", result)
+ self.assertTrue(any("CUBICSPLINE" in error for error in result["errors"]), result["errors"])
+
+
+class PoseReturn(GlbFixtureMixin, unittest.TestCase):
+ """§4: the loop rule needs a measured poseReturn, not a guess. Both directions are asserted."""
+
+ def _pose_return(self, keys: Sequence[Sequence[float]], times: Sequence[float]) -> float:
+ flat: list[float] = []
+ for key in keys:
+ flat.extend(key)
+ rig = read_rig(
+ self.write(
+ animations=[
+ {
+ "name": "clip_pose",
+ "channels": [
+ {"node": 1, "path": "rotation", "times": list(times), "values": flat}
+ ],
+ }
+ ],
+ name=f"pose-{len(keys)}.glb",
+ )
+ )
+ payload = sample_clips(rig, LANDMARK_NODES)
+ return payload["clips"][0]["poseReturn"]
+
+ def test_a_clip_whose_last_key_equals_its_first_returns_about_zero_degrees(self) -> None:
+ identity = (0.0, 0.0, 0.0, 1.0)
+ value = self._pose_return([identity, quat_z(90.0), identity], [0.0, 0.5, 1.0])
+ self.assertLess(value, clip_features.POSE_RETURN_DEGREES)
+ self.assertAlmostEqual(value, 0.0, places=6)
+
+ def test_a_clip_ending_mid_rotation_does_not(self) -> None:
+ identity = (0.0, 0.0, 0.0, 1.0)
+ value = self._pose_return([identity, quat_z(90.0)], [0.0, 1.0])
+ self.assertAlmostEqual(value, 90.0, places=4)
+ self.assertGreater(value, clip_features.POSE_RETURN_DEGREES)
+
+ def test_the_loop_rule_can_actually_decide_with_this_payload(self) -> None:
+ # Without poseReturn the rule reports `loop: null`. The point of measuring it is that the
+ # decision becomes decidable at all.
+ rig = read_rig(self.write(animations=[hip_walk_animation()]))
+ payload = sample_clips(rig, LANDMARK_NODES)
+ loaded = clip_features.load_payload(payload)
+ features = clip_features.measure_clip(loaded["clips"][0], loaded["figureHeight"])
+ self.assertIsNotNone(features.pose_return)
+ decision = clip_features.decide_loop(features)
+ self.assertIsNotNone(decision.loop)
+
+
+class ClipRecords(GlbFixtureMixin, unittest.TestCase):
+ def test_clip_duration_is_the_largest_channel_time_max(self) -> None:
+ rig = read_rig(
+ self.write(
+ animations=[
+ {
+ "name": "clip_two_channels",
+ "channels": [
+ {"node": 1, "path": "translation", "times": [0.0, 0.5],
+ "values": [0.0, 0.5, 0.0, 0.0, 0.6, 0.0]},
+ {"node": 2, "path": "translation", "times": [0.0, 2.25],
+ "values": [0.0, 0.4, 0.0, 0.0, 0.5, 0.0]},
+ ],
+ }
+ ]
+ )
+ )
+ clip = rig.clips[0]
+ self.assertAlmostEqual(clip.duration, 2.25, places=6)
+ self.assertEqual([channel.key_count for channel in clip.channels], [2, 2])
+ self.assertEqual([channel.path for channel in clip.channels], ["translation", "translation"])
+ self.assertEqual([channel.target_node_index for channel in clip.channels], [1, 2])
+ self.assertAlmostEqual(clip.channels[1].time_max, 2.25, places=6)
+
+ def test_skinned_mesh_nodes_are_the_nodes_carrying_both_mesh_and_skin(self) -> None:
+ rig = read_rig(self.write())
+ self.assertEqual(
+ list(rig.skinned_mesh_nodes),
+ [{"nodeIndex": 7, "nodeName": "node_7", "meshIndex": 0, "skinIndex": 0}],
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_mesh_parity.py b/forge/tests/test_mesh_parity.py
new file mode 100644
index 0000000..3458735
--- /dev/null
+++ b/forge/tests/test_mesh_parity.py
@@ -0,0 +1,527 @@
+#!/usr/bin/env python3
+"""Tests for the mesh freeze/parity gate, built around the defect it exists to catch.
+
+`TheDefectThisCatches.test_one_nudged_vertex_is_caught_and_located` is the whole argument for the
+module: it moves a SINGLE float in a SINGLE position buffer -- the smallest possible version of "the
+animation pipeline broke the mesh" -- and requires the gate not merely to fail but to say which
+mesh, which attribute, which element, and what the value was before and after. A gate that only says
+"something changed" would not have shortened a single one of the investigations this module exists
+to end.
+
+The other load-bearing test is `LegalAdditions`: adding skinIndex and skinWeight between freeze and
+verify must PASS. If it did not, the gate would fail every successful rig and would be turned off
+within a day, so that test defends the design decision as hard as the failure test defends the
+mechanism.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import dataclasses
+import io
+import json
+import random
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage5_rig"))
+
+from mesh_parity import ( # noqa: E402
+ FROZEN_ATTRIBUTES,
+ FROZEN_BUFFERS,
+ INDEX_KEY,
+ KIND_ATTRIBUTE_ADDED,
+ KIND_ATTRIBUTE_MISSING,
+ KIND_COUNT,
+ KIND_DUPLICATE,
+ KIND_HASH,
+ KIND_MESH_ADDED,
+ KIND_MESH_MISSING,
+ SCHEMA_VERSION,
+ STATUS_FAIL,
+ STATUS_PASS,
+ STATUS_UNEVALUATED,
+ Manifest,
+ ParityReport,
+ freeze,
+ main,
+ verify,
+)
+
+
+def cube(name: str, origin: float = 0.0) -> dict:
+ """One small closed mesh: 8 positions, 8 normals, 8 uvs, 36 indices.
+
+ Small enough to reason about by hand and large enough that a single changed float is genuinely
+ lost in the buffer unless something points at it.
+ """
+ corners = [
+ (x, y, z) for x in (0.0, 1.0) for y in (0.0, 1.0) for z in (0.0, 1.0)
+ ]
+ position: list[float] = []
+ normal: list[float] = []
+ uv: list[float] = []
+ for x, y, z in corners:
+ position.extend([x + origin, y, z])
+ normal.extend([x - 0.5, y - 0.5, z - 0.5])
+ uv.extend([x, y])
+ index = [
+ 0, 1, 3, 0, 3, 2, 4, 6, 7, 4, 7, 5, 0, 4, 5, 0, 5, 1,
+ 2, 3, 7, 2, 7, 6, 0, 2, 6, 0, 6, 4, 1, 5, 7, 1, 7, 3,
+ ]
+ return {
+ "name": name,
+ "attributes": {"position": position, "normal": normal, "uv": uv},
+ INDEX_KEY: index,
+ }
+
+
+def payload(*names: str) -> dict:
+ """A fresh payload every call; nothing here is shared between tests."""
+ chosen = names or ("torso", "arm")
+ return {"meshes": [cube(name, origin=offset) for offset, name in enumerate(chosen)]}
+
+
+def mesh_of(document: dict, name: str) -> dict:
+ for mesh in document["meshes"]:
+ if mesh["name"] == name:
+ return mesh
+ raise AssertionError(f"no mesh named {name!r} in the payload")
+
+
+def failures_of(report: ParityReport, kind: str) -> list:
+ return [failure for failure in report.failures if failure.kind == kind]
+
+
+class TheDefectThisCatches(unittest.TestCase):
+ """One vertex moved during the animation pass. The reason this module exists."""
+
+ def test_the_gate_passes_the_geometry_it_froze(self) -> None:
+ # A gate that fails everything proves nothing about the thing it failed, so this comes
+ # first: the unchanged payload must pass, cleanly and with the meshes actually compared.
+ document = payload()
+ report = verify(freeze(document), document)
+ self.assertTrue(report.ok, report.summary())
+ self.assertEqual(report.status, STATUS_PASS)
+ self.assertEqual(report.failure_count, 0)
+ self.assertEqual(report.meshes_compared, 2)
+
+ def test_one_nudged_vertex_is_caught_and_located(self) -> None:
+ document = payload()
+ manifest = freeze(document)
+
+ broken = payload()
+ moved = mesh_of(broken, "arm")
+ original = moved["attributes"]["position"][13]
+ moved["attributes"]["position"][13] = original + 1e-6
+
+ report = verify(manifest, broken)
+
+ self.assertFalse(report.ok)
+ self.assertEqual(report.status, STATUS_FAIL)
+ self.assertEqual(report.failure_count, 1, report.summary())
+
+ failure = report.failures[0]
+ self.assertEqual(failure.mesh, "arm")
+ self.assertEqual(failure.attribute, "position")
+ self.assertEqual(failure.kind, KIND_HASH)
+
+ # Naming the mesh and the attribute is not enough. A 24-float buffer -- or a 200k-float one
+ # -- needs the element, or the reader is back to diffing numbers by eye.
+ self.assertEqual(failure.differing_elements, 1)
+ self.assertEqual(len(failure.differences), 1)
+ difference = failure.differences[0]
+ self.assertEqual(difference.index, 13)
+ self.assertEqual(difference.frozen, original)
+ self.assertEqual(difference.current, original + 1e-6)
+ self.assertIn("13", failure.detail)
+ self.assertIn("arm", report.summary())
+ self.assertIn("position", report.summary())
+
+ def test_the_untouched_mesh_in_the_same_payload_is_not_implicated(self) -> None:
+ # Blaming the whole model for one bad buffer is how a gate loses its audience.
+ manifest = freeze(payload())
+ broken = payload()
+ mesh_of(broken, "arm")["attributes"]["position"][0] += 0.5
+ report = verify(manifest, broken)
+ self.assertEqual({failure.mesh for failure in report.failures}, {"arm"})
+
+ def test_a_wholesale_rebuild_reads_differently_from_a_nudge(self) -> None:
+ # The differing-element count is the difference between "someone moved a vertex" and
+ # "someone regenerated the limb", which are different bugs with different owners.
+ manifest = freeze(payload())
+ rebuilt = payload()
+ mesh = mesh_of(rebuilt, "arm")
+ mesh["attributes"]["position"] = [
+ value * 1.5 + 0.01 for value in mesh["attributes"]["position"]
+ ]
+ report = verify(manifest, rebuilt)
+ failure = failures_of(report, KIND_HASH)[0]
+ self.assertEqual(failure.differing_elements, 24)
+ # The list of reported differences is capped; the count is not.
+ self.assertLessEqual(len(failure.differences), failure.differing_elements)
+
+
+class LegalAdditions(unittest.TestCase):
+ """Adding skinIndex/skinWeight is the entire point of the implementation phase."""
+
+ def test_adding_skin_attributes_between_freeze_and_verify_passes(self) -> None:
+ document = payload()
+ manifest = freeze(document)
+
+ rigged = payload()
+ for mesh in rigged["meshes"]:
+ vertices = len(mesh["attributes"]["position"]) // 3
+ mesh["attributes"]["skinIndex"] = [0, 1, 0, 0] * vertices
+ mesh["attributes"]["skinWeight"] = [0.6, 0.4, 0.0, 0.0] * vertices
+
+ report = verify(manifest, rigged)
+
+ self.assertTrue(report.ok, report.summary())
+ self.assertEqual(report.status, STATUS_PASS)
+ self.assertEqual(report.failure_count, 0)
+ # And they are listed, not merely tolerated: a rig that silently added nothing and a rig
+ # that added skinning look the same to a gate that only reports failures.
+ self.assertEqual(
+ sorted(report.additions),
+ ["arm.skinIndex", "arm.skinWeight", "torso.skinIndex", "torso.skinWeight"],
+ )
+ self.assertIn("added (legal)", report.summary())
+
+ def test_skin_attributes_are_not_in_the_frozen_set(self) -> None:
+ # The pass above is a consequence of this, not a coincidence.
+ self.assertNotIn("skinIndex", FROZEN_BUFFERS)
+ self.assertNotIn("skinWeight", FROZEN_BUFFERS)
+ self.assertEqual(FROZEN_ATTRIBUTES, ("position", "normal", "uv"))
+ self.assertEqual(FROZEN_BUFFERS, ("position", "normal", "uv", INDEX_KEY))
+
+ def test_any_non_frozen_attribute_is_legal_not_just_the_skin_pair(self) -> None:
+ manifest = freeze(payload("torso"))
+ coloured = payload("torso")
+ vertices = len(mesh_of(coloured, "torso")["attributes"]["position"]) // 3
+ mesh_of(coloured, "torso")["attributes"]["color"] = [1.0, 1.0, 1.0] * vertices
+ report = verify(manifest, coloured)
+ self.assertTrue(report.ok, report.summary())
+ self.assertEqual(report.additions, ("torso.color",))
+
+ def test_adding_a_frozen_class_attribute_is_not_legal(self) -> None:
+ # uv was never frozen for this mesh, so producing one afterwards is new surface data, not an
+ # addition the gate is here to permit.
+ bare = payload("torso")
+ del mesh_of(bare, "torso")["attributes"]["uv"]
+ manifest = freeze(bare)
+ report = verify(manifest, payload("torso"))
+ self.assertFalse(report.ok)
+ failure = failures_of(report, KIND_ATTRIBUTE_ADDED)[0]
+ self.assertEqual((failure.mesh, failure.attribute), ("torso", "uv"))
+
+ def test_dropping_a_frozen_attribute_fails_naming_it(self) -> None:
+ manifest = freeze(payload("torso"))
+ stripped = payload("torso")
+ del mesh_of(stripped, "torso")["attributes"]["normal"]
+ report = verify(manifest, stripped)
+ self.assertFalse(report.ok)
+ failure = failures_of(report, KIND_ATTRIBUTE_MISSING)[0]
+ self.assertEqual((failure.mesh, failure.attribute), ("torso", "normal"))
+
+
+class MeshSetChanges(unittest.TestCase):
+ def test_removing_a_mesh_fails_naming_it(self) -> None:
+ manifest = freeze(payload("torso", "arm"))
+ report = verify(manifest, payload("torso"))
+ self.assertFalse(report.ok)
+ failure = failures_of(report, KIND_MESH_MISSING)[0]
+ self.assertEqual(failure.mesh, "arm")
+ self.assertEqual(report.meshes_compared, 1)
+
+ def test_adding_a_mesh_fails_naming_it(self) -> None:
+ # Implementation may add a skeleton. It may not add geometry -- a mesh that appears during
+ # rigging is either a duplicated limb or a debug helper, and both ship.
+ manifest = freeze(payload("torso"))
+ report = verify(manifest, payload("torso", "arm"))
+ self.assertFalse(report.ok)
+ failure = failures_of(report, KIND_MESH_ADDED)[0]
+ self.assertEqual(failure.mesh, "arm")
+
+ def test_reordering_meshes_passes_because_matching_is_by_name(self) -> None:
+ document = payload("torso", "arm", "head", "leg")
+ manifest = freeze(document)
+ shuffled = payload("torso", "arm", "head", "leg")
+ random.Random(20250825).shuffle(shuffled["meshes"])
+ self.assertNotEqual(
+ [mesh["name"] for mesh in shuffled["meshes"]],
+ [mesh["name"] for mesh in document["meshes"]],
+ "the shuffle must actually reorder, or this test proves nothing",
+ )
+ report = verify(manifest, shuffled)
+ self.assertTrue(report.ok, report.summary())
+ self.assertEqual(report.meshes_compared, 4)
+
+ def test_a_renamed_mesh_reads_as_one_removed_and_one_added(self) -> None:
+ manifest = freeze(payload("torso", "arm"))
+ renamed = payload("torso", "arm")
+ mesh_of(renamed, "arm")["name"] = "arm.001"
+ report = verify(manifest, renamed)
+ self.assertFalse(report.ok)
+ self.assertEqual(failures_of(report, KIND_MESH_MISSING)[0].mesh, "arm")
+ self.assertEqual(failures_of(report, KIND_MESH_ADDED)[0].mesh, "arm.001")
+
+
+class DuplicateNames(unittest.TestCase):
+ """Two meshes with one name cannot be told apart, so they are never silently zipped."""
+
+ def test_duplicate_names_in_the_payload_are_a_reported_failure(self) -> None:
+ manifest = freeze(payload("torso", "arm"))
+ doubled = payload("torso", "arm")
+ doubled["meshes"].append(cube("arm", origin=9.0))
+ report = verify(manifest, doubled)
+ self.assertFalse(report.ok)
+ failure = failures_of(report, KIND_DUPLICATE)[0]
+ self.assertEqual(failure.mesh, "arm")
+ self.assertIn("2", failure.detail)
+ # The ambiguous name is excluded from comparison entirely rather than compared against
+ # whichever copy happened to be last.
+ self.assertEqual(report.meshes_compared, 1)
+ self.assertEqual(failures_of(report, KIND_HASH), [])
+
+ def test_duplicate_names_in_the_manifest_are_a_reported_failure(self) -> None:
+ manifest = freeze(payload("torso", "arm"))
+ doubled = dataclasses.replace(manifest, meshes=manifest.meshes + (manifest.meshes[1],))
+ report = verify(doubled, payload("torso", "arm"))
+ self.assertFalse(report.ok)
+ failure = failures_of(report, KIND_DUPLICATE)[0]
+ self.assertEqual(failure.mesh, "arm")
+
+ def test_freeze_refuses_to_record_duplicate_names(self) -> None:
+ # freeze is a producer, not a gate: there is no correct manifest to emit here, so it stops.
+ doubled = payload("torso")
+ doubled["meshes"].append(cube("torso", origin=9.0))
+ with self.assertRaises(ValueError):
+ freeze(doubled)
+
+
+class CountsAreCheckedIndependentlyOfHashes(unittest.TestCase):
+ def test_a_vertex_count_change_fails_even_when_the_hashes_were_recomputed(self) -> None:
+ # The scenario: someone shortens a mesh and re-runs freeze to make the hashes agree, but the
+ # recorded counts still come from the real freeze. Comparing counts against the manifest's
+ # RECORDED counts rather than against the length of its own buffers is what catches that.
+ manifest = freeze(payload("torso"))
+
+ short = payload("torso")
+ mesh = mesh_of(short, "torso")
+ mesh["attributes"]["position"] = mesh["attributes"]["position"][:-3]
+ mesh["attributes"]["normal"] = mesh["attributes"]["normal"][:-3]
+ mesh["attributes"]["uv"] = mesh["attributes"]["uv"][:-2]
+ mesh[INDEX_KEY] = [value for value in mesh[INDEX_KEY] if value != 7]
+
+ recomputed = freeze(short)
+ spliced = dataclasses.replace(
+ recomputed,
+ meshes=(
+ dataclasses.replace(
+ recomputed.meshes[0],
+ vertex_count=manifest.meshes[0].vertex_count,
+ index_count=manifest.meshes[0].index_count,
+ ),
+ ),
+ )
+
+ report = verify(spliced, short)
+ self.assertFalse(report.ok)
+ # Every hash agrees -- the buffers really are the ones that were hashed.
+ self.assertEqual(failures_of(report, KIND_HASH), [], report.summary())
+ counts = failures_of(report, KIND_COUNT)
+ self.assertEqual({failure.mesh for failure in counts}, {"torso"})
+ details = " ".join(failure.detail for failure in counts)
+ self.assertIn("vertexCount 8 -> 7", details)
+ self.assertIn("indexCount 36 -> 30", details)
+
+ def test_a_truncated_buffer_reports_a_count_change_not_a_hash_mismatch(self) -> None:
+ # Reporting both would double every truncation, and "the hash differs" adds nothing once the
+ # length already differs.
+ manifest = freeze(payload("torso"))
+ short = payload("torso")
+ short_mesh = mesh_of(short, "torso")
+ short_mesh["attributes"]["normal"] = short_mesh["attributes"]["normal"][:-3]
+ report = verify(manifest, short)
+ self.assertFalse(report.ok)
+ self.assertEqual(report.failure_count, 1, report.summary())
+ failure = report.failures[0]
+ self.assertEqual((failure.mesh, failure.attribute, failure.kind), ("torso", "normal", KIND_COUNT))
+
+
+class IndexBufferChanges(unittest.TestCase):
+ def test_a_rewired_index_buffer_fails_naming_index(self) -> None:
+ # The weld/rewire case: every vertex is exactly where it was, so a position-only gate would
+ # pass this while the surface has been re-stitched into a different shape.
+ manifest = freeze(payload("torso"))
+ rewired = payload("torso")
+ mesh = mesh_of(rewired, "torso")
+ mesh[INDEX_KEY][4], mesh[INDEX_KEY][5] = mesh[INDEX_KEY][5], mesh[INDEX_KEY][4]
+
+ report = verify(manifest, rewired)
+
+ self.assertFalse(report.ok)
+ self.assertEqual(report.failure_count, 1, report.summary())
+ failure = report.failures[0]
+ self.assertEqual(failure.attribute, INDEX_KEY)
+ self.assertEqual(failure.kind, KIND_HASH)
+ self.assertEqual(failure.mesh, "torso")
+ self.assertEqual(failure.differing_elements, 2)
+ self.assertEqual(failure.differences[0].index, 4)
+
+ def test_the_vertex_data_really_is_untouched_in_that_case(self) -> None:
+ # Otherwise the test above might be catching a position change by accident.
+ manifest = freeze(payload("torso"))
+ rewired = payload("torso")
+ mesh = mesh_of(rewired, "torso")
+ mesh[INDEX_KEY][4], mesh[INDEX_KEY][5] = mesh[INDEX_KEY][5], mesh[INDEX_KEY][4]
+ self.assertEqual(
+ mesh["attributes"]["position"],
+ mesh_of(payload("torso"), "torso")["attributes"]["position"],
+ )
+
+
+class HonestyWhenThereIsNothingToCheck(unittest.TestCase):
+ def test_verify_without_a_manifest_is_unevaluated_and_not_ok(self) -> None:
+ report = verify(None, payload())
+ self.assertEqual(report.status, STATUS_UNEVALUATED)
+ self.assertFalse(report.ok)
+ self.assertEqual(report.failure_count, 0)
+ self.assertTrue(report.reason)
+ # Not-ok with zero failures is the whole point: nothing is wrong and nothing is proven.
+ self.assertNotEqual(report.status, STATUS_PASS)
+ self.assertNotEqual(report.status, STATUS_FAIL)
+
+ def test_an_empty_manifest_is_unevaluated_not_a_pass(self) -> None:
+ empty = Manifest(schema_version=SCHEMA_VERSION, frozen_attributes=FROZEN_BUFFERS, meshes=())
+ report = verify(empty, payload())
+ self.assertEqual(report.status, STATUS_UNEVALUATED)
+ self.assertFalse(report.ok)
+
+ def test_a_manifest_from_another_schema_is_unevaluated(self) -> None:
+ manifest = freeze(payload("torso"))
+ report = verify(dataclasses.replace(manifest, schema_version=99), payload("torso"))
+ self.assertEqual(report.status, STATUS_UNEVALUATED)
+ self.assertFalse(report.ok)
+ self.assertIn("99", report.reason or "")
+
+ def test_a_manifest_frozen_over_a_different_attribute_set_is_unevaluated(self) -> None:
+ manifest = freeze(payload("torso"))
+ narrowed = dataclasses.replace(manifest, frozen_attributes=("position",))
+ report = verify(narrowed, payload("torso"))
+ self.assertEqual(report.status, STATUS_UNEVALUATED)
+ self.assertFalse(report.ok)
+
+ def test_a_manifest_whose_hash_contradicts_its_own_buffer_says_so(self) -> None:
+ # If the scan finds no differing element after the hash said there was one, the payload is
+ # not the liar -- the manifest is.
+ manifest = freeze(payload("torso"))
+ fingerprint = manifest.meshes[0]
+ tampered = dataclasses.replace(
+ fingerprint,
+ attribute_hashes={**fingerprint.attribute_hashes, "position": "00" * 32},
+ )
+ report = verify(dataclasses.replace(manifest, meshes=(tampered,)), payload("torso"))
+ self.assertFalse(report.ok)
+ failure = failures_of(report, KIND_HASH)[0]
+ self.assertEqual(failure.differing_elements, 0)
+ self.assertIn("manifest", failure.detail)
+
+
+class JsonRoundTripStability(unittest.TestCase):
+ """Why the hash is over packed bytes and not over the JSON text."""
+
+ def test_a_json_round_trip_does_not_change_a_single_hash(self) -> None:
+ document = payload("torso", "arm")
+ before = freeze(document)
+ after = freeze(json.loads(json.dumps(document)))
+ for left, right in zip(before.meshes, after.meshes):
+ self.assertEqual(left.name, right.name)
+ self.assertEqual(left.attribute_hashes, right.attribute_hashes)
+ self.assertTrue(verify(before, json.loads(json.dumps(document))).ok)
+
+ def test_different_json_spellings_of_the_same_number_hash_the_same(self) -> None:
+ # This is what packed-byte hashing buys. `1`, `1.0` and `1e0` are three legal spellings of
+ # one double; hashing the text would call each of them a mesh change.
+ terse = json.loads(
+ '{"meshes": [{"name": "m", "attributes": {"position": [1, 2, 3, 0, 5e-1, 0]},'
+ ' "index": [0, 1, 0]}]}'
+ )
+ verbose = json.loads(
+ '{"meshes": [{"name": "m", "attributes": {"position": [1.0, 2.0, 3.0, 0.0, 0.5, 0.0]},'
+ ' "index": [0.0, 1.0, 0.0]}]}'
+ )
+ self.assertNotEqual(json.dumps(terse), json.dumps(verbose))
+ self.assertEqual(
+ freeze(terse).meshes[0].attribute_hashes,
+ freeze(verbose).meshes[0].attribute_hashes,
+ )
+ self.assertTrue(verify(freeze(terse), verbose).ok)
+
+ def test_a_manifest_survives_being_written_and_read_back(self) -> None:
+ document = payload("torso", "arm")
+ manifest = freeze(document)
+ restored = Manifest.from_dict(json.loads(json.dumps(manifest.to_dict())))
+ self.assertTrue(verify(restored, document).ok)
+ # And still fails on the same defect after the round trip.
+ broken = payload("torso", "arm")
+ mesh_of(broken, "torso")["attributes"]["position"][0] += 1e-9
+ self.assertFalse(verify(restored, broken).ok)
+
+ def test_the_frozen_bytes_are_bit_exact_not_approximate(self) -> None:
+ # -0.0 and 0.0 compare equal in float and are different bytes. The gate reports the change,
+ # because a sign flip on a normal component is a real, visible difference.
+ base = json.loads('{"meshes": [{"name": "m", "attributes": {"position": [0.0, 1.0, 2.0]}}]}')
+ flipped = json.loads(
+ '{"meshes": [{"name": "m", "attributes": {"position": [-0.0, 1.0, 2.0]}}]}'
+ )
+ report = verify(freeze(base), flipped)
+ self.assertFalse(report.ok)
+ self.assertEqual(report.failures[0].differences[0].index, 0)
+
+
+class Cli(unittest.TestCase):
+ """The CLI's exit code is the gate as CI sees it, so it is checked, not assumed.
+
+ stdout and stderr are captured rather than let through: the report JSON is the CLI's product,
+ not this test suite's, and the exit-2 case is SUPPOSED to write an error line -- printing either
+ here would bury the test results they are meant to be checked by.
+ """
+
+ @staticmethod
+ def run_cli(argv: list[str]) -> int:
+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
+ return main(argv)
+
+ def test_freeze_then_verify_exits_zero_and_a_broken_payload_exits_one(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ good = root / "good.json"
+ bad = root / "bad.json"
+ manifest = root / "manifest.json"
+
+ document = payload("torso", "arm")
+ good.write_text(json.dumps(document), encoding="utf-8")
+ broken = payload("torso", "arm")
+ mesh_of(broken, "arm")["attributes"]["position"][2] += 0.25
+ bad.write_text(json.dumps(broken), encoding="utf-8")
+
+ self.assertEqual(self.run_cli(["freeze", str(good), "--out", str(manifest)]), 0)
+ self.assertTrue(manifest.exists())
+ self.assertEqual(self.run_cli(["verify", str(manifest), str(good)]), 0)
+ self.assertEqual(self.run_cli(["verify", str(manifest), str(bad)]), 1)
+
+ def test_an_unreadable_input_exits_two_rather_than_reporting_a_pass(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ missing = Path(directory) / "nope.json"
+ self.assertEqual(self.run_cli(["freeze", str(missing)]), 2)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_rig_gates.py b/forge/tests/test_rig_gates.py
new file mode 100644
index 0000000..f78a860
--- /dev/null
+++ b/forge/tests/test_rig_gates.py
@@ -0,0 +1,884 @@
+#!/usr/bin/env python3
+"""Tests for the Stage R6 gate runner (forge/stage5_rig/rig_gates.py).
+
+Each test traces to one row of the R6 table in
+docs/pipelines/character-rigging-animation-1.5.2.md, or to the honesty rule in
+forge/stage5_rig/CONTRACT_1.5.2.md ("Any gate that cannot be evaluated because its input is absent
+reports status: unevaluated ... It is never silently a pass").
+
+The tests that matter most here are not the ones that feed a gate a bad number. They are the ones
+that feed a gate a GOOD number over thin coverage — `test_g1_fails_a_tiny_delta_sampled_only_three
+_times`, `test_g2_fails_on_under_sampled_vertex_coverage`,
+`test_g10_fails_a_five_frame_sweep_even_with_zero_holes` — because that is the shape every 1.5.1
+failure actually had: a plausible measurement over the frames nobody looked at.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage5_rig"))
+
+import mesh_parity # noqa: E402
+
+from rig_gates import ( # noqa: E402
+ BINDING_EPSILON,
+ BIND_RESTORE_TOLERANCE,
+ GATE_SPECS,
+ MINIMUM_G2_VERTICES,
+ MINIMUM_GATE_R1_SAMPLES,
+ STATUS_FAIL,
+ STATUS_PASS,
+ STATUS_UNEVALUATED,
+ run_gates,
+)
+
+H = 1.0
+
+# The joint hierarchy G7 resolves chains from. Shape, not names: root -> single-child chain -> hip
+# branch (mirrored leg pair + medial spine) -> shoulder branch (mirrored arm pair + medial neck).
+JOINTS = [
+ {"id": "root", "parent": None, "localPosition": [0.0, 0.0, 0.0]},
+ {"id": "hips", "parent": "root", "localPosition": [0.0, 0.5, 0.0]},
+ {"id": "thigh.l", "parent": "hips", "localPosition": [0.1, -0.05, 0.0]},
+ {"id": "thigh.r", "parent": "hips", "localPosition": [-0.1, -0.05, 0.0]},
+ {"id": "shin.l", "parent": "thigh.l", "localPosition": [0.0, -0.22, 0.0]},
+ {"id": "shin.r", "parent": "thigh.r", "localPosition": [0.0, -0.22, 0.0]},
+ {"id": "foot.l", "parent": "shin.l", "localPosition": [0.0, -0.23, 0.0]},
+ {"id": "foot.r", "parent": "shin.r", "localPosition": [0.0, -0.23, 0.0]},
+ {"id": "spine", "parent": "hips", "localPosition": [0.0, 0.15, 0.0]},
+ {"id": "chest", "parent": "spine", "localPosition": [0.0, 0.15, 0.0]},
+ {"id": "clavicle.l", "parent": "chest", "localPosition": [0.08, 0.05, 0.0]},
+ {"id": "clavicle.r", "parent": "chest", "localPosition": [-0.08, 0.05, 0.0]},
+ {"id": "upperarm.l", "parent": "clavicle.l", "localPosition": [0.06, 0.0, 0.0]},
+ {"id": "upperarm.r", "parent": "clavicle.r", "localPosition": [-0.06, 0.0, 0.0]},
+ {"id": "hand.l", "parent": "upperarm.l", "localPosition": [0.18, -0.12, 0.0]},
+ {"id": "hand.r", "parent": "upperarm.r", "localPosition": [-0.18, -0.12, 0.0]},
+ {"id": "neck", "parent": "chest", "localPosition": [0.0, 0.06, 0.0]},
+ {"id": "head", "parent": "neck", "localPosition": [0.0, 0.12, 0.0]},
+]
+
+# The side-label claim comes from OUTSIDE the geometry (the source rig's own naming). Without it
+# `resolve_chains` assigns left = +X and G7 becomes a tautology — see ambiguity 8 in rig_gates.
+SIDE_LABELS = {"thigh.l": "l", "thigh.r": "r", "clavicle.l": "l", "clavicle.r": "r"}
+MIRRORED_LABELS = {"thigh.l": "r", "thigh.r": "l", "clavicle.l": "r", "clavicle.r": "l"}
+
+
+def _walk_clip(skating: bool = False, scale_delta: float = 0.0) -> dict:
+ """A one-cycle walk sampled at six times, with both feet planted through their stance.
+
+ `skating=True` moves foot.l 0.05H mid-stance — five times FOOT_SLIDE_LIMIT, and invisible to
+ anyone reading the track values.
+ """
+ times = [0.0, 0.24, 0.48, 0.72, 0.96, 1.2]
+ hip_z = [0.0, 0.096, 0.192, 0.288, 0.384, 0.48]
+ left_planted_z = 0.05 if skating else 0.0
+ return {
+ "sourceName": "walk-forward",
+ "duration": 1.2,
+ "sampleTimes": list(times),
+ "landmarkPositions": {
+ "hip": [[0.0, 0.5, z] for z in hip_z],
+ "head": [[0.0, 0.95, z] for z in hip_z],
+ "hand.l": [[0.16, 0.72, z] for z in hip_z],
+ "hand.r": [[-0.16, 0.72, z] for z in hip_z],
+ "foot.l": [
+ [0.1, 0.0, 0.0],
+ [0.1, 0.0, left_planted_z],
+ [0.1, 0.0, 0.0],
+ [0.1, 0.05, 0.24],
+ [0.1, 0.02, 0.40],
+ [0.1, 0.0, 0.48],
+ ],
+ "foot.r": [
+ [-0.1, 0.0, -0.24],
+ [-0.1, 0.05, 0.0],
+ [-0.1, 0.02, 0.12],
+ [-0.1, 0.0, 0.24],
+ [-0.1, 0.0, 0.24],
+ [-0.1, 0.0, 0.24],
+ ],
+ },
+ "jointScaleDelta": [scale_delta] * len(times),
+ "poseReturn": 0.1,
+ "stance": {"foot.l": [[0.0, 0.48]], "foot.r": [[0.72, 1.2]]},
+ }
+
+
+def _idle_clip(scale_delta: float = 0.0) -> dict:
+ times = [0.0, 0.5, 1.0]
+ return {
+ "sourceName": "idle-still",
+ "duration": 1.0,
+ "sampleTimes": list(times),
+ "landmarkPositions": {
+ "hip": [[0.0, 0.5, 0.0]] * 3,
+ "head": [[0.0, 0.95, 0.0]] * 3,
+ "hand.l": [[0.16, 0.72, 0.0]] * 3,
+ "hand.r": [[-0.16, 0.72, 0.0]] * 3,
+ "foot.l": [[0.1, 0.0, 0.0]] * 3,
+ "foot.r": [[-0.1, 0.0, 0.0]] * 3,
+ },
+ "jointScaleDelta": [scale_delta] * len(times),
+ "poseReturn": 0.0,
+ "stance": {"foot.l": [[0.0, 1.0]], "foot.r": [[0.0, 1.0]]},
+ }
+
+
+def _binding(weight_bias: float = 0.0, bad_index: bool = False) -> dict:
+ """Two vertices, four influences each. `weight_bias` breaks normalisation; `bad_index` puts one
+ skin index past bones - 1."""
+ indices = [0, 1, 2, 3, 1, 2, 3, 0]
+ if bad_index:
+ indices[3] = 9
+ return {
+ "positions": [[0.0, 0.0, 0.0], [0.1, 0.0, 0.0]],
+ "partIds": ["torso", "arm"],
+ "skinIndices": indices,
+ "skinWeights": [0.25 + weight_bias, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25],
+ "jointCount": 4,
+ }
+
+
+# ---------------------------------------------------------------------------------------------
+# G11 / G12 fixtures
+#
+# The freeze manifest is built by calling `mesh_parity.freeze` on the pre-rig payload rather than
+# being hand-written, so the manifest and the "after" payload cannot drift apart in the fixture and
+# hand us a green test for the wrong reason.
+# ---------------------------------------------------------------------------------------------
+
+_TORSO_POSITION = [0.0, 0.0, 0.0, 0.1, 0.0, 0.0, 0.1, 0.2, 0.0, 0.0, 0.2, 0.0]
+_TORSO_NORMAL = [0.0, 0.0, 1.0] * 4
+_TORSO_UV = [0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0]
+_TORSO_INDEX = [0, 1, 2, 0, 2, 3]
+_ARM_POSITION = [0.2, 0.5, 0.0, 0.3, 0.5, 0.0, 0.3, 0.6, 0.0]
+_ARM_NORMAL = [0.0, 0.0, 1.0] * 3
+_ARM_UV = [0.0, 0.0, 1.0, 0.0, 1.0, 1.0]
+_ARM_INDEX = [0, 1, 2]
+
+
+def _mesh(name, position, normal, uv, index, skinning=False):
+ attributes = {"position": list(position), "normal": list(normal), "uv": list(uv)}
+ if skinning:
+ vertices = len(position) // 3
+ # The one thing rigging is ALLOWED to add. Outside FROZEN_BUFFERS on purpose.
+ attributes["skinIndex"] = [0, 1, 0, 0] * vertices
+ attributes["skinWeight"] = [1.0, 0.0, 0.0, 0.0] * vertices
+ return {"name": name, "attributes": attributes, "index": list(index)}
+
+
+def _pre_rig_meshes():
+ """The geometry as it stood before rigging: no skinning attributes anywhere."""
+ return {
+ "meshes": [
+ _mesh("torso", _TORSO_POSITION, _TORSO_NORMAL, _TORSO_UV, _TORSO_INDEX),
+ _mesh("arm", _ARM_POSITION, _ARM_NORMAL, _ARM_UV, _ARM_INDEX),
+ ]
+ }
+
+
+def _post_rig_meshes(nudge=False, skinning=True):
+ """The same geometry after rigging. `nudge` moves one torso vertex by 0.001."""
+ position = list(_TORSO_POSITION)
+ if nudge:
+ position[4] = position[4] + 0.001
+ return {
+ "meshes": [
+ _mesh("torso", position, _TORSO_NORMAL, _TORSO_UV, _TORSO_INDEX, skinning=skinning),
+ _mesh("arm", _ARM_POSITION, _ARM_NORMAL, _ARM_UV, _ARM_INDEX, skinning=skinning),
+ ]
+ }
+
+
+def _freeze_manifest():
+ return mesh_parity.freeze(_pre_rig_meshes()).to_dict()
+
+
+def _glb_report(structural_failure=None, primary_skin=0, unsupported=(), errors=(), ok=None):
+ """A `glb_rig_reference` CLI-shaped report: GlbRig.to_dict() plus the CLI's `ok`/`errors`."""
+ report = {
+ "schemaVersion": 1,
+ "kind": "glb-rig-reference",
+ "path": "character.glb",
+ "nodeCount": 48,
+ "skinCount": 1 if primary_skin is not None else 0,
+ "clipCount": 2,
+ "primarySkinIndex": primary_skin,
+ "inverseBindSource": "accessor",
+ "unsupportedInterpolationClips": list(unsupported),
+ "structuralFailure": structural_failure,
+ "warnings": [],
+ "errors": list(errors),
+ }
+ if ok is not None:
+ report["ok"] = ok
+ return report
+
+
+def _correspondence(usable=True):
+ if usable:
+ return {
+ "figureHeight": H,
+ "tolerance": 0.05,
+ "matchedBy": "measured model-space position (never node names)",
+ "matches": [
+ {"boneId": "hips", "skinJointIndex": 0, "nodeName": "mixamorig:Hips",
+ "distanceH": 0.002, "confidence": 0.96},
+ {"boneId": "chest", "skinJointIndex": 1, "nodeName": "mixamorig:Spine2",
+ "distanceH": 0.004, "confidence": 0.92},
+ ],
+ "unmatchedProceduralBones": [],
+ "unmatchedGlbJoints": [],
+ "usable": True,
+ "reason": "all 2 procedural bones matched all 2 GLB joints within 0.05H",
+ }
+ return {
+ "figureHeight": H,
+ "tolerance": 0.05,
+ "matchedBy": "measured model-space position (never node names)",
+ "matches": [
+ {"boneId": "hips", "skinJointIndex": 0, "nodeName": "mixamorig:Hips",
+ "distanceH": 0.002, "confidence": 0.96},
+ ],
+ "unmatchedProceduralBones": ["chest", "clavicle.l"],
+ "unmatchedGlbJoints": [{"skinJointIndex": 1, "name": "mixamorig:Spine2"}],
+ "usable": False,
+ "reason": "2 procedural bones and 1 GLB joint are unmatched within 0.05H",
+ }
+
+
+def full_payload() -> dict:
+ """Every measurement inside tolerance and every coverage axis satisfied."""
+ return {
+ "figureHeight": H,
+ "landmarks": ["hip", "head", "hand.l", "hand.r", "foot.l", "foot.r"],
+ "clips": [_walk_clip(), _idle_clip()],
+ "sourceScalesJoints": False,
+ "bindingSamples": {
+ "maxSampledBindingDelta": 3.0e-9,
+ "clips": {"walk-forward": 5, "idle-still": 6},
+ },
+ "deformation": {
+ "nonFiniteCount": 0,
+ "allFinite": True,
+ "meshes": {
+ "body": {"frames": 4, "verticesPerFrame": 64},
+ "hair": {"frames": 4, "verticesPerFrame": [64, 80, 64, 96]},
+ },
+ },
+ "bindRestore": {"maxBindRestoreDelta": 0.0},
+ "binding": _binding(),
+ "meshVisibility": {
+ "visibleMeshCount": 3,
+ "visibleSkinnedMeshCount": 3,
+ "unboundMeshes": [],
+ },
+ "chainAnchors": {"joints": JOINTS, "sideLabels": SIDE_LABELS},
+ "skinIntegritySweep": {
+ "frames": 32,
+ "clips": 2,
+ "times": 4,
+ "sides": 2,
+ "azimuths": 2,
+ "backgroundThroughSplitPx": 287,
+ "backgroundThroughSplitBlobs": 15,
+ "creasePx": 36470,
+ "baseline": {
+ "backgroundThroughSplitPx": 974,
+ "backgroundThroughSplitBlobs": 30,
+ "creasePx": 31316,
+ },
+ },
+ "meshParity": {"manifest": _freeze_manifest(), "after": _post_rig_meshes()},
+ "rigReference": {"source": "glb", "glb": _glb_report()},
+ }
+
+
+class GateReportShapeTest(unittest.TestCase):
+ def test_fully_populated_payload_passes_all_twelve(self):
+ report = run_gates(full_payload())
+ statuses = {result.id: (result.status, result.reason) for result in report.results}
+ self.assertEqual(len(report.results), 12)
+ for gate_id, (status, reason) in statuses.items():
+ self.assertEqual(status, STATUS_PASS, f"{gate_id} is {status}: {reason}")
+ self.assertTrue(report.ok)
+
+ def test_summary_is_table_shaped_and_names_what_each_gate_catches(self):
+ """The R6 "Catches" column rides on every result so a failing report explains itself."""
+ summary = run_gates(full_payload()).summary()
+ self.assertEqual([row["id"] for row in summary["rows"]], [s.id for s in GATE_SPECS])
+ self.assertEqual(summary["counts"], {"total": 12, "pass": 12, "fail": 0, "unevaluated": 0})
+ for row in summary["rows"]:
+ for key in ("id", "gate", "status", "measured", "threshold", "catches", "reason"):
+ self.assertIn(key, row)
+ self.assertTrue(row["catches"], f"{row['id']} carries no 'catches' text")
+ self.assertEqual(summary["rows"][0]["catches"], "clips that play silently")
+ self.assertEqual(summary["rows"][6]["catches"], "mirrored rig")
+ self.assertEqual(summary["rows"][10]["catches"], "rigging that rewrites mesh geometry")
+ self.assertEqual(
+ summary["rows"][11]["catches"],
+ "clip channels and skinIndex values addressing a different skeleton",
+ )
+
+
+class G1BindingReachesNodeTest(unittest.TestCase):
+ def test_g1_fails_when_delta_exceeds_float32_epsilon(self):
+ payload = full_payload()
+ payload["bindingSamples"]["maxSampledBindingDelta"] = 1.0e-4
+ result = run_gates(payload).by_id("G1")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("exceeds float32 epsilon", result.reason)
+ self.assertEqual(result.measured["maxSampledBindingDelta"], 1.0e-4)
+
+ def test_g1_fails_a_tiny_delta_sampled_only_three_times(self):
+ """THIS IS THE TEST THAT MATTERS.
+
+ A delta of 1e-12 looks like proof and is not. Gate R1 exists because a clip can hold an
+ action, report a duration and drive nothing; the harness that samples three times has
+ measured three moments of one clip and said nothing about the rest. Under-coverage is a
+ FAILURE, not a pass — otherwise the gate is satisfied by exactly the sloppiness it was
+ written to catch.
+ """
+ payload = full_payload()
+ payload["bindingSamples"] = {
+ "maxSampledBindingDelta": 1.0e-12,
+ "clips": {"walk-forward": 3, "idle-still": 3},
+ }
+ result = run_gates(payload).by_id("G1")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertLess(result.measured["maxSampledBindingDelta"], BINDING_EPSILON)
+ self.assertIn(f"fewer than {MINIMUM_GATE_R1_SAMPLES} times", result.reason)
+ self.assertIn("under-coverage is a failure", result.reason)
+ self.assertEqual(
+ result.measured["coverage"]["clipsUnderSampled"],
+ {"walk-forward": 3, "idle-still": 3},
+ )
+
+ def test_g1_fails_a_tiny_delta_that_skipped_a_clip(self):
+ """Same shape as the test above: the clip nobody sampled is the clip that plays silently."""
+ payload = full_payload()
+ payload["bindingSamples"] = {
+ "maxSampledBindingDelta": 1.0e-12,
+ "clips": {"walk-forward": 25},
+ }
+ result = run_gates(payload).by_id("G1")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("skipped 1 of 2 clips", result.reason)
+ self.assertEqual(result.measured["coverage"]["clipsMissing"], ["idle-still"])
+
+ def test_g1_roster_is_never_taken_from_the_harness_own_report(self):
+ """Without an independent roster "covered every clip" is true by construction."""
+ payload = full_payload()
+ payload.pop("clips")
+ result = run_gates(payload).by_id("G1")
+ self.assertEqual(result.status, STATUS_UNEVALUATED)
+ self.assertIn("no independent clip roster", result.reason)
+
+
+class G2DeformationFiniteTest(unittest.TestCase):
+ def test_g2_fails_on_non_finite_deformation(self):
+ payload = full_payload()
+ payload["deformation"]["nonFiniteCount"] = 7
+ payload["deformation"]["allFinite"] = False
+ result = run_gates(payload).by_id("G2")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("non-finite", result.reason)
+ self.assertEqual(result.measured["nonFiniteCount"], 7)
+
+ def test_g2_fails_on_under_sampled_vertex_coverage(self):
+ """All-finite over 8 vertices is not all-finite: the vertex sent to infinity is one of the
+ 19,992 the harness never transformed."""
+ payload = full_payload()
+ payload["deformation"]["meshes"]["body"] = {"frames": 4, "verticesPerFrame": 8}
+ result = run_gates(payload).by_id("G2")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertEqual(result.measured["nonFiniteCount"], 0)
+ self.assertIn(f"below {MINIMUM_G2_VERTICES}/mesh/frame", result.reason)
+ self.assertIn("body", result.reason)
+
+ def test_g2_checks_every_frame_not_just_the_best_one(self):
+ payload = full_payload()
+ payload["deformation"]["meshes"]["hair"] = {"frames": 4, "verticesPerFrame": [64, 64, 12, 64]}
+ result = run_gates(payload).by_id("G2")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("hair transformed 12 vertices", result.reason)
+
+
+class G3BindRestoreTest(unittest.TestCase):
+ def test_g3_catches_pose_bleed(self):
+ """A clip that ends mid-pose leaves joints displaced, and the next clip's tracks only
+ overwrite the joints they address."""
+ payload = full_payload()
+ payload["bindRestore"]["maxBindRestoreDelta"] = 1.0e-6
+ result = run_gates(payload).by_id("G3")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertEqual(result.measured, 1.0e-6)
+ self.assertEqual(result.threshold, BIND_RESTORE_TOLERANCE)
+ self.assertIn("still displaced after stop()", result.reason)
+
+
+class G4G5DelegationTest(unittest.TestCase):
+ def test_g4_delegates_the_weight_sum_check_to_skin_conditioning(self):
+ payload = full_payload()
+ payload["binding"] = _binding(weight_bias=0.01) # sums to 1.01
+ report = run_gates(payload)
+ g4 = report.by_id("G4")
+ self.assertEqual(g4.status, STATUS_FAIL)
+ self.assertEqual(g4.details["delegatedTo"], "skin_conditioning.validate_binding")
+ joined = " ".join(g4.details["delegatedFailures"])
+ self.assertIn("|1 - sum(w)|", joined) # the text is skin_conditioning's, not ours
+ self.assertIn("vertex 0", joined)
+ # The indices were untouched, so G5 must not be dragged down with it.
+ self.assertEqual(report.by_id("G5").status, STATUS_PASS)
+
+ def test_g5_delegates_the_index_range_check_to_skin_conditioning(self):
+ payload = full_payload()
+ payload["binding"] = _binding(bad_index=True) # index 9 with jointCount 4
+ report = run_gates(payload)
+ g5 = report.by_id("G5")
+ self.assertEqual(g5.status, STATUS_FAIL)
+ self.assertEqual(g5.details["delegatedTo"], "skin_conditioning.validate_binding")
+ joined = " ".join(g5.details["delegatedFailures"])
+ self.assertIn("skin index 9 outside [0, 3]", joined) # again, skin_conditioning's words
+ self.assertEqual(g5.measured["maxSkinIndex"], 9)
+ self.assertEqual(g5.measured["boneCount"], 4)
+ self.assertEqual(report.by_id("G4").status, STATUS_PASS)
+
+
+class G6MeshBindingTest(unittest.TestCase):
+ def test_g6_fails_when_a_visible_mesh_is_unbound(self):
+ payload = full_payload()
+ payload["meshVisibility"] = {
+ "visibleMeshCount": 3,
+ "visibleSkinnedMeshCount": 2,
+ "unboundMeshes": ["shoulder-pad.l"],
+ }
+ result = run_gates(payload).by_id("G6")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("shoulder-pad.l", result.reason)
+ self.assertIn("1 mesh(es) unaccounted for", result.reason)
+
+
+class G7MedialLateralTest(unittest.TestCase):
+ def test_g7_catches_a_mirrored_rig(self):
+ """Every left-hand action plays on the right, and nothing about it looks wrong in
+ isolation. Three inequalities per pair are the whole detector."""
+ payload = full_payload()
+ payload["chainAnchors"] = {"joints": JOINTS, "sideLabels": MIRRORED_LABELS}
+ result = run_gates(payload).by_id("G7")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertEqual(result.details["delegatedTo"], "action_design.check_medial_lateral")
+ self.assertIn("MEDIAL_LATERAL", result.details["delegatedFailures"][0])
+ self.assertIn("the rig is mirrored", result.details["delegatedFailures"][0])
+
+ def test_g7_is_unevaluated_not_pass_without_an_independent_side_claim(self):
+ """Ambiguity 8. With left = +X assigned from the same geometry the gate compares against,
+ an errorless run proves nothing — so it is not reported as a pass."""
+ payload = full_payload()
+ payload["chainAnchors"] = {"joints": JOINTS} # no sideLabels
+ report = run_gates(payload)
+ result = report.by_id("G7")
+ self.assertEqual(result.status, STATUS_UNEVALUATED)
+ self.assertIn("could not have been caught", result.reason)
+ self.assertFalse(report.ok)
+
+
+class G8FootContactTest(unittest.TestCase):
+ def test_g8_passes_a_gait_with_the_contact_constraint_enforced(self):
+ result = run_gates(full_payload()).by_id("G8")
+ self.assertEqual(result.status, STATUS_PASS)
+ self.assertEqual(result.measured["maxFootSlideFraction"], 0.0)
+ self.assertEqual(result.measured["clipsMeasured"], 2)
+ self.assertEqual(result.details["delegatedTo"], "action_design.foot_slide")
+
+ def test_g8_catches_a_skating_gait(self):
+ """Reads as "floaty" to every viewer and is hard to name by eye; 0.05H is five times the
+ limit and completely invisible in the track values."""
+ payload = full_payload()
+ payload["clips"] = [_walk_clip(skating=True), _idle_clip()]
+ result = run_gates(payload).by_id("G8")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertAlmostEqual(result.measured["maxFootSlideFraction"], 0.05, places=9)
+ self.assertEqual(result.measured["worstClip"], "walk-forward")
+ self.assertIn("walk-forward", result.reason)
+ self.assertIn("foot.l", result.reason)
+
+
+class G9JointScaleTest(unittest.TestCase):
+ def test_g9_fails_on_scale_delta_above_zero(self):
+ payload = full_payload()
+ payload["clips"] = [_walk_clip(scale_delta=0.004), _idle_clip()]
+ result = run_gates(payload).by_id("G9")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertAlmostEqual(result.measured["maxScaleDelta"], 0.004, places=9)
+ self.assertEqual(result.measured["clipsScaling"], ["walk-forward"])
+ self.assertIn("Nothing declares sourceScalesJoints", result.reason)
+
+ def test_g9_reports_pass_with_warning_when_the_source_declares_joint_scale(self):
+ """"unless the source has it" is an admission, never a silent pass: R2's proximity blend
+ averages bindings across parts and a scaled joint invalidates that averaging."""
+ payload = full_payload()
+ payload["clips"] = [_walk_clip(scale_delta=0.004), _idle_clip()]
+ payload["sourceScalesJoints"] = True
+ result = run_gates(payload).by_id("G9")
+ self.assertEqual(result.status, STATUS_PASS)
+ self.assertTrue(result.warnings, "a declared joint scale must not pass silently")
+ self.assertIn("walk-forward", result.warnings[0])
+ self.assertIn("Stage R2", result.warnings[0])
+ self.assertIn("pass with warning", result.reason)
+
+
+class G10SkinIntegritySweepTest(unittest.TestCase):
+ def test_g10_fails_a_five_frame_sweep_even_with_zero_holes(self):
+ """"Five poses is not coverage." Coincidence-welding looked correct until a 132-frame
+ sweep found cracks in 28 frames; a clean number over 5 frames is not evidence."""
+ payload = full_payload()
+ payload["skinIntegritySweep"] = {
+ "frames": 5,
+ "clips": 5,
+ "times": 1,
+ "sides": 1,
+ "azimuths": 1,
+ "backgroundThroughSplitPx": 0,
+ "backgroundThroughSplitBlobs": 0,
+ "creasePx": 120,
+ "baseline": {"backgroundThroughSplitPx": 974, "creasePx": 31316},
+ }
+ result = run_gates(payload).by_id("G10")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertEqual(result.measured["backgroundThroughSplitPx"], 0.0)
+ self.assertIn("five poses is not coverage", result.reason)
+ self.assertIn("materially thinner", result.reason)
+
+ def test_g10_fails_a_sweep_thinner_than_its_declared_clip_set_allows(self):
+ payload = full_payload()
+ payload["skinIntegritySweep"].update(
+ {"frames": 16, "clips": 1, "times": 4, "sides": 2, "azimuths": 2}
+ )
+ result = run_gates(payload).by_id("G10")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("covered 1 of 2 clip(s)", result.reason)
+
+ def test_g10_fails_a_declared_frame_count_its_axes_do_not_support(self):
+ payload = full_payload()
+ payload["skinIntegritySweep"]["frames"] = 176 # axes still multiply to 32
+ result = run_gates(payload).by_id("G10")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("axes multiply to 32", result.reason)
+
+ def test_g10_reports_holes_and_creases_as_two_separate_numbers(self):
+ """R2 trades one against the other on purpose; a single combined score hides the trade."""
+ result = run_gates(full_payload()).by_id("G10")
+ self.assertEqual(result.status, STATUS_PASS)
+ self.assertEqual(result.measured["backgroundThroughSplitPx"], 287.0)
+ self.assertEqual(result.measured["creasePx"], 36470.0)
+ self.assertEqual(result.measured["baselineBackgroundThroughSplitPx"], 974.0)
+ self.assertEqual(result.measured["baselineCreasePx"], 31316.0)
+ self.assertNotIn("score", result.measured)
+ # Creases rose ~16% and that is REPORTED, not gated — gating it would ask a later stage to
+ # disable the blend, which is the failure R2 warns about.
+ self.assertTrue(any("crease" in w for w in result.warnings))
+
+ def test_g10_is_unevaluated_without_a_measured_baseline(self):
+ payload = full_payload()
+ payload["skinIntegritySweep"].pop("baseline")
+ result = run_gates(payload).by_id("G10")
+ self.assertEqual(result.status, STATUS_UNEVALUATED)
+ self.assertIn("baseline", result.reason)
+
+ def test_g10_is_unevaluated_without_a_per_axis_breakdown(self):
+ payload = full_payload()
+ for axis in ("clips", "times", "sides", "azimuths"):
+ payload["skinIntegritySweep"].pop(axis)
+ result = run_gates(payload).by_id("G10")
+ self.assertEqual(result.status, STATUS_UNEVALUATED)
+ self.assertIn("per-axis breakdown", result.reason)
+
+
+class G11MeshParityTest(unittest.TestCase):
+ def test_g11_fails_on_a_nudged_vertex_and_names_mesh_attribute_and_element(self):
+ """"The hash differs" hands a human two megabytes of numbers and a diff tool. The gate has
+ to carry through which mesh, which attribute, and which element — "1 of 12 elements differ"
+ is a completely different bug report from "all 12 differ"."""
+ payload = full_payload()
+ payload["meshParity"] = {
+ "manifest": _freeze_manifest(),
+ "after": _post_rig_meshes(nudge=True),
+ }
+ result = run_gates(payload).by_id("G11")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertEqual(result.details["delegatedTo"], "mesh_parity.verify")
+ self.assertEqual(result.measured["failureCount"], 1)
+ failure = result.measured["failures"][0]
+ self.assertEqual(failure["mesh"], "torso")
+ self.assertEqual(failure["attribute"], "position")
+ self.assertEqual(failure["kind"], mesh_parity.KIND_HASH)
+ self.assertEqual(failure["differingElements"], 1)
+ self.assertEqual(failure["differences"][0]["index"], 4)
+ self.assertAlmostEqual(failure["differences"][0]["frozen"], 0.0, places=9)
+ self.assertAlmostEqual(failure["differences"][0]["current"], 0.001, places=9)
+ # The headline reason must stand on its own without opening the payload.
+ self.assertIn("torso.position", result.reason)
+ self.assertIn("element 4", result.reason)
+
+ def test_g11_passes_when_only_skin_index_and_skin_weight_were_added(self):
+ """THE TEST THAT KEEPS THE GATE SWITCHED ON.
+
+ skinIndex and skinWeight sit outside FROZEN_BUFFERS deliberately — adding them is the entire
+ legal purpose of the implementation phase. A gate that failed every successful rig would be
+ switched off within a week, which is strictly worse than not having it at all.
+ """
+ payload = full_payload()
+ payload["meshParity"] = {
+ "manifest": _freeze_manifest(),
+ "after": _post_rig_meshes(skinning=True),
+ }
+ result = run_gates(payload).by_id("G11")
+ self.assertEqual(result.status, STATUS_PASS, result.reason)
+ self.assertEqual(result.measured["failureCount"], 0)
+ self.assertEqual(result.measured["meshesCompared"], 2)
+ # The additions are reported so they are visible, and never gated.
+ self.assertEqual(
+ sorted(result.measured["addedLegal"]),
+ ["arm.skinIndex", "arm.skinWeight", "torso.skinIndex", "torso.skinWeight"],
+ )
+ self.assertTrue(any("legal" in warning for warning in result.warnings))
+
+ def test_g11_passes_a_rig_that_added_nothing_at_all(self):
+ payload = full_payload()
+ payload["meshParity"] = {
+ "manifest": _freeze_manifest(),
+ "after": _post_rig_meshes(skinning=False),
+ }
+ result = run_gates(payload).by_id("G11")
+ self.assertEqual(result.status, STATUS_PASS)
+ self.assertEqual(result.measured["addedLegalCount"], 0)
+
+ def test_g11_is_unevaluated_when_the_manifest_half_is_absent(self):
+ payload = full_payload()
+ payload["meshParity"] = {"after": _post_rig_meshes()}
+ result = run_gates(payload).by_id("G11")
+ self.assertEqual(result.status, STATUS_UNEVALUATED)
+ self.assertIn("`manifest`", result.reason)
+ self.assertNotIn("`after`", result.reason)
+ self.assertIn("unproven, which is not the same as unbroken", result.reason)
+
+ def test_g11_is_unevaluated_when_the_after_half_is_absent(self):
+ payload = full_payload()
+ payload["meshParity"] = {"manifest": _freeze_manifest()}
+ result = run_gates(payload).by_id("G11")
+ self.assertEqual(result.status, STATUS_UNEVALUATED)
+ self.assertIn("`after`", result.reason)
+ self.assertNotIn("`manifest` (the freeze record", result.reason)
+
+ def test_g11_defers_the_mesh_set_decision_to_mesh_parity(self):
+ """Ambiguity 10: a mesh removed after the freeze is mesh_parity's call, not ours."""
+ payload = full_payload()
+ after = _post_rig_meshes()
+ after["meshes"] = [mesh for mesh in after["meshes"] if mesh["name"] != "arm"]
+ payload["meshParity"] = {"manifest": _freeze_manifest(), "after": after}
+ result = run_gates(payload).by_id("G11")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertEqual(result.measured["failures"][0]["kind"], mesh_parity.KIND_MESH_MISSING)
+ self.assertEqual(result.measured["failures"][0]["mesh"], "arm")
+
+
+class G12RigReferenceTest(unittest.TestCase):
+ def test_g12_passes_a_rig_that_came_straight_from_the_glb(self):
+ result = run_gates(full_payload()).by_id("G12")
+ self.assertEqual(result.status, STATUS_PASS, result.reason)
+ self.assertEqual(result.measured["primarySkinIndex"], 0)
+ self.assertTrue(result.measured["glbOk"])
+ self.assertIn("the file's own index spaces", result.reason)
+
+ def test_g12_passes_a_procedural_skeleton_with_a_usable_correspondence(self):
+ payload = full_payload()
+ payload["rigReference"] = {
+ "source": "procedural",
+ "glb": _glb_report(),
+ "correspondence": _correspondence(usable=True),
+ }
+ result = run_gates(payload).by_id("G12")
+ self.assertEqual(result.status, STATUS_PASS, result.reason)
+ self.assertIs(result.measured["correspondenceUsable"], True)
+
+ def test_g12_fails_when_the_correspondence_is_not_usable_and_surfaces_the_reason(self):
+ """`usable` is False whenever ANY joint on EITHER side is unmatched. A partial map
+ retargets the bones it knows and leaves the rest at bind pose — the disjointed mesh."""
+ payload = full_payload()
+ payload["rigReference"] = {
+ "source": "procedural",
+ "glb": _glb_report(),
+ "correspondence": _correspondence(usable=False),
+ }
+ result = run_gates(payload).by_id("G12")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("2 procedural bones and 1 GLB joint are unmatched", result.reason)
+ self.assertIn("chest", result.reason)
+ self.assertIn("mixamorig:Spine2", result.reason)
+ self.assertEqual(result.measured["unmatchedProceduralBones"], ["chest", "clavicle.l"])
+ self.assertIn("the mapping was invented", result.reason)
+
+ def test_g12_fails_not_unevaluated_on_a_structural_failure(self):
+ """A structural failure is a known-bad answer, not a missing one."""
+ payload = full_payload()
+ payload["rigReference"] = {
+ "source": "glb",
+ "glb": _glb_report(
+ structural_failure="GLB carries 3 skins and no primary skin was chosen; each skin "
+ "owns its own joint index space",
+ primary_skin=None,
+ ),
+ }
+ result = run_gates(payload).by_id("G12")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertNotEqual(result.status, STATUS_UNEVALUATED)
+ self.assertIn("carries 3 skins", result.reason)
+ self.assertIn("no usable skeleton of record", result.reason)
+
+ def test_g12_fails_on_unsupported_interpolation(self):
+ """Ambiguity 13: glb_rig_reference keeps this separate from structuralFailure; the gate
+ fails on either and names which one fired."""
+ payload = full_payload()
+ payload["rigReference"] = {
+ "source": "glb",
+ "glb": _glb_report(unsupported=["dash-forward"]),
+ }
+ result = run_gates(payload).by_id("G12")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("dash-forward", result.reason)
+ self.assertIn("interpolation", result.reason)
+ self.assertEqual(result.measured["unsupportedInterpolationClips"], ["dash-forward"])
+
+ def test_g12_fails_a_procedural_source_carrying_no_correspondence(self):
+ """Ambiguity 14: the defect stated in the payload, not absent input."""
+ payload = full_payload()
+ payload["rigReference"] = {"source": "procedural", "glb": _glb_report()}
+ result = run_gates(payload).by_id("G12")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertIn("needs an explicit mapping", result.reason)
+
+ def test_g12_honours_an_explicit_ok_false_and_derives_it_when_absent(self):
+ """Ambiguity 12: `ok` comes from the CLI, not GlbRig.to_dict(), so it is derived when the
+ caller worked in-process."""
+ derived = run_gates(full_payload()).by_id("G12")
+ self.assertFalse(derived.measured["okWasDeclared"])
+ self.assertTrue(derived.measured["glbOk"])
+
+ payload = full_payload()
+ payload["rigReference"] = {
+ "source": "glb",
+ "glb": _glb_report(ok=False, errors=["--sample-clips needs --landmarks"]),
+ }
+ result = run_gates(payload).by_id("G12")
+ self.assertEqual(result.status, STATUS_FAIL)
+ self.assertTrue(result.measured["okWasDeclared"])
+ self.assertIn("not ok", result.reason)
+
+ def test_g12_is_unevaluated_when_the_block_carries_no_glb_report(self):
+ payload = full_payload()
+ payload["rigReference"] = {"source": "glb"}
+ result = run_gates(payload).by_id("G12")
+ self.assertEqual(result.status, STATUS_UNEVALUATED)
+ self.assertIn("no skeleton of record", result.reason)
+
+
+class HonestyRuleTest(unittest.TestCase):
+ """The honesty rule, from CONTRACT_1.5.2.md.
+
+ "Any gate that cannot be evaluated because its input is absent reports `status: unevaluated`
+ with a reason. It is never silently a pass."
+ """
+
+ INPUT_KEYS = {
+ "G1": "bindingSamples",
+ "G2": "deformation",
+ "G3": "bindRestore",
+ "G4": "binding",
+ "G5": "binding",
+ "G6": "meshVisibility",
+ "G7": "chainAnchors",
+ "G8": "clips",
+ "G9": "clips",
+ "G10": "skinIntegritySweep",
+ "G11": "meshParity",
+ "G12": "rigReference",
+ }
+
+ def test_every_gate_is_unevaluated_not_pass_when_its_input_is_absent(self):
+ self.assertEqual(sorted(self.INPUT_KEYS), sorted(spec.id for spec in GATE_SPECS))
+ for spec in GATE_SPECS:
+ with self.subTest(gate=spec.id):
+ payload = copy.deepcopy(full_payload())
+ payload.pop(self.INPUT_KEYS[spec.id])
+ report = run_gates(payload)
+ result = report.by_id(spec.id)
+ self.assertEqual(
+ result.status,
+ STATUS_UNEVALUATED,
+ f"{spec.id} reported {result.status} with {self.INPUT_KEYS[spec.id]!r} absent",
+ )
+ self.assertTrue(result.reason, f"{spec.id} gave no reason")
+ self.assertIsNone(result.measured)
+ self.assertFalse(
+ report.ok, f"a report containing an unevaluated {spec.id} must not be ok"
+ )
+
+ def test_an_unevaluated_gate_makes_the_whole_report_not_ok(self):
+ payload = full_payload()
+ payload.pop("bindRestore")
+ report = run_gates(payload)
+ self.assertFalse(report.ok)
+ self.assertEqual([r.id for r in report.unevaluated], ["G3"])
+ self.assertEqual(report.failed, ())
+ self.assertEqual(report.summary()["counts"]["pass"], 11)
+
+ def test_an_empty_payload_evaluates_nothing_and_is_not_ok(self):
+ report = run_gates({})
+ self.assertEqual(len(report.unevaluated), 12)
+ self.assertFalse(report.ok)
+
+
+class CliTest(unittest.TestCase):
+ SCRIPT = ROOT / "stage5_rig" / "rig_gates.py"
+
+ def _run(self, payload: dict) -> tuple[int, dict]:
+ with tempfile.TemporaryDirectory() as tmp:
+ path = Path(tmp) / "payload.json"
+ path.write_text(json.dumps(payload), encoding="utf-8")
+ proc = subprocess.run(
+ [sys.executable, str(self.SCRIPT), str(path)],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ return proc.returncode, json.loads(proc.stdout)
+
+ def test_cli_prints_the_report_and_exits_zero_when_every_gate_passes(self):
+ code, report = self._run(full_payload())
+ self.assertEqual(code, 0, report)
+ self.assertTrue(report["ok"])
+ # Derived from GATE_SPECS, not hardcoded: adding a gate must not need a test edit here.
+ self.assertEqual(len(report["gates"]), len(GATE_SPECS))
+
+ def test_cli_exits_one_on_failure(self):
+ payload = full_payload()
+ payload["bindRestore"]["maxBindRestoreDelta"] = 1.0
+ code, report = self._run(payload)
+ self.assertEqual(code, 1)
+ self.assertFalse(report["ok"])
+ self.assertEqual(report["summary"]["failed"], ["G3"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_rig_milestone0.py b/forge/tests/test_rig_milestone0.py
index 198aeed..0d3b3e1 100644
--- a/forge/tests/test_rig_milestone0.py
+++ b/forge/tests/test_rig_milestone0.py
@@ -263,6 +263,43 @@ class RigMilestone0(unittest.TestCase):
self.assertEqual(non_manifold, 0, f"gate (d) FAIL: {non_manifold} non-manifold edges after bind")
+class RigMilestone0TemplateOrdering(unittest.TestCase):
+ """Static text checks on emit_typescript()'s output -- no node/showcase needed.
+
+ `mesh.add(root)` puts the bones' local-space rest transforms into the scene graph, but they
+ stay at their local values until something recomputes world matrices. `new THREE.Skeleton(...)`
+ calls `calculateInverses()` internally, which reads each bone's CURRENT world matrix at
+ construction time. Skeleton-then-updateMatrixWorld (or no updateMatrixWorld at all) captures
+ identity matrices into the inverse binds; those inverses then fail to cancel the rest pose
+ during skinning, so every vertex is displaced by its bone's offset at rest. This compiles,
+ binds, reports `bound: true`, and renders a corpse -- see
+ test_rig_hierarchy_emission.py::test_bone_rotation_deforms_its_own_mesh_and_not_a_distant_one
+ for the equivalent failure mode in the main factory emitter, which generate_threejs_factory.py
+ fixed the same way (`root.updateMatrixWorld(true)` before `new THREE.Skeleton(...)`).
+ """
+
+ def test_update_matrix_world_runs_between_mesh_add_and_skeleton_construction(self) -> None:
+ spec = build_three_bone_arm_spec()
+ source = emit_typescript(spec, COMPONENT_EXTENTS, CAPSULE_RADIUS)
+
+ mesh_add_index = source.index("mesh.add(root);")
+ update_matrix_world_index = source.index("mesh.updateMatrixWorld(true);")
+ skeleton_index = source.index("new THREE.Skeleton(BONE_IDS.map((id) => bones[id]));")
+
+ self.assertLess(
+ mesh_add_index, update_matrix_world_index,
+ "mesh.updateMatrixWorld(true) must run AFTER the bones are attached to the mesh "
+ "(mesh.add(root)), or it recomputes world matrices for a graph the bones aren't "
+ "even part of yet",
+ )
+ self.assertLess(
+ update_matrix_world_index, skeleton_index,
+ "mesh.updateMatrixWorld(true) must run BEFORE `new THREE.Skeleton(...)` -- "
+ "calculateInverses() reads each bone's CURRENT world matrix at construction time, "
+ "so a Skeleton built first captures identity matrices and the rig renders a corpse",
+ )
+
+
class AxisExemptionSelfCheck(unittest.TestCase):
"""Closes a coverage gap team-lead identified (2026-07-30): the derived
3-bone-arm capsule always measures axisExemptVertexCount == 0, so the
diff --git a/forge/tests/test_rig_workflow_steps.py b/forge/tests/test_rig_workflow_steps.py
new file mode 100644
index 0000000..3d9b761
--- /dev/null
+++ b/forge/tests/test_rig_workflow_steps.py
@@ -0,0 +1,209 @@
+#!/usr/bin/env python3
+"""The Stage R checklist -- that it exists, and that its ORDER cannot drift.
+
+This file exists because of a specific failure: every forge/stage5_rig/ module was callable and
+nothing in the workflow ever told anyone to call one. `next.py` walks the checklist, so a gate
+absent from the checklist is a gate that never runs, and a gate that never runs reports a clean
+verdict forever.
+
+The order assertions are the load-bearing half. "Repair, then freeze, then bind, then verify" is
+not a stylistic preference -- moving the freeze after the bind would let the bind rewrite vertices
+and then certify the rewritten buffer, so the manifest would attest to the damage instead of
+catching it. A reordering like that is invisible in review and total in effect, which is exactly
+the class of defect this suite is for.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "_shared"))
+
+from workflow_state import ( # noqa: E402
+ RIG_STEPS,
+ WorkflowStateError,
+ new_state,
+ next_entry,
+ recompute,
+ status_payload,
+)
+
+
+def rig_ids(state: dict) -> list[str]:
+ return [step["id"] for step in state["checklist"] if step["scope"] == "rig"]
+
+
+class AnimatedCharacterProfile(unittest.TestCase):
+ def setUp(self) -> None:
+ self.state = new_state("subject.glb", profile="animated-character", spec="spec.json")
+
+ def test_the_profile_is_accepted(self) -> None:
+ self.assertEqual(self.state["profile"], "animated-character")
+
+ def test_every_rig_step_reaches_the_checklist(self) -> None:
+ self.assertEqual(rig_ids(self.state), [step_id for step_id, _command in RIG_STEPS])
+
+ def test_it_keeps_the_character_steps_too(self) -> None:
+ """An animated character is still a character; the anatomy contract must not be lost."""
+ ids = [step["id"] for step in self.state["checklist"]]
+ self.assertIn("character-contract-read", ids)
+ self.assertIn("character-landmarks", ids)
+
+ def test_a_plain_character_build_gets_no_rig_steps(self) -> None:
+ """Rigging is opt-in. A static character must not be blocked on animation gates."""
+ self.assertEqual(rig_ids(new_state("subject.png", profile="character")), [])
+
+ def test_generic_and_cs2_get_no_rig_steps(self) -> None:
+ for profile in ("generic", "cs2"):
+ with self.subTest(profile=profile):
+ self.assertEqual(rig_ids(new_state("subject.png", profile=profile)), [])
+
+ def test_an_unknown_profile_is_still_refused(self) -> None:
+ with self.assertRaises(WorkflowStateError):
+ new_state("subject.glb", profile="animated")
+
+
+class StageROrderIsLoadBearing(unittest.TestCase):
+ def setUp(self) -> None:
+ self.ids = rig_ids(new_state("subject.glb", profile="animated-character", spec="spec.json"))
+
+ def index(self, step_id: str) -> int:
+ self.assertIn(step_id, self.ids)
+ return self.ids.index(step_id)
+
+ def test_repair_precedes_the_freeze(self) -> None:
+ """A mesh may legitimately need fixing; freezing a broken mesh certifies the breakage."""
+ self.assertLess(self.index("mesh-repair"), self.index("mesh-freeze"))
+
+ def test_the_freeze_precedes_every_rig_step(self) -> None:
+ """After the freeze the geometry is evidence. Binding before it leaves nothing to compare."""
+ freeze = self.index("mesh-freeze")
+ self.assertLess(freeze, self.index("rig-payload-validate"))
+ self.assertLess(freeze, self.index("rig-bind"))
+
+ def test_parity_is_verified_after_the_bind(self) -> None:
+ """Binding is the only moment "implementation did not touch the mesh" can be falsified."""
+ self.assertLess(self.index("rig-bind"), self.index("mesh-parity-verify"))
+
+ def test_the_glb_reference_precedes_binding(self) -> None:
+ """Rigging refers FROM the GLB, so its skeleton must be read before anything is bound."""
+ self.assertLess(self.index("glb-rig-reference"), self.index("rig-bind"))
+
+ def test_the_contract_is_read_first(self) -> None:
+ self.assertEqual(self.ids[0], "rig-contract-read")
+
+ def test_the_gates_run_last(self) -> None:
+ self.assertEqual(self.ids[-1], "rig-gates")
+
+
+class TheDispatcherActuallyReachesThem(unittest.TestCase):
+ """The half the first version of this suite missed, and the reason it is written this way now.
+
+ The original tests asserted the rig steps were IN the checklist and in the right ORDER. Both
+ passed while `next_entry()` had no branch for scope "rig" at all: the steps sat pending forever,
+ `recompute()` declared the build `complete` after the final scope, and `next.py` never once asked
+ for a rig step. Presence in a list is not reachability, and asserting the list is not asserting
+ the behaviour -- which is precisely the defect the Stage R wiring exists to end, reproduced one
+ layer up. These tests drive the real state machine instead.
+ """
+
+ def drain(self, profile: str) -> tuple[list[str], dict]:
+ """Walk the state machine the way next.py does, returning the rig steps it dispatched."""
+ state = new_state("subject.glb", profile=profile, spec="spec.json")
+ dispatched: list[str] = []
+ for _ in range(200):
+ entry = next_entry(state)
+ if entry is None:
+ break
+ if entry["id"] == "await-pass-transition":
+ state["currentPass"] = "complete"
+ continue
+ for step in state["checklist"]:
+ if step["id"] == entry["id"]:
+ step["status"] = "done"
+ if entry["scope"] == "rig":
+ dispatched.append(entry["id"])
+ else:
+ self.fail("state machine did not terminate")
+ recompute(state)
+ return dispatched, state
+
+ def test_every_rig_step_is_actually_dispatched(self) -> None:
+ dispatched, _state = self.drain("animated-character")
+ self.assertEqual(dispatched, [step_id for step_id, _command in RIG_STEPS])
+
+ def test_the_build_is_not_complete_while_a_rig_step_is_pending(self) -> None:
+ """The exact bug: `complete` was reached with all nine rig steps still pending."""
+ state = new_state("subject.glb", profile="animated-character", spec="spec.json")
+ state["currentPass"] = "complete"
+ for step in state["checklist"]:
+ if step["scope"] != "rig":
+ step["status"] = "done"
+ recompute(state)
+ self.assertNotEqual(state["status"], "complete")
+ self.assertEqual(next_entry(state)["scope"], "rig")
+
+ def test_rig_steps_come_after_the_final_scope(self) -> None:
+ """Rigging is additive to a finished mesh; binding one whose parts still move freezes
+ geometry that has not settled."""
+ dispatched, _state = self.drain("animated-character")
+ state = new_state("subject.glb", profile="animated-character", spec="spec.json")
+ order = [step["scope"] for step in state["checklist"]]
+ self.assertLess(max(i for i, s in enumerate(order) if s == "final"),
+ min(i for i, s in enumerate(order) if s == "rig"))
+ self.assertTrue(dispatched)
+
+ def test_a_plain_character_build_still_completes(self) -> None:
+ """Adding the rig scope must not strand a profile that has no rig steps."""
+ dispatched, state = self.drain("character")
+ self.assertEqual(dispatched, [])
+ self.assertEqual(state["status"], "complete")
+
+ def test_rig_steps_are_visible_in_status(self) -> None:
+ """Invisible in status output is unreachable in practice: nobody knows to run them."""
+ state = new_state("subject.glb", profile="animated-character", spec="spec.json")
+ pending = status_payload(state)["pending"]
+ for step_id, _command in RIG_STEPS:
+ self.assertIn(step_id, pending)
+
+
+class StepsNameTheirTooling(unittest.TestCase):
+ def setUp(self) -> None:
+ self.commands = dict(RIG_STEPS)
+
+ def test_each_gate_step_names_the_script_that_runs_it(self) -> None:
+ for step_id, script in (
+ ("glb-rig-reference", "glb_rig_reference.py"),
+ ("mesh-freeze", "mesh_parity.py"),
+ ("mesh-parity-verify", "mesh_parity.py"),
+ ("rig-payload-validate", "validate_rig_payload.py"),
+ ("clip-measure", "clip_features.py"),
+ ("rig-gates", "rig_gates.py"),
+ ):
+ with self.subTest(step=step_id):
+ self.assertIn(script, self.commands[step_id])
+
+ def test_freeze_and_verify_use_the_matching_subcommands(self) -> None:
+ self.assertIn("mesh_parity.py freeze", self.commands["mesh-freeze"])
+ self.assertIn("mesh_parity.py verify", self.commands["mesh-parity-verify"])
+
+ def test_the_bind_step_states_what_it_may_add(self) -> None:
+ """The whole mesh-immutability rule lives in this string; a rewrite that drops it is a bug."""
+ command = self.commands["rig-bind"]
+ for token in ("skinIndex", "skinWeight", "frozen"):
+ self.assertIn(token, command)
+
+ def test_the_payload_validator_states_its_own_limits(self) -> None:
+ """A green structural payload is not evidence the mesh survives animation."""
+ self.assertIn("structural payload integrity ONLY", self.commands["rig-payload-validate"])
+ # The CLI takes --payload, and a sculpt spec is a different schema from a rig payload.
+ self.assertIn("--payload", self.commands["rig-payload-validate"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_skin_conditioning.py b/forge/tests/test_skin_conditioning.py
new file mode 100644
index 0000000..9545084
--- /dev/null
+++ b/forge/tests/test_skin_conditioning.py
@@ -0,0 +1,504 @@
+#!/usr/bin/env python3
+"""Tests for Stage R2 skin conditioning, built around the defect it exists to remove.
+
+`test_coincident_vertices_bound_to_different_joints_stop_separating` is the whole argument for this
+module. It builds two overlapping parts, poses them with a real linear-blend skin transform whose two
+joints diverge, and MEASURES the gap that opens at the seam before and after blending -- because
+"proximity blending stops the skin tearing" is otherwise just a claim. Everything else here defends
+one of the four implementation requirements, each of which is load-bearing on its own.
+
+Pure Python 3.10+ stdlib.
+"""
+
+from __future__ import annotations
+
+import math
+import random
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "stage5_rig"))
+
+from skin_conditioning import ( # noqa: E402
+ BLEND_RADIUS,
+ MAX_INFLUENCES,
+ WEIGHT_SUM_TOLERANCE,
+ SkinBinding,
+ UniformGrid,
+ blend_weights,
+ brute_force_query,
+ validate_binding,
+ weld_coincident,
+ _CELL_OFFSETS,
+)
+
+TORSO = 0
+ARM = 1
+
+
+class Fixture:
+ """A two-part seam plus one deep interior vertex per part.
+
+ Coordinates are fractions of figure height H and are scaled by `height` on the way in, so the
+ same fixture can be built at any scale. The two grids are mirror images about the seam row, which
+ is what makes the coincident probe pair a fair test: neither part is favoured by the geometry.
+ """
+
+ def __init__(self, height: float = 1.0, arm_shift: float = 0.0):
+ self.height = height
+ xs = [0.000, 0.002, 0.004]
+ torso_ys = [0.000, 0.002, 0.004]
+ arm_ys = [0.004 + arm_shift, 0.006 + arm_shift, 0.008 + arm_shift]
+
+ positions: list[list[float]] = []
+ parts: list[str] = []
+ indices: list[int] = []
+ weights: list[float] = []
+
+ def add(point: tuple[float, float, float], part: str, joint: int) -> int:
+ positions.append([coordinate * height for coordinate in point])
+ parts.append(part)
+ indices.extend([joint, 0, 0, 0])
+ weights.extend([1.0, 0.0, 0.0, 0.0])
+ return len(positions) - 1
+
+ for y in torso_ys:
+ for x in xs:
+ index = add((x, y, 0.0), "torso", TORSO)
+ if (x, y) == (0.002, torso_ys[2]):
+ self.torso_probe = index
+ for y in arm_ys:
+ for x in xs:
+ index = add((x, y, 0.0), "arm", ARM)
+ if (x, y) == (0.002, arm_ys[0]):
+ self.arm_probe = index
+
+ # Far from the seam in both directions: no vertex of the other part is anywhere near them, so
+ # they are interior by definition and must come back untouched.
+ self.torso_interior = add((0.002, -0.5, 0.0), "torso", TORSO)
+ self.arm_interior = add((0.002, 0.5, 0.0), "arm", ARM)
+
+ self.binding = SkinBinding(
+ positions=positions,
+ part_ids=parts,
+ skin_indices=indices,
+ skin_weights=weights,
+ joint_count=2,
+ )
+
+
+def rotate_about_z(degrees: float, pivot: list[float]):
+ """One joint's world transform: a rotation about a pivot, the way a shoulder actually moves."""
+ angle = math.radians(degrees)
+ cosine, sine = math.cos(angle), math.sin(angle)
+
+ def transform(point: list[float]) -> list[float]:
+ x = point[0] - pivot[0]
+ y = point[1] - pivot[1]
+ return [cosine * x - sine * y + pivot[0], sine * x + cosine * y + pivot[1], point[2]]
+
+ return transform
+
+
+def identity(point: list[float]) -> list[float]:
+ return list(point)
+
+
+def diverging_joints(height: float = 1.0):
+ """Joint 0 holds still, joint 1 swings 40 degrees about a pivot below the seam.
+
+ Any pair of vertices bound to different joints must separate under this; that separation is the
+ defect being measured, not an artefact of the fixture.
+ """
+ return [identity, rotate_about_z(40.0, [0.0, -0.4 * height, 0.0])]
+
+
+def pose(binding: SkinBinding, joints, index: int) -> list[list[float]]:
+ """Linear blend skinning of one vertex: v' = sum_i w_i * (M_i . v)."""
+ point = binding.positions[index]
+ result = [0.0, 0.0, 0.0]
+ for joint, weight in binding.influences(index):
+ if weight == 0.0:
+ continue
+ moved = joints[joint](point)
+ for axis in range(3):
+ result[axis] += weight * moved[axis]
+ return result
+
+
+def separation(binding: SkinBinding, joints, a: int, b: int) -> float:
+ return math.dist(pose(binding, joints, a), pose(binding, joints, b))
+
+
+def slots(binding: SkinBinding, index: int) -> tuple[list[int], list[float]]:
+ base = index * MAX_INFLUENCES
+ return (
+ binding.skin_indices[base : base + MAX_INFLUENCES],
+ binding.skin_weights[base : base + MAX_INFLUENCES],
+ )
+
+
+class TheDefectThisFixes(unittest.TestCase):
+ """The seam tear, measured on a posed mesh before and after blending."""
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.fixture = Fixture()
+ cls.joints = diverging_joints()
+ cls.blended, cls.report = blend_weights(cls.fixture.binding, 1.0)
+
+ def test_the_probe_vertices_really_are_coincident_and_differently_bound(self) -> None:
+ # If this were false the measurement below would prove nothing.
+ source = self.fixture.binding
+ self.assertEqual(
+ source.positions[self.fixture.torso_probe], source.positions[self.fixture.arm_probe]
+ )
+ self.assertNotEqual(
+ source.influences(self.fixture.torso_probe)[0][0],
+ source.influences(self.fixture.arm_probe)[0][0],
+ )
+ self.assertNotEqual(
+ source.part_ids[self.fixture.torso_probe], source.part_ids[self.fixture.arm_probe]
+ )
+
+ def test_coincident_vertices_bound_to_different_joints_stop_separating(self) -> None:
+ before = separation(
+ self.fixture.binding, self.joints, self.fixture.torso_probe, self.fixture.arm_probe
+ )
+ after = separation(
+ self.blended, self.joints, self.fixture.torso_probe, self.fixture.arm_probe
+ )
+ # The tear is real before the blend: two vertices at the same point in bind pose end up a
+ # quarter of a figure height apart once their joints diverge. That is the hole.
+ self.assertGreater(before, 0.2)
+ # And it is gone afterwards. Both vertices see the same neighbourhood -- each contains the
+ # other at distance 0 -- so they get the same mixed field and the same reduced binding, and
+ # a shared binding cannot separate under any pose.
+ self.assertLess(after, before * 0.01)
+
+ def test_the_blend_does_not_work_by_freezing_the_arm(self) -> None:
+ # A fix that simply averaged everything toward the torso would also close the seam, and would
+ # be useless. Deep arm vertices must still move with the arm joint alone.
+ moved = pose(self.blended, self.joints, self.fixture.arm_interior)
+ expected = self.joints[ARM](self.blended.positions[self.fixture.arm_interior])
+ self.assertLess(math.dist(moved, expected), 1e-12)
+
+ def test_the_report_counts_what_it_touched(self) -> None:
+ total = self.fixture.binding.vertex_count
+ self.assertEqual(
+ self.report.vertices_touched
+ + self.report.vertices_interior
+ + self.report.vertices_without_weight,
+ total,
+ )
+ self.assertGreater(self.report.vertices_touched, 0)
+ self.assertEqual(self.report.radius_fraction, BLEND_RADIUS)
+ self.assertAlmostEqual(self.report.radius_world, BLEND_RADIUS * 1.0)
+
+
+class WeldingWasNotEnough(unittest.TestCase):
+ """The rejected approach, reproduced so it can never come back.
+
+ Coincidence welding closed one visible crack and left 28 of 132 swept frames still cracked. The
+ reason is geometric, not a tuning failure: adjacent parts mostly OVERLAP rather than share a rim,
+ so on a real seam there is nothing within 1e-4 H to weld.
+ """
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ # arm_shift = -0.001H: the parts interpenetrate, and the nearest cross-part pair is 0.001H
+ # apart -- ten times the weld tolerance, well inside the blend radius.
+ cls.fixture = Fixture(arm_shift=-0.001)
+ cls.joints = diverging_joints()
+ cls.welded, cls.welded_groups = weld_coincident(cls.fixture.binding, 1.0)
+ cls.blended, _ = blend_weights(cls.fixture.binding, 1.0)
+
+ def test_the_overlap_fixture_has_nothing_exactly_coincident(self) -> None:
+ source = self.fixture.binding
+ nearest = min(
+ math.dist(source.positions[a], source.positions[b])
+ for a in range(source.vertex_count)
+ for b in range(source.vertex_count)
+ if a < b and source.part_ids[a] != source.part_ids[b]
+ )
+ self.assertGreater(nearest, 1e-4)
+ self.assertLess(nearest, BLEND_RADIUS)
+
+ def test_welding_finds_nothing_to_weld_and_changes_nothing(self) -> None:
+ self.assertEqual(self.welded_groups, 0)
+ self.assertEqual(self.welded.skin_indices, self.fixture.binding.skin_indices)
+ self.assertEqual(self.welded.skin_weights, self.fixture.binding.skin_weights)
+
+ def test_the_seam_still_opens_after_welding_but_not_after_blending(self) -> None:
+ probes = (self.fixture.torso_probe, self.fixture.arm_probe)
+ bind_gap = math.dist(
+ self.fixture.binding.positions[probes[0]], self.fixture.binding.positions[probes[1]]
+ )
+ opened_unfixed = separation(self.fixture.binding, self.joints, *probes) - bind_gap
+ opened_welded = separation(self.welded, self.joints, *probes) - bind_gap
+ opened_blended = separation(self.blended, self.joints, *probes) - bind_gap
+ # Welding is a no-op here, so the hole is exactly as wide as it was.
+ self.assertAlmostEqual(opened_welded, opened_unfixed, places=12)
+ self.assertGreater(opened_unfixed, 0.2)
+ # Blending is not a no-op on the same geometry. The parts do not become identical -- these
+ # vertices are not coincident -- but the seam closes by most of its width.
+ self.assertLess(opened_blended, opened_unfixed * 0.25)
+
+
+class DenseAccumulation(unittest.TestCase):
+ """Expand to a dense vector over all joints before mixing, reduce back to 4 afterwards."""
+
+ @classmethod
+ def setUpClass(cls) -> None:
+ # A centre vertex bound to joints 0 and 1, with four foreign neighbours referencing joints
+ # 2, 3, 4 and 5 at increasing distance. Six distinct joints in the neighbourhood, four slots
+ # to hold them.
+ positions = [[0.0, 0.0, 0.0]]
+ parts = ["a"]
+ indices = [0, 1, 0, 0]
+ weights = [0.7, 0.3, 0.0, 0.0]
+ for offset, joint in ((0.0010, 2), (0.0015, 3), (0.0020, 4), (0.0025, 5)):
+ positions.append([offset, 0.0, 0.0])
+ parts.append("b")
+ indices.extend([joint, 0, 0, 0])
+ weights.extend([1.0, 0.0, 0.0, 0.0])
+ cls.source = SkinBinding(positions, parts, indices, weights, joint_count=6)
+ cls.blended, cls.report = blend_weights(cls.source, 1.0)
+
+ def dense_by_hand(self) -> dict[int, float]:
+ """The mixed field at the centre vertex, recomputed independently of the module."""
+ radius = BLEND_RADIUS
+ field: dict[int, float] = {}
+ for index, point in enumerate(self.source.positions):
+ distance = math.dist(self.source.positions[0], point)
+ if distance > radius:
+ continue
+ kernel = (1.0 - distance / radius) ** 2
+ for joint, weight in self.source.influences(index):
+ if weight > 0.0:
+ field[joint] = field.get(joint, 0.0) + weight * kernel
+ return field
+
+ def sparse_mix_by_hand(self) -> set[int]:
+ """The WRONG method: mix into the four slots the vertex already has and drop the rest."""
+ radius = BLEND_RADIUS
+ own = {joint for joint, weight in self.source.influences(0) if weight > 0.0}
+ field = {joint: weight for joint, weight in self.source.influences(0) if weight > 0.0}
+ for index, point in enumerate(self.source.positions[1:], start=1):
+ distance = math.dist(self.source.positions[0], point)
+ if distance > radius:
+ continue
+ kernel = (1.0 - distance / radius) ** 2
+ for joint, weight in self.source.influences(index):
+ if weight > 0.0 and joint in own:
+ field[joint] += weight * kernel
+ return set(field)
+
+ def test_the_neighbourhood_really_references_more_than_four_joints(self) -> None:
+ self.assertGreater(len(self.dense_by_hand()), MAX_INFLUENCES)
+ self.assertGreaterEqual(self.report.max_influences_seen, len(self.dense_by_hand()))
+
+ def test_the_four_largest_influences_of_the_full_field_survive(self) -> None:
+ expected = [
+ joint
+ for joint, _ in sorted(self.dense_by_hand().items(), key=lambda kv: (-kv[1], kv[0]))
+ ][:MAX_INFLUENCES]
+ got, _ = slots(self.blended, 0)
+ self.assertEqual(got, expected)
+
+ def test_mixing_the_sparse_slots_directly_would_give_a_different_answer(self) -> None:
+ # This is why the dense expansion is not an optimisation detail. The sparse mix can only ever
+ # return joints the vertex already had, so every influence arriving from the other part --
+ # which is the entire point of the blend -- is dropped before it is even weighed.
+ wrong = self.sparse_mix_by_hand()
+ got, _ = slots(self.blended, 0)
+ self.assertNotEqual(set(got), wrong)
+ self.assertTrue(set(got) - wrong, "the dense field must keep joints the sparse mix loses")
+
+ def test_a_lossy_reduction_is_reported_not_hidden(self) -> None:
+ # Six influences into four slots throws real weight away here. The number is reported so a
+ # caller can see it; hiding it would make a visibly wrong deformation look like a clean run.
+ self.assertGreaterEqual(self.report.lossy_reductions, 1)
+ self.assertGreater(self.report.max_discarded_fraction, 0.0)
+
+
+class WriteAfterAllReads(unittest.TestCase):
+ def test_shuffling_the_vertex_order_changes_nothing(self) -> None:
+ fixture = Fixture()
+ source = fixture.binding
+ order = list(range(source.vertex_count))
+ random.Random(20250825).shuffle(order)
+
+ shuffled = SkinBinding(
+ positions=[source.positions[i] for i in order],
+ part_ids=[source.part_ids[i] for i in order],
+ skin_indices=[
+ source.skin_indices[i * MAX_INFLUENCES + slot]
+ for i in order
+ for slot in range(MAX_INFLUENCES)
+ ],
+ skin_weights=[
+ source.skin_weights[i * MAX_INFLUENCES + slot]
+ for i in order
+ for slot in range(MAX_INFLUENCES)
+ ],
+ joint_count=source.joint_count,
+ )
+
+ straight, _ = blend_weights(source, 1.0)
+ mixed, _ = blend_weights(shuffled, 1.0)
+ for position, original in enumerate(order):
+ self.assertEqual(
+ slots(mixed, position),
+ slots(straight, original),
+ f"vertex {original} blended differently when visited in a different order",
+ )
+
+
+class InteriorVerticesAreNeverTouched(unittest.TestCase):
+ def test_interior_vertices_are_bit_identical_to_the_source(self) -> None:
+ fixture = Fixture()
+ source = fixture.binding
+ blended, report = blend_weights(source, 1.0)
+ for index in (fixture.torso_interior, fixture.arm_interior):
+ source_indices, source_weights = slots(source, index)
+ blended_indices, blended_weights = slots(blended, index)
+ self.assertEqual(blended_indices, source_indices)
+ # Bit-identical, not merely close: a recomputed interior weight would put a difference
+ # into every vertex of the model for no reason at all.
+ self.assertEqual(blended_weights, source_weights)
+ for got, want in zip(blended_weights, source_weights):
+ self.assertEqual(math.copysign(1.0, got), math.copysign(1.0, want))
+ self.assertGreaterEqual(report.vertices_interior, 2)
+
+ def test_a_vertex_with_a_foreign_neighbour_just_outside_the_radius_stays_interior(self) -> None:
+ # The boundary case: one part's vertex sits a hair beyond R from the other part.
+ positions = [[0.0, 0.0, 0.0], [BLEND_RADIUS * 1.0001, 0.0, 0.0]]
+ source = SkinBinding(positions, ["a", "b"], [0, 0, 0, 0, 1, 0, 0, 0],
+ [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0], joint_count=2)
+ blended, report = blend_weights(source, 1.0)
+ self.assertEqual(report.vertices_interior, 2)
+ self.assertEqual(report.vertices_touched, 0)
+ self.assertEqual(blended.skin_indices, source.skin_indices)
+ self.assertEqual(blended.skin_weights, source.skin_weights)
+
+
+class GridHash(unittest.TestCase):
+ def test_grid_results_equal_brute_force_results_exactly(self) -> None:
+ rng = random.Random(7)
+ positions = [
+ [rng.uniform(-0.02, 0.02), rng.uniform(-0.02, 0.02), rng.uniform(-0.02, 0.02)]
+ for _ in range(400)
+ ]
+ grid = UniformGrid(positions, BLEND_RADIUS)
+ for point in positions:
+ got = sorted(grid.query(point, BLEND_RADIUS))
+ want = sorted(brute_force_query(positions, point, BLEND_RADIUS))
+ self.assertEqual(got, want)
+
+ def test_a_query_touches_at_most_27_buckets(self) -> None:
+ # One cell per radius is what bounds this. The bound is the reason the stage survives a real
+ # mesh: brute force is O(n^2) and unusable past ~50k vertices.
+ self.assertEqual(len(_CELL_OFFSETS), 27)
+ rng = random.Random(11)
+ positions = [
+ [rng.uniform(-0.05, 0.05), rng.uniform(-0.05, 0.05), rng.uniform(-0.05, 0.05)]
+ for _ in range(2000)
+ ]
+ grid = UniformGrid(positions, BLEND_RADIUS)
+ queries = 0
+ for point in positions:
+ grid.query(point, BLEND_RADIUS)
+ queries += 1
+ self.assertLessEqual(grid.max_buckets_per_query, 27)
+ self.assertEqual(grid.buckets_visited, queries * 27)
+
+ def test_a_query_wider_than_the_cell_is_refused_not_silently_wrong(self) -> None:
+ grid = UniformGrid([[0.0, 0.0, 0.0]], BLEND_RADIUS)
+ with self.assertRaises(ValueError):
+ grid.query([0.0, 0.0, 0.0], BLEND_RADIUS * 2)
+
+
+class GateR2(unittest.TestCase):
+ def test_a_blended_binding_passes_the_gate(self) -> None:
+ blended, _ = blend_weights(Fixture().binding, 1.0)
+ self.assertEqual(validate_binding(blended), [])
+
+ def test_weights_renormalise_within_tolerance(self) -> None:
+ blended, _ = blend_weights(Fixture().binding, 1.0)
+ worst = max(
+ abs(1.0 - math.fsum(slots(blended, index)[1]))
+ for index in range(blended.vertex_count)
+ )
+ self.assertLessEqual(worst, WEIGHT_SUM_TOLERANCE)
+
+ def test_every_index_stays_in_range_after_reduction(self) -> None:
+ positions = [[0.0, 0.0, 0.0], [0.001, 0.0, 0.0], [0.002, 0.0, 0.0]]
+ binding = SkinBinding(
+ positions,
+ ["a", "b", "b"],
+ [0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0],
+ [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0],
+ joint_count=3,
+ )
+ blended, _ = blend_weights(binding, 1.0)
+ self.assertLessEqual(max(blended.skin_indices), blended.joint_count - 1)
+ self.assertGreaterEqual(min(blended.skin_indices), 0)
+ self.assertEqual(validate_binding(blended), [])
+
+ def test_the_gate_actually_fails_a_broken_binding(self) -> None:
+ # A gate that cannot fail proves nothing about the bindings that pass it.
+ broken = SkinBinding(
+ positions=[[0.0, 0.0, 0.0]],
+ part_ids=["a"],
+ skin_indices=[9, 0, 0, 0],
+ skin_weights=[0.5, 0.0, 0.0, 0.0],
+ joint_count=2,
+ )
+ failures = validate_binding(broken)
+ self.assertTrue(any("sum(w)" in message for message in failures))
+ self.assertTrue(any("outside" in message for message in failures))
+
+
+class RadiusScalesWithHeight(unittest.TestCase):
+ def test_the_same_figure_at_double_height_blends_identically(self) -> None:
+ # R is a fraction of H, so doubling every coordinate and H must be invisible to the weights.
+ # A radius in absolute units would silently stop reaching across the seam on a taller rig.
+ small, _ = blend_weights(Fixture(height=1.0).binding, 1.0)
+ large, _ = blend_weights(Fixture(height=2.0).binding, 2.0)
+ for index in range(small.vertex_count):
+ self.assertEqual(slots(large, index), slots(small, index))
+
+ def test_a_caller_supplied_radius_is_the_one_recorded(self) -> None:
+ _, report = blend_weights(Fixture().binding, 1.0, radius=0.012)
+ self.assertEqual(report.radius_fraction, 0.012)
+ self.assertAlmostEqual(report.radius_world, 0.012)
+
+ def test_rejects_input_it_cannot_blend(self) -> None:
+ fixture = Fixture()
+ with self.assertRaises(ValueError):
+ blend_weights(fixture.binding, 0.0)
+ with self.assertRaises(ValueError):
+ blend_weights(fixture.binding, 1.0, radius=0.0)
+ with self.assertRaises(ValueError):
+ blend_weights(
+ SkinBinding([[0.0, 0.0, 0.0]], ["a"], [0, 0, 0, 0], [1.0, 0.0, 0.0], 1), 1.0
+ )
+
+
+class DoesNotMutateItsInput(unittest.TestCase):
+ def test_the_source_binding_is_untouched(self) -> None:
+ fixture = Fixture()
+ before_indices = list(fixture.binding.skin_indices)
+ before_weights = list(fixture.binding.skin_weights)
+ before_positions = [list(point) for point in fixture.binding.positions]
+ blend_weights(fixture.binding, 1.0)
+ self.assertEqual(fixture.binding.skin_indices, before_indices)
+ self.assertEqual(fixture.binding.skin_weights, before_weights)
+ self.assertEqual(fixture.binding.positions, before_positions)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/grimoire/readiness/animation_contract.md b/grimoire/readiness/animation_contract.md
new file mode 100644
index 0000000..6ad2778
--- /dev/null
+++ b/grimoire/readiness/animation_contract.md
@@ -0,0 +1,78 @@
+# Animation contract — 1.5.2
+
+Read this when a character rig must **move**, not merely bind. The payload/bind contract lives in
+`procedural_rigging_contract.md`; this file covers what happens after a skeleton exists. The full
+derivation, the measured numbers and the failure log are in
+`docs/pipelines/character-rigging-animation-1.5.2.md` — read that file at the moment you reach
+Stage R, not before.
+
+Every threshold is a fraction of **figure height H**, never an absolute unit. A rig at a different
+scale converts; no module may assume `H == 1.0`.
+
+## The one rule
+
+> Nothing about a rig is believed until it has been evaluated at a sampled time and compared
+> against the value the track says it should have. **A clip that exists is not a clip that plays.**
+
+Two separate 1.5.1 bugs each produced a plausible scene with **zero motion**: eleven clips held
+actions, the mixer held state, buttons dispatched, nothing moved. Neither was visible in code
+review. Both were found only by measuring.
+
+## Stage order and the script that owns each
+
+| Stage | What it decides | Script |
+| --- | --- | --- |
+| R0 | deform vs technical nodes, skeleton index space, landmarks | `stage5_rig/validate_rig_payload.py` |
+| R1 | bind space — identity bind, offset from bounds alone | `stage5_rig/emit_animation_runtime.py` |
+| R2 | skin conditioning — proximity weight blending | `stage5_rig/skin_conditioning.py` |
+| R3 | clip identification — measure, classify, name, loop | `stage5_rig/clip_features.py` |
+| R4 | action design — author to a target band, then prove it | `stage5_rig/action_design.py` |
+| R5 | runtime assembly — tickers, offsets, controller contract | `stage5_rig/emit_animation_runtime.py` |
+| R6 | gates G1–G10 | `stage5_rig/rig_gates.py` |
+
+The module boundaries and the sampled-clip payload shape are fixed in
+`forge/stage5_rig/CONTRACT_1.5.2.md`.
+
+## Hard rules, one line each
+
+- A node is a `Bone` **iff it appears in `skin.joints`**. Never infer from names — clips target
+ technical nodes that are not joints, and building those as bones corrupts the index space.
+- Build all nodes, then attach children, then attach roots. Any other order leaves world matrices
+ stale at skeleton time.
+- `mesh.bind(skeleton, new THREE.Matrix4())` — identity, always, in attached bind mode. The
+ armature transform is already inside `skinMatrix`; adding it again double-counts.
+- Display offset comes from the **mesh bounds alone**: `(−centre.x, −min.y, −centre.z)`.
+- `scaleDelta ≠ 0` is a tripwire, not a descriptor. Surface it before anything else proceeds: a
+ rig that scales joints changes what R2 may legally do to skin weights.
+- Loop is decided by **poseReturn**, not by travel: `poseReturn ≤ 0.5°` **and**
+ `‖hip(T) − hip(0)‖ ≤ 0.01H`. The 1.5.1 rule contradicted its own data.
+- Names that describe motion are provable; names that imply intent are not. Intent carries
+ `inferred: true` — that is the honest answer, not a placeholder for a better classifier.
+- R2 trades holes against creases deliberately: **a hole shows the background, a crease shows
+ skin.** A later stage must never "fix" the crease count by disabling the blend.
+- A lazily-built character MUST trigger `refreshTickers()` when its payload resolves, or every
+ clip plays silently in a scene that otherwise renders correctly.
+- Presentation offsets are removed before the rig ticks and re-applied after. Never restore a
+ cached rest pose — it overwrites the pose the animation just produced.
+
+## Gates — nothing ships until all pass
+
+`G1` binding reaches node (`maxSampledBindingDelta ≤ 2⁻²³`) · `G2` deformation finite ·
+`G3` bind restore (`≤ 1e-12`) · `G4` weights normalised (`≤ 2e-7`) · `G5` indices in range ·
+`G6` every visible mesh bound · `G7` medial/lateral (`leftAnchor.x > 0 > rightAnchor.x`) ·
+`G8` foot contact (`footSlide ≤ 0.01H`) · `G9` no joint scale · `G10` skin integrity sweep.
+
+**G1 is the gate that catches silent death** — it is the only check that distinguishes a clip that
+plays from one that exists, loads, holds an action and reports a duration while driving nothing.
+
+**G10 needs a harness, and five poses is not coverage.** The sweep that found the real defects was
+11 clips × 4 times × 2 sides × 2 azimuths = **176 frames**. Report holes and creases as two
+numbers; a single combined score hides the R2 trade.
+
+A gate whose input is absent reports `unevaluated` with a reason. It is never silently a pass.
+
+## What this does not solve
+
+Creases at part overlaps (needs one continuous mesh with a unified weight field — a different
+topology contract), retargeting between skeletons (needs joint correspondence and its own gates),
+and intent (no measurement distinguishes a strike from a stumble).