Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.
Python 3dai-agentsclaude-codecomputer-graphicsgenerativeimage-to-3dprocedural-generationthreejstypescriptwebgl
Merge main (v1.5.2) into lab/cs2-plugin
kokorolx8e3d856db173
diff --cc CHANGELOG.mdindex 9da8e9a,b4fd0e9..0789cc5--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,32 -7,117 +7,144 @@@ and this project adheres to [Semantic V## [Unreleased]+### Changed — BREAKING++- **A domain is no longer inferred from the target's name.** `detect_cs2_intent` and its 17-keyword+ table (including bare `"fade"` and `"karambit"`) are removed, so a target called+ `"AK-47 | Redline"` or `"Karambit Doppler"` no longer identifies itself as CS2 — it resolves to the+ generic `core_3d` evidence collection like any other object. Declare the domain instead; `--cs2`+ and `--profile cs2` are unchanged. Name similarity is not a legitimate resolution input+ (`PLUGIN_CONTRACT.md` §13), and the old heuristic silently applied CS2's quality floors and+ evidence collection to anything whose name happened to contain one of those words.+- The local-spec-search collection now defaults to `core_3d` rather than `cs2`. That step runs on+ every profile, so every generic run was previously searching a domain corpus by default.+- `objectClass.cs2: true` is replaced by `objectClass.domain: "<id>"`. Specs authored before this+ change carry the old field.+- `weapon-v1.4` no longer requires a CS2 marker to pass strict validation. It is the weapon *shape*+ template, keyed by classified kind, and CS2 is a finish/material domain riding the generic+ hard-surface path — so requiring the marker meant a plain sword could pass only by being labelled a+ CS2 skin. Domain coherence is still enforced by `validate_cs2_contract`.++### Added++- `forge/_shared/domains/` — a domain registry. Each module declares one `DOMAIN` mapping+ contributing checklist steps, a splice anchor, and an evidence collection; registration is by+ presence, so the base pipeline holds no list of domain names. `--profile` choices derive from it,+ and an unregistered profile fails loud naming what is available instead of quietly running as+ generic. `workflow_state.py` and `forge/state.py` now contain no domain name at all.++ **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++- **`animated-character` workflow profile** (now `forge/_shared/domains/animated_character.py` --++ ported from the hardcoded `RIG_STEPS` into the domain registry when this branch merged v1.5.2;++ the registry gained a `rigSteps` key, appended after the FINAL steps). 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### Addeddiff --cc SKILL.mdindex 1a7c2fa,42f5366..5d95c55--- a/SKILL.md+++ b/SKILL.md@@@ -62,7 -58,7 +62,7 @@@ Conversation context is disposable; `.iInitialize once per reconstruction, then gate every step through it:```bash- python3 forge/state.py init --state .img2threejs/state.json --reference <img> --profile <generic|installed-domain> --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/state.py init --state .img2threejs/state.json --reference <img> --profile <generic|character|animated-character|installed-domain> --spec object-sculpt-spec.jsonpython3 forge/next.py --state .img2threejs/state.json [object-sculpt-spec.json]python3 forge/state.py mark <step-id> --state .img2threejs/state.json --evidence <path>```@@@ -73,12 -69,13 +73,17 @@@- Every completed step needs evidence; mark a non-applicable step `skipped` only with `--reason` —silent omission is forbidden. Loop counts derive from `reviewHistory` actions(`refine-spec`/`refine-code`), not agent memory. Defaults: 3 corrections per pass, 6 total.- - A domain profile's steps, gates and reference material come from its **installed plugin**, not- from this checkout; with no plugin installed only `generic` is available and `forge/state.py init`- names what is. A profile adds mandatory gates without changing the core order -- a domain plugin- typically requires an authoritative classification, an intake manifest, and a machine-readable- domain review before AI review; `character` requires the character- contracts and landmark evidence. Every profile records suitability, projection applicability, and-- 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; `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++- A domain profile's steps, gates and reference material come from the **registry**: in-repo++ modules (`character`, `animated-character`) and installed plugins register identically, and++ `forge/state.py init` names what is available. A profile adds mandatory gates without changing++ the core order -- a domain plugin typically requires an authoritative classification, an intake++ manifest, and a machine-readable domain review before AI review; `character` requires the++ character 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, andmaterial-evidence applicability. The state file is a resumability index, not visual evidence:renders, specs, review history, and deterministic gates remain the authoritative artifacts.@@@ -294,7 -289,12 +299,12 @@@ attachment, material, detail inventorypasses 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.+- A domain plugin's review gate also runs against its versioned scene fixture.- Local state enforces 3 corrections per pass and 6 total by default; reaching either limit is ahard stop. `correction_loop.py` may stop earlier on repeated defects, oscillation, or plateau.- `continue` requires a render + comparison sheet + AI-vision score ≥ threshold, every criticaldiff --cc forge/_shared/domains/__init__.pyindex 86ae333,0000000..8ce8ad1mode 100644,000000..100644--- a/forge/_shared/domains/__init__.py+++ b/forge/_shared/domains/__init__.py@@@ -1,164 -1,0 +1,167 @@@+"""Domain profiles the base pipeline can run.++The base pipeline names no domain. It asks this registry what is available, and a domain contributes+its own steps, its own evidence collection and its own track. Each module in this package declares a+single `DOMAIN` mapping; registration is by presence, not by the base holding a list of names.++This is the extension point the CS2 extraction needs. Today both entries are in-repo. When a domain+moves out to a plugin, its module leaves this directory and the harness supplies the same mapping+instead -- the base pipeline does not change either way, which is the property being bought here.++Required keys:+ id the profile identifier a run is started with+Optional keys, each defaulting to "contributes nothing":+ setupSteps ((step_id, command), ...) spliced into the setup phase+ setupAnchorBefore base step id to splice before; required when setupSteps is non-empty+ passSteps ((step_id, command), ...) spliced into every correction pass+ passAnchorBefore base step id to splice before; required when passSteps is non-empty+ specCollection an extra local-evidence collection to search++ rigSteps ((step_id, command), ...) appended after the FINAL steps as the rig track;++ no anchor -- the rig phase always follows the terminal steps (v1.5.2)+"""++from __future__ import annotations++import importlib.util+import json+import os+from pathlib import Path+from typing import Any, Final++_PACKAGE_DIR: Final = Path(__file__).resolve().parent++_REQUIRED: Final = ("id",)+_ALLOWED: Final = {+ "id",+ "setupSteps",+ "setupAnchorBefore",+ "passSteps",+ "passAnchorBefore",+ "specCollection",++ "rigSteps",+}+++class DomainRegistryError(ValueError):+ pass+++def _load_module(path: Path) -> Any:+ spec = importlib.util.spec_from_file_location(f"_img2_domain_{path.stem}", path)+ if spec is None or spec.loader is None:+ raise DomainRegistryError(f"cannot load domain module {path}")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _validate(entry: Any, source: Path) -> dict[str, Any]:+ if not isinstance(entry, dict):+ raise DomainRegistryError(f"{source.name}: DOMAIN must be a mapping")+ for key in _REQUIRED:+ if not entry.get(key):+ raise DomainRegistryError(f"{source.name}: DOMAIN is missing required key {key!r}")+ unknown = sorted(set(entry) - _ALLOWED)+ if unknown:+ # Refused rather than ignored: a typo'd key would otherwise silently contribute nothing.+ raise DomainRegistryError(f"{source.name}: DOMAIN has unknown key(s) {unknown}")+ for steps_key, anchor_key in (("setupSteps", "setupAnchorBefore"), ("passSteps", "passAnchorBefore")):+ if entry.get(steps_key) and not entry.get(anchor_key):+ raise DomainRegistryError(f"{source.name}: {steps_key} needs {anchor_key}")+ return entry+++def registered_domains() -> dict[str, dict[str, Any]]:+ """Every domain profile available to this run, keyed by id.++ Two sources, treated identically once loaded: modules in this package (in-repo domains) and+ `domain.json` in each installed plugin. A domain that moves from the first to the second changes+ nothing for the base pipeline -- that equivalence is the point of the registry.+ """+ found: dict[str, dict[str, Any]] = {}++ def claim(entry: Any, source: Path) -> None:+ entry = _validate(entry, source)+ if entry["id"] in found:+ # Two providers claiming one id is ambiguous; the base must not pick one.+ raise DomainRegistryError(f"domain id {entry['id']!r} is declared twice")+ found[entry["id"]] = entry++ for path in sorted(_PACKAGE_DIR.glob("*.py")):+ if path.name == "__init__.py":+ continue+ module = _load_module(path)+ entry = getattr(module, "DOMAIN", None)+ if entry is None:+ raise DomainRegistryError(f"{path.name}: a domain module must declare DOMAIN")+ claim(entry, path)++ for path, entry in _installed_plugin_domains():+ claim(entry, path)++ return found+++def _img2_home() -> Path:+ return Path(os.environ.get("IMG2_HOME") or Path.home() / ".img2")+++def _installed_plugin_domains() -> list[tuple[Path, Any]]:+ """Domain declarations from installed plugins.++ Reads the harness registry rather than globbing the plugins directory, so a checkout left behind+ by a removed plugin does not silently contribute steps. A plugin that ships no `domain.json`+ simply contributes no domain -- it may still provide capabilities.+ """+ registry = _img2_home() / "plugins.json"+ if not registry.is_file():+ return []+ try:+ rows = json.loads(registry.read_text(encoding="utf-8")).get("plugins") or []+ except (OSError, json.JSONDecodeError) as exc:+ raise DomainRegistryError(f"cannot read the plugin registry at {registry}: {exc}") from exc++ out: list[tuple[Path, Any]] = []+ for row in rows:+ plugin_id = (row or {}).get("id")+ if not plugin_id:+ continue+ declaration = _img2_home() / "plugins" / plugin_id / "domain.json"+ if not declaration.is_file():+ continue+ try:+ entry = json.loads(declaration.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ raise DomainRegistryError(f"cannot read {declaration}: {exc}") from exc+ # Steps arrive as JSON arrays; the splice unpacks them as (id, command) pairs. {plugin_dir}+ # is resolved here, the same substitution the harness performs, so a checklist command a+ # plugin supplied is runnable from the workspace without the caller knowing where it lives.+ plugin_dir = str(declaration.parent)- for key in ("setupSteps", "passSteps"):++ for key in ("setupSteps", "passSteps", "rigSteps"):+ if key in entry:+ try:+ entry[key] = tuple(+ (step_id, command.replace("{plugin_dir}", plugin_dir)) for step_id, command in entry[key]+ )+ except (TypeError, ValueError, AttributeError) as exc:+ # Unpacking used to run before validation, so a malformed row surfaced as a bare+ # ValueError/AttributeError instead of an error naming the file at fault.+ raise DomainRegistryError(+ f"{declaration}: {key!r} rows must be [id, command] pairs of strings"+ ) from exc+ out.append((declaration, entry))+ return out+++def domain_profile(profile: str) -> dict[str, Any] | None:+ """The registered domain for `profile`, or None for the generic pipeline."""+ if profile == "generic":+ return None+ domains = registered_domains()+ if profile not in domains:+ known = ", ".join(sorted(["generic", *domains]))+ raise DomainRegistryError(+ f"no installed provider serves profile {profile!r}; available: {known}. "+ "Install the domain plugin that provides it, or start the run as generic."+ )+ return domains[profile]diff --cc forge/_shared/domains/animated_character.pyindex 0000000,0000000..52c0fdanew file mode 100644--- /dev/null+++ b/forge/_shared/domains/animated_character.py@@@ -1,0 -1,0 +1,87 @@@++"""Animated-character domain profile (Stage R, v1.5.2's rigging/animation pipeline).++++Ported from the hardcoded `RIG_STEPS`/profile branch v1.5.2 added on main into the registry the++CS2 extraction introduced, in the same merge that brought the two together: an animated character++is a character (same setup contributions) plus the rig track appended after the FINAL steps.++++Rig docs: docs/pipelines/character-rigging-animation-1.5.2.md.++++These rig steps 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 of rigSteps 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.++"""++++from __future__ import annotations++++from typing import Any, Final++++DOMAIN: Final[dict[str, Any]] = {++ "id": "animated-character",++ # An animated character is still a character; the anatomy contract must not be lost. The two++ # steps are declared here rather than imported from character.py: registry modules load++ # independently (importlib by path), and each declaration stays readable on its own.++ "setupSteps": (++ (++ "character-contract-read",++ "Read grimoire/character/reconstruction.md and grimoire/character/likeness_maximization.md completely",++ ),++ (++ "character-landmarks",++ "python3 forge/stage1_intake/extract_landmarks.py {reference} --out anatomy.json --overlay landmarks.png",++ ),++ ),++ "setupAnchorBefore": "local-spec-search",++ "rigSteps": (++ (++ "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)",++ ),++ ),++}diff --cc forge/_shared/workflow_state.pyindex d84d4e9,0172bd7..7d9d610--- a/forge/_shared/workflow_state.py+++ b/forge/_shared/workflow_state.py@@@ -63,35 -69,75 +63,34 @@@ PASS_STEPS: Final =FINAL_STEPS: Final = (("part-coverage", "python3 forge/stage4_review/check_part_coverage.py --spec {spec} --manifest parts.json"),("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)",- ),+ # D4/task 3.8: base-owned, appended unconditionally -- no plugin ever splices this in (there is+ # no `finalSteps` key in domains/__init__.py's _ALLOWED, deliberately: a plugin must never be+ # able to change what runs at the terminal phase behind the user's back). An explicit+ # `--target <kind>` is the only thing that ever populates this step: on a successful run,+ # `emit_target.record_target_selection` marks it `done` and records which plugin ran (or+ # `None` for the reference target) in the new `targetSelection` state field, which slice 4's+ # gate-participation rule reads. With no `--target`, emit_target.py's no-op path (D2) never+ # touches this file at all -- correcting an earlier claim in this comment that the no-op path+ # marks the row "done"; it does not, and this row is left `pending` on that path (a stated,+ # not-yet-resolved rough edge: forge/next.py will keep naming it as the next required step+ # even though there is nothing further to do when no target will ever be selected). Round-3 H6:+ # workspaces created before this change do not carry this row in their persisted checklist+ # (new_state() materialises FINAL_STEPS once, at init) -- not breakage, since nothing crashes and+ # SCHEMA_VERSION stays 1, but emit_target.py's own action-ready precondition still enforces+ # terminal-only there directly, independent of whether this row exists in a given state file.(- "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)",+ "emission-target",+ "python3 forge/stage3_build/emit_target.py --spec {spec} --workspace . "+ "[--target <kind> [--plugin <id>]]",),+ # task 4.2's proposed hook point (see run_gates.py's module docstring for the full rationale):+ # a distinct checklist step, not auto-chained inside emit_target.py, following the same+ # discipline every other FINAL_STEPS/PASS_STEPS row already has -- the agent invokes it, it is+ # not triggered by the step before it. Harmless with no plugin involved: the two-clause rule+ # naturally yields zero gates to run, and this exits 0 having done nothing.+ ("plugin-gates", "python3 forge/stage3_build/run_gates.py --workspace ."),)--class WorkflowStateError(ValueError):pass@@@ -158,7 -183,12 +157,8 @@@ 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 []- ),++ + [_step(*item, scope="rig") for item in ((domain.get("rigSteps") or ()) if domain else ())],"loops": {"perPass": {},"total": 0,diff --cc forge/tests/test_rig_workflow_steps.pyindex 0000000,3d9b761..91a99f2mode 000000,100644..100644--- a/forge/tests/test_rig_workflow_steps.py+++ b/forge/tests/test_rig_workflow_steps.py@@@ -1,0 -1,209 +1,211 @@@+ #!/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"):++ def test_profiles_without_rig_steps_get_none(self) -> None:++ # "cs2" left this list when the domain moved to its installed plugin (a registry profile++ # would need IMG2_HOME pinned here); generic and character cover the no-rigSteps rule.++ for profile in ("generic", "character"):+ 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()