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.

feat: add the emission-target socket behind an explicit --target

kokorolx12843ff504d1
diff --git a/CLAUDE.md b/CLAUDE.md
index 04f2bb6..b739876 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -47,3 +47,10 @@ implementation claims and completion:
5. If capture, file write, readback, comparison, scoring, or diagnosis fails, stop the visual
workflow and repair the tooling first. Do not infer visual evidence from runtime readiness,
structural tests, inline previews, or code review, and do not claim the visual gate passed.
+
+**Scope of this gate.** It governs the Three.js reconstruction this repository builds — the
+procedural model and its self-correction loop. An exported artifact produced by an explicitly-selected
+emission target (`--target <kind>`) is a different thing: it is verified to the base's own stated
+limit — container/structure check where a prober exists, existence/size/location/determinism
+otherwise — and is never reported under this gate's completion vocabulary. The visual fidelity of an
+export, if any is claimed, is that target plugin's own gate's responsibility, not this one's.
diff --git a/SKILL.md b/SKILL.md
index ad9c178..1a7c2fa 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -9,7 +9,11 @@ version: 1.5.1
Rebuild the object visible in a reference image as a **code-only** procedural Three.js model,
gated by a staged sculpting pipeline and an AI-vision self-correction loop. This is
-reconstruction-by-code, **not** photogrammetry, mesh extraction, or downloaded art packs.
+reconstruction-by-code, **not** photogrammetry, mesh extraction, or downloaded art packs. That
+promise governs how the model is *built* — it says nothing about which file formats it can
+subsequently be *exported* to; an explicitly-selected emission target (`--target <kind>`) is a
+terminal, whole-artifact transform of the already-built model, verified to its own stated limit,
+never a second way to build one.
Agent-agnostic: works under Claude Code, Codex, or OpenCode. Wherever this doc says "agent
vision" or "agent browser tool", use whatever the host provides — native image reading, a
diff --git a/forge/_shared/glb_container.py b/forge/_shared/glb_container.py
new file mode 100644
index 0000000..9e32d5a
--- /dev/null
+++ b/forge/_shared/glb_container.py
@@ -0,0 +1,89 @@
+"""The GLB binary-glTF container parse, shared between intake and export.
+
+Extracted from `forge/stage1_intake/probe_glb.py` (task 3.6, `establish-the-emission-target-contract`
+slice 3): the magic/version/chunk parse is intake-domain-independent, but `probe_glb.py` itself is
+not a drop-in for the export side -- it also builds the richer semantic-decomposition report via
+`semantic_decomposition.assess_semantic_decomposition`, which the export tier-1 verifier has no use
+for and should not have to import. This module holds only the container parse: is this a well-formed
+GLB, and (incidentally) what chunks does it carry. `probe_glb.py` now imports `GLB_MAGIC` and
+`parse_glb` from here instead of defining its own copy, so both sides read one implementation.
+"""
+
+from __future__ import annotations
+
+import json
+import struct
+from pathlib import Path
+from typing import Any
+
+GLB_MAGIC = b"glTF"
+JSON_CHUNK = 0x4E4F534A
+BIN_CHUNK = 0x004E4942
+
+
+def _chunk_type_name(chunk_type: int) -> str:
+ try:
+ return chunk_type.to_bytes(4, "little").decode("ascii", errors="replace")
+ except OverflowError:
+ return hex(chunk_type)
+
+
+def parse_glb(path: Path) -> tuple[dict[str, Any], bytes, dict[str, Any]]:
+ """Parse the GLB container: header, chunk table, and the JSON/BIN chunk payloads.
+
+ Raises ValueError naming the specific structural defect on anything malformed -- short header,
+ wrong magic, unsupported version, a length mismatch, a truncated or overrunning chunk, more than
+ one JSON or BIN chunk, a missing JSON chunk, or JSON that isn't a UTF-8 object. This is the
+ complete container check; it does not look inside the document beyond confirming it parses as an
+ object.
+ """
+ data = path.read_bytes()
+ if len(data) < 12:
+ raise ValueError("GLB is shorter than the 12-byte header")
+ magic, version, declared_length = struct.unpack_from("<4sII", data, 0)
+ if magic != GLB_MAGIC:
+ raise ValueError("file does not start with the glTF binary magic")
+ if version != 2:
+ raise ValueError(f"unsupported GLB version {version}; expected 2")
+ if declared_length != len(data):
+ raise ValueError(f"header length {declared_length} does not match file size {len(data)}")
+
+ cursor = 12
+ json_payload: bytes | None = None
+ bin_payload = b""
+ chunks: list[dict[str, Any]] = []
+ while cursor < len(data):
+ if cursor + 8 > len(data):
+ raise ValueError("truncated GLB chunk header")
+ chunk_length, chunk_type = struct.unpack_from("<II", data, cursor)
+ cursor += 8
+ end = cursor + chunk_length
+ if end > len(data):
+ raise ValueError("GLB chunk extends beyond the declared file")
+ payload = data[cursor:end]
+ cursor = end
+ chunks.append({"type": _chunk_type_name(chunk_type), "bytes": chunk_length})
+ if chunk_type == JSON_CHUNK:
+ if json_payload is not None:
+ raise ValueError("GLB contains more than one JSON chunk")
+ json_payload = payload.rstrip(b" \t\r\n\x00")
+ elif chunk_type == BIN_CHUNK:
+ if bin_payload:
+ raise ValueError("GLB contains more than one BIN chunk")
+ bin_payload = payload
+
+ if json_payload is None:
+ raise ValueError("GLB has no JSON chunk")
+ try:
+ document = json.loads(json_payload.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+ raise ValueError(f"GLB JSON chunk is invalid: {exc}") from exc
+ if not isinstance(document, dict):
+ raise ValueError("GLB JSON root must be an object")
+ return document, bin_payload, {
+ "version": version,
+ "declaredLength": declared_length,
+ "jsonChunkBytes": len(json_payload),
+ "binChunkBytes": len(bin_payload),
+ "chunks": chunks,
+ }
diff --git a/forge/_shared/targets.py b/forge/_shared/targets.py
new file mode 100644
index 0000000..dfe5ede
--- /dev/null
+++ b/forge/_shared/targets.py
@@ -0,0 +1,325 @@
+"""Resolve emission targets (design D5, `establish-the-emission-target-contract`).
+
+An emission target is a terminal, whole-artifact transform declared by an installed plugin's
+`steps.json` `provides` row (D1) and discovered through its `plugin.json` capability edge. This
+module answers exactly one question -- "which installed provider, if any, serves `--target <kind>`"
+-- by reading the same `plugins.json` registry the harness's Node CLI writes, plus each candidate
+plugin's own manifest and step declarations.
+
+It is deliberately NOT an extension of `forge/_shared/domains/__init__.py`: that registry's
+`_ALLOWED` key set is a closed domain-profile vocabulary, and the target axis is orthogonal to it
+(D5). `_img2_home()` is duplicated here rather than imported from `domains` for the same reason --
+this module is an independent reader, not a client of the domain registry.
+
+**Fail-loud is scoped to selection time, not import time.** Nothing at module scope touches the
+filesystem; `resolve_target()` is the only entry point that reads `plugins.json`, and it is called
+only after the caller has already decided a target was explicitly requested. A malformed registry
+therefore cannot break `emit_target.py --help` or its no-target default path (round-3 H1's PR #106
+citation: `registered_domains()` running at argparse-construction time is exactly the shape this
+module avoids).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+from pathlib import Path
+from typing import Any, Final, NamedTuple
+
+# Mirrors img2-harness/bin/img2.mjs's MAX_PLUGIN_SCHEMA / CORE_API / MAX_PROVIDES_SCHEMA (`:11-17`).
+# Both languages parse a plugin manifest independently by design (D5) -- doctor-green and
+# base-ran-it must never disagree about what a manifest requires -- so both sides carry the same
+# numbers. There is no shared source for them across the Node/Python boundary; keeping them in sync
+# is a manual discipline, same as CONTRACT_REVISION.
+MAX_PLUGIN_SCHEMA: Final = 1
+CORE_API: Final = 1
+MAX_PROVIDES_SCHEMA: Final = 1
+
+SCULPT_SPEC_KIND: Final = "sculpt-spec"
+REFERENCE_TARGET_KIND: Final = "threejs-ts"
+
+
+class TargetResolutionError(ValueError):
+ """A `--target` request could not be resolved, or a candidate's declaration is invalid.
+
+ The message always names the kind, and for ambiguity every claimant -- callers print
+ `str(exc)` and refuse; there is no fallback to the no-target default from this error (D6:
+ fallback is only for "nothing selected", never for a selection that failed)."""
+
+
+class Target(NamedTuple):
+ kind: str
+ plugin_id: str | None # None only for the base-owned reference target
+ plugin_dir: Path | None # None only for the reference target
+ plugin_version: str | None # the manifest's own "version", for provenance
+ resolved_sha: str | None # the registry row's resolvedSha, for provenance
+ command: str | None # the providing step's raw, unsubstituted command; None for reference
+ step_id: str | None
+ artifact_kind: str
+ artifact_path: str | None # workspace-relative, already prefixed with .img2/artifacts/<plugin-id>/; reference: None
+ deterministic: bool
+ timeout_seconds: int | None # per-step override, or None for the socket's default
+
+
+def _img2_home() -> Path:
+ # Deliberately duplicated from domains/__init__.py:102-103 -- see the module docstring.
+ return Path(os.environ.get("IMG2_HOME") or Path.home() / ".img2")
+
+
+def _harness_version(home: Path) -> str:
+ package_json = home / "harness" / "package.json"
+ try:
+ data = json.loads(package_json.read_text(encoding="utf-8"))
+ version = data.get("version")
+ return version if isinstance(version, str) else "0.0.0"
+ except (OSError, json.JSONDecodeError):
+ return "0.0.0"
+
+
+_SEMVER_RE: Final = re.compile(r"^(\d+)\.(\d+)\.(\d+)$")
+_RANGE_RE: Final = re.compile(r"^>=\s*(\d+)(?:\.(\d+))?(?:\.(\d+))?$")
+
+
+def _parse_semver(value: Any) -> tuple[int, int, int] | None:
+ if not isinstance(value, str):
+ return None
+ match = _SEMVER_RE.match(value.strip())
+ return (int(match[1]), int(match[2]), int(match[3])) if match else None
+
+
+def _range_satisfied(range_str: str, version: str) -> bool:
+ # Same restricted grammar as img2.mjs's rangeSatisfied (":140-152"): only ">=X[.Y[.Z]]",
+ # missing minor/patch defaulting to 0.
+ match = _RANGE_RE.match(range_str.strip())
+ if not match:
+ raise TargetResolutionError(f'unsupported requires.harness range "{range_str}"')
+ minimum = (int(match[1]), int(match[2] or 0), int(match[3] or 0))
+ actual = _parse_semver(version)
+ if actual is None:
+ raise TargetResolutionError(f"unparseable harness version: {version}")
+ return actual >= minimum
+
+
+def _read_json(path: Path, *, what: str) -> Any:
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except FileNotFoundError as exc:
+ raise TargetResolutionError(f"{what} does not exist: {path}") from exc
+ except (OSError, json.JSONDecodeError) as exc:
+ raise TargetResolutionError(f"{what} is not valid JSON: {path}: {exc}") from exc
+
+
+def _validate_manifest(manifest: Any, home: Path, *, plugin_id: str, where: Path) -> dict[str, Any]:
+ """Re-check the manifest rules the Node CLI's `validateManifest` enforces (D5): `schema` <=
+ max, `coreApi` exact equality, `requires.harness` range -- so a plugin that somehow drifted out
+ of doctor-green state (edited by hand, or installed by an older harness) is refused here too,
+ not silently invoked."""
+ if not isinstance(manifest, dict):
+ raise TargetResolutionError(f"plugin {plugin_id!r}: {where} is not a JSON object")
+ schema = manifest.get("schema")
+ if not isinstance(schema, int) or schema < 1:
+ raise TargetResolutionError(f"plugin {plugin_id!r}: manifest \"schema\" must be an integer >= 1")
+ if schema > MAX_PLUGIN_SCHEMA:
+ raise TargetResolutionError(
+ f"plugin {plugin_id!r}: manifest schema {schema} is newer than this base reads "
+ f"(MAX_PLUGIN_SCHEMA={MAX_PLUGIN_SCHEMA})"
+ )
+ requires = manifest.get("requires")
+ if not isinstance(requires, dict):
+ raise TargetResolutionError(f"plugin {plugin_id!r}: manifest \"requires\" must be an object")
+ harness_range = requires.get("harness")
+ if not isinstance(harness_range, str):
+ raise TargetResolutionError(f"plugin {plugin_id!r}: \"requires.harness\" must be a semver range string")
+ if not _range_satisfied(harness_range, _harness_version(home)):
+ raise TargetResolutionError(
+ f"plugin {plugin_id!r} requires harness {harness_range!r} but the installed harness is "
+ f"{_harness_version(home)!r}"
+ )
+ core_api = requires.get("coreApi")
+ if not isinstance(core_api, int):
+ raise TargetResolutionError(f"plugin {plugin_id!r}: \"requires.coreApi\" must be an integer")
+ if core_api != CORE_API:
+ raise TargetResolutionError(
+ f"plugin {plugin_id!r} requires coreApi {core_api} but this base provides coreApi {CORE_API}"
+ )
+ return manifest
+
+
+def path_escapes(declared_path: Any, plugin_id: str) -> bool:
+ """Mirrors img2.mjs's `artifactPathEscapes` exactly: a declared artifact path must resolve
+ under `.img2/artifacts/<plugin-id>/` -- no absolute path, no leading `~`, no `..` escape.
+ Checked here (for the runtime re-check emit_target.py performs before invocation, D6) and at
+ doctor (the harness's own static check) -- the two must never disagree."""
+ if not isinstance(declared_path, str) or not declared_path:
+ return True
+ if os.path.isabs(declared_path) or declared_path.startswith("~"):
+ return True
+ prefix = f".img2/artifacts/{plugin_id}/"
+ normalized = os.path.normpath(declared_path).replace(os.sep, "/")
+ if normalized == ".." or normalized.startswith("../"):
+ return True
+ return not normalized.startswith(prefix)
+
+
+def _validate_provides(provides: Any, *, plugin_id: str, step_id: str) -> dict[str, Any]:
+ if not isinstance(provides, dict):
+ raise TargetResolutionError(f"plugin {plugin_id!r} step {step_id!r}: \"provides\" must be an object")
+ version = provides.get("version")
+ if not isinstance(version, int) or version < 1:
+ raise TargetResolutionError(
+ f"plugin {plugin_id!r} step {step_id!r}: \"provides.version\" must be an integer >= 1"
+ )
+ if version > MAX_PROVIDES_SCHEMA:
+ raise TargetResolutionError(
+ f"plugin {plugin_id!r} step {step_id!r}: provides.version {version} is newer than this "
+ f"base reads (MAX_PROVIDES_SCHEMA={MAX_PROVIDES_SCHEMA})"
+ )
+ artifact = provides.get("artifact")
+ if not isinstance(artifact, dict):
+ raise TargetResolutionError(f"plugin {plugin_id!r} step {step_id!r}: \"provides.artifact\" must be an object")
+ kind = artifact.get("kind")
+ path = artifact.get("path")
+ if not isinstance(kind, str) or not kind:
+ raise TargetResolutionError(f"plugin {plugin_id!r} step {step_id!r}: \"provides.artifact.kind\" is required")
+ if not isinstance(path, str) or not path:
+ raise TargetResolutionError(f"plugin {plugin_id!r} step {step_id!r}: \"provides.artifact.path\" is required")
+ if path_escapes(path, plugin_id):
+ raise TargetResolutionError(
+ f"plugin {plugin_id!r} step {step_id!r}: provides.artifact.path {path!r} must resolve "
+ f"under .img2/artifacts/{plugin_id}/"
+ )
+ return provides
+
+
+def _plugin_targets(home: Path) -> list[Target]:
+ """Every target edge declared by an installed plugin, of any kind."""
+ registry = home / "plugins.json"
+ if not registry.is_file():
+ return []
+ registry_doc = _read_json(registry, what="the plugin registry")
+ rows = registry_doc.get("plugins") if isinstance(registry_doc, dict) else None
+ if not isinstance(rows, list):
+ raise TargetResolutionError(f"the plugin registry at {registry} has no \"plugins\" array")
+
+ out: list[Target] = []
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ plugin_id = row.get("id")
+ if not isinstance(plugin_id, str) or not plugin_id:
+ continue
+ plugin_dir = home / "plugins" / plugin_id
+ manifest_path = plugin_dir / "plugin.json"
+ steps_path = plugin_dir / "steps.json"
+ if not manifest_path.is_file() or not steps_path.is_file():
+ # A plugin with no steps.json declares no targets -- it may still provide capabilities
+ # this module has no reason to know about.
+ continue
+ manifest = _validate_manifest(
+ _read_json(manifest_path, what=f"plugin {plugin_id!r}'s plugin.json"),
+ home,
+ plugin_id=plugin_id,
+ where=manifest_path,
+ )
+ capability_kinds = {
+ cap.get("to")
+ for cap in manifest.get("capabilities", [])
+ if isinstance(cap, dict) and cap.get("from") == SCULPT_SPEC_KIND
+ }
+ steps = _read_json(steps_path, what=f"plugin {plugin_id!r}'s steps.json")
+ if not isinstance(steps, list):
+ continue
+ for step in steps:
+ if not isinstance(step, dict):
+ continue
+ provides = step.get("provides")
+ if not isinstance(provides, dict) or provides.get("from") != SCULPT_SPEC_KIND:
+ continue
+ step_id = step.get("id") if isinstance(step.get("id"), str) else "<unnamed step>"
+ provides = _validate_provides(provides, plugin_id=plugin_id, step_id=step_id)
+ kind = provides.get("to")
+ if not isinstance(kind, str) or not kind:
+ raise TargetResolutionError(f"plugin {plugin_id!r} step {step_id!r}: \"provides.to\" is required")
+ if kind not in capability_kinds:
+ # Doctor should already have refused this at install time (task 1.2); re-checked
+ # here because the registry can drift after doctor last ran (D5's premise).
+ raise TargetResolutionError(
+ f"plugin {plugin_id!r} step {step_id!r} provides {kind!r} with no matching "
+ f"manifest capability edge from {SCULPT_SPEC_KIND!r}"
+ )
+ deterministic = step.get("deterministic")
+ if not isinstance(deterministic, bool):
+ raise TargetResolutionError(
+ f"plugin {plugin_id!r} step {step_id!r}: \"deterministic\" must be declared as a boolean "
+ f"beside \"provides\" (D7)"
+ )
+ timeout_seconds = step.get("timeoutSeconds")
+ if timeout_seconds is not None and not (isinstance(timeout_seconds, int) and timeout_seconds > 0):
+ raise TargetResolutionError(
+ f"plugin {plugin_id!r} step {step_id!r}: \"timeoutSeconds\" must be a positive integer"
+ )
+ artifact = provides["artifact"]
+ out.append(Target(
+ kind=kind,
+ plugin_id=plugin_id,
+ plugin_dir=plugin_dir,
+ plugin_version=manifest.get("version") if isinstance(manifest.get("version"), str) else None,
+ resolved_sha=row.get("resolvedSha") if isinstance(row.get("resolvedSha"), str) else None,
+ command=step.get("command") if isinstance(step.get("command"), str) else None,
+ step_id=step_id,
+ artifact_kind=artifact["kind"],
+ artifact_path=artifact["path"],
+ deterministic=deterministic,
+ timeout_seconds=timeout_seconds,
+ ))
+ return out
+
+
+def reference_target() -> Target:
+ """`threejs-ts`: the base-owned reference target (D2, D8, M6's resolution (b)).
+
+ Declared here, as base-owned data, rather than as a real installed plugin -- the base checkout
+ ships no `plugin.json` of its own (it is registered with hosts as a skill, not a plugin). This is
+ the named exception to "resolved through the same path as a plugin-declared target": the
+ declaration's home differs, but resolution (via `resolve_target`) does not special-case it
+ beyond that -- it is filtered, matched, and disambiguated exactly like any plugin candidate.
+ """
+ return Target(
+ kind=REFERENCE_TARGET_KIND,
+ plugin_id=None,
+ plugin_dir=None,
+ plugin_version=None,
+ resolved_sha=None,
+ command=None,
+ step_id=None,
+ artifact_kind=REFERENCE_TARGET_KIND,
+ artifact_path=None,
+ deterministic=True,
+ timeout_seconds=None,
+ )
+
+
+def resolve_target(kind: str, *, plugin: str | None = None, home: Path | None = None) -> Target:
+ """Resolve an explicit `--target <kind>` [`--plugin <id>`] request.
+
+ Never call this for the no-target path: it reads `plugins.json` and every installed target
+ plugin's manifest, and `emit_target.py` must return before any of that when no target was
+ requested (D5).
+ """
+ home = home or _img2_home()
+ all_targets = _plugin_targets(home) + [reference_target()]
+ candidates = [target for target in all_targets if target.kind == kind]
+ if plugin is not None:
+ candidates = [target for target in candidates if target.plugin_id == plugin]
+ if not candidates:
+ raise TargetResolutionError(f"no installed plugin {plugin!r} provides target kind {kind!r}")
+ if not candidates:
+ raise TargetResolutionError(f"no installed plugin provides target kind {kind!r}")
+ if len(candidates) > 1:
+ claimants = sorted(target.plugin_id or f"{REFERENCE_TARGET_KIND} (base reference target)" for target in candidates)
+ raise TargetResolutionError(
+ f"target kind {kind!r} is provided by more than one installed plugin: "
+ f"{', '.join(claimants)}; disambiguate with --plugin"
+ )
+ return candidates[0]
diff --git a/forge/_shared/workflow_state.py b/forge/_shared/workflow_state.py
index 1953d6d..d84d4e9 100644
--- a/forge/_shared/workflow_state.py
+++ b/forge/_shared/workflow_state.py
@@ -63,6 +63,32 @@ 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"),
+ # 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.
+ (
+ "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 ."),
)
diff --git a/forge/stage1_intake/probe_glb.py b/forge/stage1_intake/probe_glb.py
index 5b14e11..8f7541b 100644
--- a/forge/stage1_intake/probe_glb.py
+++ b/forge/stage1_intake/probe_glb.py
@@ -15,6 +15,7 @@ import hashlib
import json
import math
import struct
+import sys
from pathlib import Path
from typing import Any
@@ -23,10 +24,17 @@ try:
except ImportError: # pragma: no cover - direct script execution
from semantic_decomposition import assess_semantic_decomposition
+# The container parse (magic/version/chunk table) is shared with the emission-target socket's tier-1
+# GLB verification (task 3.6, establish-the-emission-target-contract) -- it lives in
+# forge/_shared/glb_container.py rather than here, because this module also imports the
+# intake-domain semantic_decomposition machinery the export side has no use for and should not have
+# to pull in as a "drop-in". Same package-relative/direct-script dual import as above.
+try:
+ from .._shared.glb_container import GLB_MAGIC, parse_glb
+except ImportError: # pragma: no cover - direct script execution
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))
+ from glb_container import GLB_MAGIC, parse_glb # noqa: E402
-GLB_MAGIC = b"glTF"
-JSON_CHUNK = 0x4E4F534A
-BIN_CHUNK = 0x004E4942
MAX_FALLBACK_BOUND_SAMPLES = 1_000_000
@@ -38,66 +46,6 @@ def sha256(path: Path) -> str:
return digest.hexdigest()
-def _chunk_type_name(chunk_type: int) -> str:
- try:
- return chunk_type.to_bytes(4, "little").decode("ascii", errors="replace")
- except OverflowError:
- return hex(chunk_type)
-
-
-def parse_glb(path: Path) -> tuple[dict[str, Any], bytes, dict[str, Any]]:
- data = path.read_bytes()
- if len(data) < 12:
- raise ValueError("GLB is shorter than the 12-byte header")
- magic, version, declared_length = struct.unpack_from("<4sII", data, 0)
- if magic != GLB_MAGIC:
- raise ValueError("file does not start with the glTF binary magic")
- if version != 2:
- raise ValueError(f"unsupported GLB version {version}; expected 2")
- if declared_length != len(data):
- raise ValueError(f"header length {declared_length} does not match file size {len(data)}")
-
- cursor = 12
- json_payload: bytes | None = None
- bin_payload = b""
- chunks: list[dict[str, Any]] = []
- while cursor < len(data):
- if cursor + 8 > len(data):
- raise ValueError("truncated GLB chunk header")
- chunk_length, chunk_type = struct.unpack_from("<II", data, cursor)
- cursor += 8
- end = cursor + chunk_length
- if end > len(data):
- raise ValueError("GLB chunk extends beyond the declared file")
- payload = data[cursor:end]
- cursor = end
- chunks.append({"type": _chunk_type_name(chunk_type), "bytes": chunk_length})
- if chunk_type == JSON_CHUNK:
- if json_payload is not None:
- raise ValueError("GLB contains more than one JSON chunk")
- json_payload = payload.rstrip(b" \t\r\n\x00")
- elif chunk_type == BIN_CHUNK:
- if bin_payload:
- raise ValueError("GLB contains more than one BIN chunk")
- bin_payload = payload
-
- if json_payload is None:
- raise ValueError("GLB has no JSON chunk")
- try:
- document = json.loads(json_payload.decode("utf-8"))
- except (UnicodeDecodeError, json.JSONDecodeError) as exc:
- raise ValueError(f"GLB JSON chunk is invalid: {exc}") from exc
- if not isinstance(document, dict):
- raise ValueError("GLB JSON root must be an object")
- return document, bin_payload, {
- "version": version,
- "declaredLength": declared_length,
- "jsonChunkBytes": len(json_payload),
- "binChunkBytes": len(bin_payload),
- "chunks": chunks,
- }
-
-
def _buffer_view_bytes(document: dict[str, Any], bin_payload: bytes, view_index: int) -> bytes:
views = document.get("bufferViews", [])
if not isinstance(views, list) or not 0 <= view_index < len(views):
diff --git a/forge/stage3_build/emit_target.py b/forge/stage3_build/emit_target.py
new file mode 100644
index 0000000..36f5297
--- /dev/null
+++ b/forge/stage3_build/emit_target.py
@@ -0,0 +1,568 @@
+#!/usr/bin/env python3
+"""Resolve and invoke an emission target (design D4), or no-op with none selected.
+
+This is a NEW CLI. `generate_threejs_factory.py` is not modified by this module and carries no
+target-related edits at all -- the terminal export step is layered on top of it, never inside it.
+
+With no `--target`, this is a successful no-op: it writes nothing, changes no byte, and returns
+before `forge/_shared/targets.py` reads anything (D5) -- a malformed `plugins.json` therefore cannot
+break the default path, matching PR #106's finding about `registered_domains()` running at
+argparse-construction time.
+
+With `--target <kind>`, the socket: checks the terminal (`action-ready`) precondition (D3) -> resolves
+the target (D5, refusing ambiguity or a missing kind, never falling back) -> re-checks the artifact
+path statically (D6) -> invokes it as a bounded subprocess with an injected `IMG2_HOME` (D6, round-3
+H1) -> verifies the artifact to the honest limit (D10) -> verifies determinism if declared (D7) ->
+records provenance (D5's manifest data plus the spec content hash).
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import shlex
+import subprocess
+import sys
+import tempfile
+import time
+from pathlib import Path
+from typing import Any
+
+_FORGE_ROOT = Path(__file__).resolve().parent.parent
+sys.path[:0] = [str(_FORGE_ROOT), str(_FORGE_ROOT / "_shared")]
+
+from glb_container import parse_glb # noqa: E402
+from targets import ( # noqa: E402
+ Target,
+ TargetResolutionError,
+ _harness_version,
+ path_escapes,
+ resolve_target,
+)
+from workflow_state import WorkflowStateError, load_state, mark_steps, save_state, status_payload # noqa: E402
+
+DEFAULT_TIMEOUT_SECONDS = 300
+MAX_TIMEOUT_SECONDS = 1800
+MAX_STDOUT_BYTES = 1024 * 1024
+MAX_STDERR_BYTES = 64 * 1024
+MAX_ARTIFACT_BYTES = 512 * 1024 * 1024
+ENV_ALLOWLIST = ("PATH", "HOME", "LANG", "LC_ALL")
+ARTIFACT_OF_RECORD = "src/createObjectModel.ts"
+DETERMINISM_CACHE_NAME = ".determinism-verified.json"
+
+
+class EmitTargetError(RuntimeError):
+ """A target run was refused or failed. Callers print `str(exc)` and exit non-zero -- never
+ fall back to the no-target default (D6): fallback only ever applies to "nothing selected".
+
+ `classification` distinguishes what kind of failure this is -- see `_classify_reference_
+ failure` for the one case (the reference target) where the socket bothers to tell them apart
+ instead of reporting a flat "error" for everything."""
+
+ def __init__(self, message: str, *, classification: str = "error") -> None:
+ super().__init__(message)
+ self.classification = classification
+
+
+def _img2_home() -> Path:
+ return Path(os.environ.get("IMG2_HOME") or Path.home() / ".img2")
+
+
+def _sha256_file(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as handle:
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+# ---------------------------------------------------------------- D3: terminal-only precondition
+
+def assert_action_ready(workspace: Path) -> None:
+ """Refuse unless workspace state records `action-ready`, naming the unmet step (D3).
+
+ Reads state via `status_payload` only, per design's stated limit: this does not re-verify
+ `action-ready`'s recorded evidence content (free text a human or agent supplied) -- it trusts
+ the checklist's own `done` marking, the same way `mark_steps`'s out-of-order guard does.
+ """
+ state_path = workspace / ".img2threejs" / "state.json"
+ if not state_path.is_file():
+ raise EmitTargetError(
+ f"target run refused: no workflow state at {state_path}; this workspace has not "
+ f"reached action-ready"
+ )
+ try:
+ state = load_state(state_path)
+ except WorkflowStateError as exc:
+ raise EmitTargetError(f"target run refused: {exc}") from exc
+ by_id = {entry["id"]: entry for entry in state["checklist"]}
+ action_ready = by_id.get("action-ready")
+ if action_ready is None or action_ready.get("status") != "done":
+ payload = status_payload(state)
+ unmet = payload["currentStep"]
+ raise EmitTargetError(
+ f"target run refused: action-ready is not recorded yet (next required step: {unmet!r})"
+ )
+
+
+def record_target_selection(workspace: Path, target: Target, *, artifact_path: Path) -> None:
+ """After a successful target run, record WHICH plugin ran (task 4.2's own precondition: gate
+ execution needs to know whether a plugin's step actually ran in THIS workspace, and nothing
+ else in workflow state carries that attribution for a target step). Additive only -- a new
+ top-level `targetSelection` key, never `reviewHistory`/`buildPasses`/any pass-state field (D3).
+
+ Marks the `emission-target` checklist entry `done` when it exists. It will not exist in a
+ workspace created before this change (round-3 H6: `new_state()` materialises `FINAL_STEPS`
+ once, at init) -- that is not an error, the workspace simply has no such step to mark, and
+ `targetSelection` is still recorded so gate participation can still be determined for it.
+ """
+ state_path = workspace / ".img2threejs" / "state.json"
+ state = load_state(state_path)
+ by_id = {entry["id"]: entry for entry in state["checklist"]}
+ if "emission-target" in by_id and by_id["emission-target"]["status"] != "done":
+ mark_steps(state, ["emission-target"], status="done", evidence=[str(artifact_path)])
+ state["targetSelection"] = {"pluginId": target.plugin_id, "kind": target.kind}
+ save_state(state_path, state)
+
+
+# ---------------------------------------------------------------- D6: the bounded runner
+
+def _bounded_env(declared: list[str]) -> dict[str, str]:
+ """Construct the child environment. `IMG2_HOME` is INJECTED from the base's own resolution,
+ never merely allowed to pass through (round-3 H1: an allowlist forwards a variable only when
+ the parent already has it, and the base itself commonly runs with IMG2_HOME unset)."""
+ env = {name: os.environ[name] for name in ENV_ALLOWLIST if name in os.environ}
+ for name in declared:
+ if name in os.environ:
+ env[name] = os.environ[name]
+ env["IMG2_HOME"] = str(_img2_home())
+ return env
+
+
+def _resolve_timeout(target: Target) -> int:
+ timeout = target.timeout_seconds if target.timeout_seconds is not None else DEFAULT_TIMEOUT_SECONDS
+ if timeout > MAX_TIMEOUT_SECONDS:
+ raise EmitTargetError(
+ f"target {target.kind!r}: declared timeoutSeconds {timeout} exceeds the base-owned "
+ f"ceiling of {MAX_TIMEOUT_SECONDS}s"
+ )
+ return timeout
+
+
+def run_bounded(
+ argv: list[str],
+ *,
+ cwd: Path,
+ timeout: int,
+ declared_env: list[str],
+ target_kind: str,
+) -> subprocess.CompletedProcess:
+ env = _bounded_env(declared_env)
+ try:
+ proc = subprocess.run(
+ argv,
+ cwd=cwd,
+ env=env,
+ timeout=timeout,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise EmitTargetError(f"target {target_kind!r} timed out after {timeout}s") from exc
+ except (FileNotFoundError, PermissionError) as exc:
+ raise EmitTargetError(f"target {target_kind!r}: could not spawn its command: {exc}") from exc
+ # subprocess.CompletedProcess is an ordinary mutable object (not a namedtuple); capping its
+ # captured output in place is the bound (D6: 1 MiB stdout / 64 KiB stderr).
+ if len(proc.stdout) > MAX_STDOUT_BYTES:
+ proc.stdout = proc.stdout[:MAX_STDOUT_BYTES]
+ if len(proc.stderr) > MAX_STDERR_BYTES:
+ proc.stderr = proc.stderr[:MAX_STDERR_BYTES]
+ return proc
+
+
+def _substitute(command: str, *, workspace: Path, spec: Path, plugin_dir: Path) -> list[str]:
+ """{plugin_dir}/{workspace}/{spec} replaced by value -- steps.json's closed placeholder set
+ (img2.mjs:670). {image} is not substituted: no installed target step should need it (a target's
+ `from` is always sculpt-spec, never image), and leaving it untouched matches the harness's own
+ "replace by value" discipline rather than inventing a new rule for this file."""
+ return [
+ token.replace("{plugin_dir}", str(plugin_dir)).replace("{workspace}", str(workspace)).replace("{spec}", str(spec))
+ for token in shlex.split(command)
+ ]
+
+
+# ---------------------------------------------------------------- D10: tier-1 verification
+
+def _verify_glb(path: Path) -> None:
+ try:
+ parse_glb(path)
+ except ValueError as exc:
+ raise EmitTargetError(f"GLB container check failed for {path}: {exc}") from exc
+
+
+_PROBERS = {"glb": _verify_glb}
+
+
+def verify_artifact(path: Path, declared_kind: str) -> dict[str, Any]:
+ """Verify to the honest limit (D10): container check where a prober exists, existence/size/
+ location always. Raises EmitTargetError naming the declared/actual kinds on a wrong-kind
+ artifact; returns the recorded verification level otherwise."""
+ if not path.is_file():
+ raise EmitTargetError(f"target produced no artifact at {path}")
+ size = path.stat().st_size
+ if size > MAX_ARTIFACT_BYTES:
+ raise EmitTargetError(
+ f"target {declared_kind!r} artifact at {path} is {size} bytes, exceeding the "
+ f"{MAX_ARTIFACT_BYTES}-byte bound"
+ )
+ prober = _PROBERS.get(declared_kind)
+ if prober is None:
+ return {
+ "kind": declared_kind,
+ "level": "existence+size+location",
+ "note": "no container prober for this kind; no further base quality warranty applies",
+ }
+ try:
+ prober(path)
+ except EmitTargetError as exc:
+ raise EmitTargetError(
+ f"target declared kind {declared_kind!r} but its artifact failed that kind's container "
+ f"check: {exc}"
+ ) from exc
+ return {"kind": declared_kind, "level": "container+existence+size+location"}
+
+
+# ---------------------------------------------------------------- D7: determinism
+
+def _determinism_cache_path(workspace: Path, plugin_id: str) -> Path:
+ return workspace / ".img2" / "artifacts" / plugin_id / DETERMINISM_CACHE_NAME
+
+
+def _determinism_cache_key(resolved_sha: str | None, spec_hash: str) -> str:
+ return f"{resolved_sha or '<none>'}:{spec_hash}"
+
+
+def verify_determinism(
+ target: Target,
+ *,
+ argv: list[str],
+ cwd: Path,
+ timeout: int,
+ artifact_path: Path,
+ spec_hash: str,
+) -> bool:
+ """Verify a declared-deterministic target by double-invocation, cached once per
+ (resolvedSha, spec-content-hash) so repeat builds cost zero (D7). Returns True if this run
+ performed (and passed) verification, False if it was served from the cache. Raises
+ EmitTargetError naming the target on a mismatch. There is no skip flag anywhere."""
+ cache_path = _determinism_cache_path(cwd, target.plugin_id or "threejs-ts")
+ key = _determinism_cache_key(target.resolved_sha, spec_hash)
+ cache: dict[str, bool] = {}
+ if cache_path.is_file():
+ try:
+ cache = json.loads(cache_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ cache = {}
+ if cache.get(key):
+ return False
+
+ first_bytes = artifact_path.read_bytes()
+ proc = run_bounded(argv, cwd=cwd, timeout=timeout, declared_env=[], target_kind=target.kind)
+ if proc.returncode != 0:
+ raise EmitTargetError(
+ f"target {target.kind!r}: determinism re-invocation exited {proc.returncode}: "
+ f"{proc.stderr.decode('utf-8', errors='replace')}"
+ )
+ second_bytes = artifact_path.read_bytes()
+ if first_bytes != second_bytes:
+ raise EmitTargetError(
+ f"target {target.kind!r} declared itself deterministic but two invocations against the "
+ f"same (resolvedSha, spec) produced different bytes"
+ )
+ cache[key] = True
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
+ cache_path.write_text(json.dumps(cache), encoding="utf-8")
+ return True
+
+
+# ---------------------------------------------------------------- provenance
+
+def build_provenance(
+ target: Target,
+ *,
+ spec_hash: str,
+ harness_version: str,
+ verification: dict[str, Any],
+ determinism_verified: bool | None,
+) -> dict[str, Any]:
+ return {
+ "kind": "img2.target-artifact",
+ "version": 1,
+ "target": target.kind,
+ "plugin": {
+ "id": target.plugin_id,
+ "version": target.plugin_version,
+ "resolvedSha": target.resolved_sha,
+ },
+ "specContentHash": spec_hash,
+ "harnessVersion": harness_version,
+ "deterministic": target.deterministic,
+ "determinismVerified": determinism_verified,
+ "verification": verification,
+ # Never reported under a gated TypeScript build's completion vocabulary (D10's own scenario):
+ # this section exists precisely so nothing downstream can conflate the two.
+ "baseQualityWarranty": "container/existence/size/location only; no visual warranty",
+ }
+
+
+def _write_provenance(artifact_path: Path, provenance: dict[str, Any]) -> None:
+ provenance_path = artifact_path.with_suffix(artifact_path.suffix + ".provenance.json")
+ handle, tmp_name = tempfile.mkstemp(dir=provenance_path.parent, prefix=".provenance.", suffix=".tmp")
+ try:
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
+ json.dump(provenance, stream, indent=2)
+ stream.write("\n")
+ except BaseException:
+ os.unlink(tmp_name)
+ raise
+ os.replace(tmp_name, provenance_path)
+
+
+# ---------------------------------------------------------------- no-target path (D2)
+
+def run_no_target() -> int:
+ """The default: no target selected. Writes nothing, changes no byte, succeeds -- and returns
+ before this function is even reached, since main() checks `args.target is None` before calling
+ anything in this module that touches the registry (D5)."""
+ print(f"no target selected; the artifact of record is {ARTIFACT_OF_RECORD}")
+ return 0
+
+
+# ---------------------------------------------------------------- target invocation
+
+def run_target(
+ kind: str,
+ *,
+ plugin: str | None,
+ spec_path: Path,
+ workspace: Path,
+ harness_version_reader=None,
+) -> int:
+ assert_action_ready(workspace)
+ try:
+ target = resolve_target(kind, plugin=plugin)
+ except TargetResolutionError as exc:
+ raise EmitTargetError(str(exc)) from exc
+
+ if target.plugin_id is None:
+ return _run_reference_target(target, spec_path=spec_path, workspace=workspace)
+ return _run_plugin_target(target, spec_path=spec_path, workspace=workspace)
+
+
+def _run_plugin_target(target: Target, *, spec_path: Path, workspace: Path) -> int:
+ assert target.plugin_dir is not None and target.artifact_path is not None and target.command is not None
+ # Runtime re-check (D6): the same static rule doctor enforces, re-checked here before the
+ # subprocess starts, since the registry can drift after doctor last ran.
+ if path_escapes(target.artifact_path, target.plugin_id):
+ raise EmitTargetError(
+ f"target {target.kind!r}: declared artifact path {target.artifact_path!r} does not "
+ f"resolve under .img2/artifacts/{target.plugin_id}/"
+ )
+ # target.artifact_path is already workspace-relative and already carries the full
+ # ".img2/artifacts/<plugin-id>/" prefix (that is exactly what path_escapes just re-checked) --
+ # it is not a bare filename to be joined under that prefix a second time.
+ artifact_path = (workspace / target.artifact_path).resolve()
+ argv = _substitute(target.command, workspace=workspace, spec=spec_path, plugin_dir=target.plugin_dir)
+ timeout = _resolve_timeout(target)
+ spec_hash = _sha256_file(spec_path)
+
+ # Delete-on-failure wraps the whole invocation, not just a non-zero exit: the plugin writes to
+ # its own declared path directly (there is no base-owned temp location to rename from for a
+ # third-party target -- only the reference target, which the base invokes with its own --out,
+ # gets true temp-write+rename below), so ANY failure here -- crash, non-zero exit, timeout,
+ # wrong-kind, oversized -- must not leave a right-named wrong-length file behind. A timeout
+ # raises out of run_bounded() before a CompletedProcess even exists, so the cleanup cannot live
+ # behind a "check proc.returncode" gate; it has to wrap the call itself.
+ try:
+ proc = run_bounded(argv, cwd=workspace, timeout=timeout, declared_env=[], target_kind=target.kind)
+ if proc.returncode != 0:
+ raise EmitTargetError(
+ f"target {target.kind!r} (plugin {target.plugin_id!r}) exited {proc.returncode}: "
+ f"{proc.stderr.decode('utf-8', errors='replace')}"
+ )
+ verification = verify_artifact(artifact_path, target.artifact_kind)
+ determinism_verified = None
+ if target.deterministic:
+ determinism_verified = verify_determinism(
+ target,
+ argv=argv,
+ cwd=workspace,
+ timeout=timeout,
+ artifact_path=artifact_path,
+ spec_hash=spec_hash,
+ )
+ except EmitTargetError:
+ artifact_path.unlink(missing_ok=True)
+ raise
+
+ provenance = build_provenance(
+ target,
+ spec_hash=spec_hash,
+ harness_version=_harness_version_for_provenance(),
+ verification=verification,
+ determinism_verified=determinism_verified,
+ )
+ _write_provenance(artifact_path, provenance)
+ record_target_selection(workspace, target, artifact_path=artifact_path)
+ print(json.dumps({"artifact": str(artifact_path), "provenance": provenance}, indent=2))
+ return 0
+
+
+def _classify_reference_failure(returncode: int, stderr: bytes) -> EmitTargetError:
+ """Reconciliation (task 3.10's envelope-parity gap, resolved by the lead): `generate_threejs_
+ factory.py main()` returns exit 2 for both a strict-quality BLOCKED report (a structured JSON
+ envelope printed to stderr by `emit_blocked`) and a plain `argparse.error()` usage mistake
+ (free-text prose, also on stderr, also exit 2) -- one exit code, two unrelated shapes.
+
+ The socket classifies by envelope, not by exit code, and this makes ZERO changes to
+ `generate_threejs_factory.py` -- the emitter's exit-code overload is its own pre-existing
+ surface, left for whoever next revises `main()`; only the socket's own parsing changes here. A
+ stderr that parses as JSON with `status == "BLOCKED"` is a quality block, surfaced with its own
+ `cause`/`nextAction` verbatim -- that prose is actionable and must not be flattened into an
+ opaque string. Anything else -- prose, JSON that isn't a BLOCKED envelope, or JSON that only
+ half-parses -- is classified `error`, never treated as a pass: the same "a malformed envelope
+ is an error, not a pass" discipline `gate_runner.parse_verdict` applies to a gate's verdict.
+ """
+ text = stderr.decode("utf-8", errors="replace")
+ try:
+ doc = json.loads(text)
+ except json.JSONDecodeError:
+ doc = None
+ if isinstance(doc, dict) and doc.get("status") == "BLOCKED":
+ cause = doc.get("cause") if isinstance(doc.get("cause"), list) else []
+ message = f"reference target refused: strict-quality blocked ({len(cause)} failure(s)): " + "; ".join(
+ str(item) for item in cause
+ )
+ next_action = doc.get("nextAction")
+ if next_action:
+ message += f" -- {next_action}"
+ return EmitTargetError(message, classification="quality-block")
+ return EmitTargetError(f"reference target exited {returncode}: {text}", classification="error")
+
+
+def _run_reference_target(target: Target, *, spec_path: Path, workspace: Path) -> int:
+ """`--target threejs-ts`: the base fully controls invocation, so this is the one case where
+ D6's temp-write+rename is literally implementable rather than a best-effort delete-on-failure
+ (see `_run_plugin_target`'s note). Runs `generate_threejs_factory.py` as a subprocess -- proving
+ the byte-equality/envelope/bounds/kind parity D8 requires -- against the last completed build
+ pass, since action-ready implies the pass loop is done and its TypeScript already exists
+ in-process (D2)."""
+ from orchestrate_passes import completed_passes, pass_order
+
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
+ ids = pass_order(spec)
+ completed = completed_passes(spec, ids)
+ if not completed:
+ raise EmitTargetError(
+ "target 'threejs-ts' requires at least one completed build pass; none recorded in the spec"
+ )
+ pass_id = completed[-1]
+
+ plugin_id = "threejs-ts"
+ artifact_rel = "model.ts"
+ artifact_path = (workspace / ".img2" / "artifacts" / plugin_id / artifact_rel).resolve()
+ timeout = _resolve_timeout(target)
+ spec_hash = _sha256_file(spec_path)
+ emitter = str(_FORGE_ROOT / "stage3_build" / "generate_threejs_factory.py")
+
+ def invoke(out_path: Path) -> subprocess.CompletedProcess:
+ argv = [sys.executable, emitter, str(spec_path), "--out", str(out_path), "--pass-id", pass_id]
+ return run_bounded(argv, cwd=workspace, timeout=timeout, declared_env=[], target_kind=target.kind)
+
+ artifact_path.parent.mkdir(parents=True, exist_ok=True)
+ handle, tmp_name = tempfile.mkstemp(dir=artifact_path.parent, prefix=".model.", suffix=".ts.tmp")
+ os.close(handle)
+ tmp_path = Path(tmp_name)
+ try:
+ proc = invoke(tmp_path)
+ if proc.returncode != 0:
+ raise _classify_reference_failure(proc.returncode, proc.stderr)
+ determinism_verified = None
+ if target.deterministic:
+ cache_path = _determinism_cache_path(workspace, plugin_id)
+ key = _determinism_cache_key(None, spec_hash)
+ cache: dict[str, bool] = {}
+ if cache_path.is_file():
+ try:
+ cache = json.loads(cache_path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ cache = {}
+ if not cache.get(key):
+ handle2, tmp2_name = tempfile.mkstemp(dir=artifact_path.parent, prefix=".model2.", suffix=".ts.tmp")
+ os.close(handle2)
+ tmp2_path = Path(tmp2_name)
+ try:
+ proc2 = invoke(tmp2_path)
+ if proc2.returncode != 0 or tmp2_path.read_bytes() != tmp_path.read_bytes():
+ raise EmitTargetError(
+ "reference target declared itself deterministic but two invocations "
+ "against the same (spec, pass_id) produced different bytes"
+ )
+ finally:
+ tmp2_path.unlink(missing_ok=True)
+ cache[key] = True
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
+ cache_path.write_text(json.dumps(cache), encoding="utf-8")
+ determinism_verified = True
+ else:
+ determinism_verified = False
+ verification = verify_artifact(tmp_path, target.artifact_kind)
+ os.replace(tmp_path, artifact_path)
+ except BaseException:
+ tmp_path.unlink(missing_ok=True)
+ raise
+
+ provenance = build_provenance(
+ target,
+ spec_hash=spec_hash,
+ harness_version=_harness_version_for_provenance(),
+ verification=verification,
+ determinism_verified=determinism_verified,
+ )
+ _write_provenance(artifact_path, provenance)
+ record_target_selection(workspace, target, artifact_path=artifact_path)
+ print(json.dumps({"artifact": str(artifact_path), "provenance": provenance}, indent=2))
+ return 0
+
+
+def _harness_version_for_provenance() -> str:
+ return _harness_version(_img2_home())
+
+
+# ---------------------------------------------------------------- CLI
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--spec", type=Path, required=True)
+ parser.add_argument("--target", default=None, help="target kind, e.g. threejs-ts; omit for the no-op default")
+ parser.add_argument("--plugin", default=None, help="disambiguate when more than one plugin provides --target")
+ parser.add_argument("--workspace", type=Path, default=Path.cwd())
+ args = parser.parse_args(argv)
+
+ if args.target is None:
+ # Returns before any registry read (D5): a malformed plugins.json must not break this path.
+ return run_no_target()
+
+ workspace = args.workspace.expanduser().resolve()
+ spec_path = args.spec.expanduser().resolve()
+ try:
+ return run_target(args.target, plugin=args.plugin, spec_path=spec_path, workspace=workspace)
+ except EmitTargetError as exc:
+ print(f"emit-target [{exc.classification}]: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/tests/fixtures/reference_target_conformance_spec.json b/forge/tests/fixtures/reference_target_conformance_spec.json
new file mode 100644
index 0000000..c7c710a
--- /dev/null
+++ b/forge/tests/fixtures/reference_target_conformance_spec.json
@@ -0,0 +1,3247 @@
+{
+ "targetName": "TradeIt Hard Case",
+ "targetId": "tradeit-hard-case",
+ "schemaVersion": "2.1",
+ "terminologyProfile": {
+ "domain": "real-time procedural Three.js asset",
+ "geometryTerms": [
+ "silhouette",
+ "topology",
+ "primitive",
+ "bevel",
+ "chamfer",
+ "taper",
+ "bend",
+ "boolean cut",
+ "edge loop",
+ "surface normal",
+ "displacement"
+ ],
+ "materialTerms": [
+ "albedo",
+ "baseColor",
+ "roughness",
+ "metalness",
+ "normal map",
+ "bump map",
+ "ambient occlusion",
+ "cavity dirt",
+ "edge wear",
+ "clearcoat"
+ ],
+ "lightingTerms": [
+ "key light",
+ "fill light",
+ "rim light",
+ "HDRI/environment reflection",
+ "contact shadow"
+ ],
+ "descriptionRule": "Use measurable 3D graphics terms. Avoid vague words unless they are paired with concrete geometry/material/shader parameters."
+ },
+ "sourceImage": ".img2threejs/refs/case-closed.png",
+ "referenceCamera": {
+ "solved": false,
+ "fovDegrees": 35.0,
+ "aspect": 1.0,
+ "orientation": {
+ "yaw": 28.0,
+ "pitch": 12.0,
+ "roll": 0.0
+ },
+ "positionHint": [
+ 1.1,
+ 0.55,
+ 1.8
+ ],
+ "note": "3/4 front-left studio framing, not solved via solve_camera_pose.py (flat print decal route does not require pixel-exact projection); used only as a review-render hint."
+ },
+ "suitability": "pass",
+ "scores": {
+ "object_isolation": 3,
+ "silhouette_readability": 3,
+ "depth_inference": 2,
+ "primitive_decomposition": 3,
+ "material_procedurality": 3,
+ "occlusion_risk": 2,
+ "interaction_fit": 3
+ },
+ "preSpecAssessment": {
+ "objectClass": {
+ "primaryType": "rotomolded hard equipment case",
+ "primaryDomain": "object",
+ "formLanguage": [
+ "geometric",
+ "tapered-box"
+ ],
+ "structureKind": [
+ "rigid-shell",
+ "hinged-lid",
+ "hardware-mounted"
+ ],
+ "motionPotential": [
+ "lid-hinge-rotation",
+ "latch-cam-rotation",
+ "padlock-shackle-idle-sway"
+ ],
+ "materialFamilies": [
+ "matte-composite-shell",
+ "satin-metal-hardware",
+ "plated-brass-metal",
+ "flat-printed-decal"
+ ],
+ "notes": "Pelican/SKB-style protective case: tapered rotomolded shell, 2 over-center draw latches, recessed side handle, brass padlock (closed-state accessory), printed logo/stripe decal. Confirmed by a second ghost-render reference showing the open/hinged state."
+ },
+ "complexity": {
+ "tier": "moderate",
+ "scores": {
+ "silhouetteComplexity": 1,
+ "componentCount": 2,
+ "hierarchyDepth": 2,
+ "repetitionDensity": 1,
+ "materialLayerCount": 2,
+ "localDetailDensity": 2,
+ "occlusionRisk": 2,
+ "actionReadinessNeed": 2
+ },
+ "estimatedCounts": {
+ "macroComponents": 6,
+ "mesoComponents": 6,
+ "microFeatureGroups": 3,
+ "materialLayers": 4,
+ "repetitionSystems": 1
+ },
+ "reasoning": [
+ "Macro parts: body, lid, latchLeft, latchRight, sideHandle, padlock \u2014 six independent volumes.",
+ "Meso: 3-rib lid group, decal graphic panel, latch cam+bail per latch, hasp loop, handle recess pocket.",
+ "Micro/repetition: 2x mirrored latch assembly, ~4x lid-edge fastener heads treated as one instanced group.",
+ "Materials: matte shell, satin-metal hardware, plated-brass padlock body + satin steel shackle, flat decal on the shell finish \u2014 4 distinct PBR treatments, no patterned/photoreal skin.",
+ "occlusionRisk=2: back face, left face, bottom, and hinge-pin geometry are all hidden in both references.",
+ "actionReadinessNeed=2: user explicitly requested lid/latch pivots plus an idle userData.tick animation."
+ ]
+ },
+ "specDepthDecision": {
+ "requiredDepth": "moderate",
+ "minimumComponentLevels": [
+ "macro",
+ "meso",
+ "micro"
+ ],
+ "needsRepetitionSystems": true,
+ "needsMaterialLocalOverrides": true,
+ "needsMultipleReviewViews": true,
+ "needsActionReadyHierarchy": true,
+ "rationale": "Six macro parts with meso sub-assemblies (latch cam+bail, lid ribs, decal panel) and one repetition system (mirrored latches / fastener row) push this past a shallow moderate spec; local overrides are needed for the decal, hardware, and padlock finishes layered on the shared shell material."
+ },
+ "unknownsToResolveBeforeImplementation": [],
+ "detailInventory": {
+ "scanMethod": "grid-3x3",
+ "targetMinDetails": 6,
+ "note": "Populated from build_detail_inventory.py grid-3x3 crops of case-closed.png + full-frame case-open.png for mechanism confirmation.",
+ "details": [
+ {
+ "id": "tradeit-logo-icon",
+ "description": "Circular blue double-arrow/handshake icon, front-left of the decal panel.",
+ "priority": "critical",
+ "componentRef": "decalGraphic",
+ "materialRef": "decalPrint",
+ "evidenceRef": "zone-r1c0.png, zone-r1c1.png",
+ "confidence": 0.85,
+ "realization": "unreported",
+ "kind": "decal",
+ "mapsTo": {
+ "ref": "shellMatte/tradeitLogoIcon"
+ }
+ },
+ {
+ "id": "tradeit-wordmark",
+ "description": "White 'TRADEIT' wordmark below the icon, flat printed text.",
+ "priority": "critical",
+ "componentRef": "decalGraphic",
+ "materialRef": "decalPrint",
+ "evidenceRef": "zone-r1c0.png, zone-r2c1.png",
+ "confidence": 0.85,
+ "realization": "unreported",
+ "kind": "decal",
+ "mapsTo": {
+ "ref": "shellMatte/tradeitWordmark"
+ }
+ },
+ {
+ "id": "diagonal-blue-chevron",
+ "description": "Wide diagonal blue wedge/chevron band across the lower-right of the front face, widening toward the bottom-left.",
+ "priority": "critical",
+ "componentRef": "decalGraphic",
+ "materialRef": "decalPrint",
+ "evidenceRef": "zone-r1c2.png",
+ "confidence": 0.8,
+ "realization": "unreported",
+ "kind": "decal",
+ "mapsTo": {
+ "ref": "shellMatte/diagonalChevron"
+ }
+ },
+ {
+ "id": "draw-latch-pair",
+ "description": "Two black over-center cam latches with metal wire bail hardware, mounted flush at ~30%/70% width straddling the lid/body seam.",
+ "priority": "critical",
+ "componentRef": "latchLeft,latchRight",
+ "materialRef": "shellMatte,hardwareSatin",
+ "evidenceRef": "zone-r1c1.png",
+ "confidence": 0.75,
+ "realization": "unreported",
+ "kind": "fastener",
+ "mapsTo": {
+ "ref": "latch"
+ }
+ },
+ {
+ "id": "hasp-eyeloop",
+ "description": "Small bent-wire/eyebolt loop mounted on the shell right of the latches, the padlock shackle passes through it.",
+ "priority": "important",
+ "componentRef": "haspLoop",
+ "materialRef": "hardwareSatin",
+ "evidenceRef": "zone-r1c1.png",
+ "confidence": 0.6,
+ "realization": "unreported",
+ "kind": "fastener",
+ "mapsTo": {
+ "ref": "haspLoop"
+ }
+ },
+ {
+ "id": "padlock-assembly",
+ "description": "Brass-plated padlock body + steel shackle hanging from the hasp loop; closed-state-only accessory (absent in case-open).",
+ "priority": "important",
+ "componentRef": "padlock",
+ "materialRef": "brassPlated,steelSatin",
+ "evidenceRef": "zone-r1c1.png",
+ "confidence": 0.55,
+ "realization": "unreported",
+ "kind": "fastener",
+ "mapsTo": {
+ "ref": "padlock"
+ }
+ },
+ {
+ "id": "lid-top-ribs",
+ "description": "Three parallel raised rounded ribs spanning the full depth of the lid top face, evenly spaced.",
+ "priority": "important",
+ "componentRef": "lid",
+ "materialRef": "shellMatte",
+ "evidenceRef": "zone-r0c1.png, zone-r0c2.png",
+ "confidence": 0.85,
+ "realization": "unreported",
+ "kind": "ridge",
+ "mapsTo": {
+ "ref": "lidRidge"
+ }
+ },
+ {
+ "id": "side-handle-recess",
+ "description": "Recessed rectangular pocket on the right face with an inset grip bar; far side/full cross-section not visible.",
+ "priority": "minor",
+ "componentRef": "sideHandle",
+ "materialRef": "shellMatte",
+ "evidenceRef": "zone-r1c2.png",
+ "confidence": 0.5,
+ "realization": "unreported",
+ "kind": "groove",
+ "mapsTo": {
+ "ref": "sideHandle/side-handle-recess"
+ }
+ },
+ {
+ "id": "lid-edge-fastener-row",
+ "description": "Row of ~4 small round rivet/screw heads along the lid's front-bottom lip, below the ribs.",
+ "priority": "minor",
+ "componentRef": "lid",
+ "materialRef": "hardwareSatin",
+ "evidenceRef": "zone-r0c2.png",
+ "confidence": 0.55,
+ "realization": "unreported",
+ "kind": "fastener",
+ "mapsTo": {
+ "ref": "lidFastener"
+ }
+ },
+ {
+ "id": "rounded-bevel-edges",
+ "description": "Continuous rounded fillet on all 12 body/lid edges; molded into the shell, not applied bumpers.",
+ "priority": "important",
+ "componentRef": "body,lid",
+ "materialRef": "shellMatte",
+ "evidenceRef": "case-closed.png (full frame)",
+ "confidence": 0.8,
+ "realization": "unreported",
+ "kind": "bevel",
+ "mapsTo": {
+ "ref": "root/rounded-bevel-edges"
+ }
+ },
+ {
+ "id": "body-taper",
+ "description": "Body tapers inward from lid seam to base (rotomold draft angle), visible in the front-face silhouette.",
+ "priority": "important",
+ "componentRef": "body",
+ "materialRef": "shellMatte",
+ "evidenceRef": "case-closed.png (full frame)",
+ "confidence": 0.7,
+ "realization": "unreported",
+ "kind": "contour",
+ "mapsTo": {
+ "ref": "root/body-taper"
+ }
+ }
+ ]
+ },
+ "anatomy": {
+ "applies": false,
+ "styleHeads": 0.0,
+ "proportions": {
+ "headUnit": 0.0,
+ "torso": 0.0,
+ "legs": 0.0,
+ "shoulderWidth": 0.0,
+ "hipWidth": 0.0
+ },
+ "pose": {
+ "type": "unassessed",
+ "jointAngles": {}
+ },
+ "faceLandmarks": {
+ "eyeLine": 0.0,
+ "eyeSpacing": 0.0,
+ "noseBase": 0.0,
+ "mouthLine": 0.0,
+ "hairline": 0.0
+ },
+ "features": [],
+ "confidence": 0.0,
+ "note": "Only meaningful when objectClass.primaryDomain is character or hybrid. Set applies=true and fill from forge/stage1_intake/extract_landmarks.py. See grimoire/character/reconstruction.md and grimoire/character/likeness_maximization.md."
+ },
+ "sourceImage": ".img2threejs/refs/case-closed.png"
+ },
+ "qualityContract": {
+ "qualityBar": "moderate",
+ "definitionOfDone": [
+ "The rendered model matches the reference silhouette, primary proportions, visible component hierarchy, material response, and most recognizable local features for the selected fidelity tier."
+ ],
+ "minimumSpecDepth": {
+ "macroComponents": 2,
+ "mesoComponents": 3,
+ "microFeatureGroups": 2,
+ "materialLayers": 2,
+ "repetitionSystems": 0,
+ "reviewViewpoints": 3
+ },
+ "featureGroups": [
+ {
+ "id": "overall-silhouette",
+ "name": "Overall silhouette and proportions",
+ "required": true,
+ "qualityCriteria": [
+ "Bounding shape, dominant curves, negative spaces, and scale relationships are explicitly described."
+ ],
+ "evidenceRefs": [
+ "full-object"
+ ],
+ "failureModes": [
+ "model reads as a generic placeholder instead of the reference object",
+ "major proportions are guessed without evidence"
+ ]
+ },
+ {
+ "id": "primary-structure",
+ "name": "Primary structure and hierarchy",
+ "required": true,
+ "qualityCriteria": [
+ "Major parts, joints, seams, contact points, and parent-child relationships are named before code generation."
+ ],
+ "evidenceRefs": [
+ "full-object"
+ ],
+ "failureModes": [
+ "large visible parts are merged into one mesh",
+ "component hierarchy is too shallow for the observed complexity"
+ ]
+ },
+ {
+ "id": "attachment-joint-correctness",
+ "name": "Attachment and joint correctness",
+ "required": true,
+ "qualityCriteria": [
+ "Every visible child appendage, branch, limb, handle, connector, tube, cable, horn, wing, leg, or hinged part has an attachment contract with parent socket, localStart/localEnd, contact type, embed/overlap, and gap tolerance."
+ ],
+ "evidenceRefs": [
+ "full-object"
+ ],
+ "failureModes": [
+ "child part root floats away from the parent",
+ "branch/limb/tube is centered in space instead of pivoting from its root",
+ "parent-child transform mixes world and local coordinates"
+ ]
+ },
+ {
+ "id": "surface-material-response",
+ "name": "Surface material response",
+ "required": true,
+ "qualityCriteria": [
+ "Albedo zones, roughness, normal/bump/displacement intent, cavity dirt, edge wear, and local overrides are specified where visible.",
+ "Important materials define independent albedo, roughness, height/normal, and AO responses instead of reusing one texture for unrelated PBR channels.",
+ "Surface response is decomposed into macro, meso, and micro frequency bands with scale and amplitude tied to object scale."
+ ],
+ "evidenceRefs": [
+ "full-object"
+ ],
+ "failureModes": [
+ "surface looks like flat plastic",
+ "local material variation is missing or not tied to image evidence"
+ ]
+ },
+ {
+ "id": "reference-lookdev",
+ "name": "Reference color, material, and lighting response",
+ "required": true,
+ "qualityCriteria": [
+ "Material-pass names the reference-derived albedo palette, roughness variation, tactile normal/bump/displacement response, and local masks.",
+ "When a source image is available, run reference PBR extraction and require confidence >= 0.7 before treating maps as implementation-ready.",
+ "Lighting-pass names key/fill/rim or environment light, exposure, tone mapping, background, and contact shadow behavior.",
+ "Neutral, grazing-angle, and reference-matched renders prove that surface relief survives relighting and is not painted into albedo."
+ ],
+ "evidenceRefs": [
+ "full-object"
+ ],
+ "failureModes": [
+ "model has acceptable shape but reads as flat shaded or plastic",
+ "colors are a generic average instead of reference-observed local color zones",
+ "lighting is evenly ambient and cannot reproduce the source value range"
+ ]
+ }
+ ],
+ "visualDeltaChecks": [
+ "silhouette and negative-space delta",
+ "component hierarchy depth delta",
+ "repetition density and distribution delta",
+ "material albedo/roughness/normal response delta",
+ "local feature placement and scale delta"
+ ],
+ "antiShallowSpecRules": [
+ "Do not proceed to code if qualityContract.qualityBar is unassessed.",
+ "Do not proceed to code if the spec only contains a root component for a moderate or complex object.",
+ "Do not proceed to code if required featureGroups are not represented by componentTree, materials, or repetitionSystems.",
+ "Do not proceed to code if visible local features are described only in prose and not attached to components/materials/evidenceRefs.",
+ "Do not proceed past structural-pass if attached child parts lack attachment.parentSocket, localStart, localEnd, embedDepth/overlap, and gapTolerance.",
+ "Do not pass material look-dev when albedo is reused as roughness, height, normal, or AO.",
+ "Do not pass material look-dev without macro, meso, and micro surface frequency bands for close-up materials.",
+ "Do not pass reference-fidelity material look-dev from a source image without usable referencePbr maps or an explicit documented limitation.",
+ "Do not patch a spec with extracted PBR maps when extraction confidence is below the target threshold unless the user explicitly accepts lower fidelity.",
+ "Do not place adjacent separate-geometry parts below 0.02 world-unit seam overlap (source: grimoire/build/geometry_patterns.md).",
+ "Do not satisfy raised or recessed relief, fasteners, or grip structure with a map alone when the feature affects form; use geometry or displacement (source: grimoire/build/geometry_patterns.md).",
+ "Adjacent components must overlap by at least 0.02 world units at shared seams (source: grimoire/build/geometry_patterns.md).",
+ "Raised or recessed relief and fasteners must be geometry, instanced micro-parts, or displacement; a map alone is an approximation (source: grimoire/build/geometry_patterns.md)."
+ ],
+ "mustNotDo": [
+ "Do not proceed to code if qualityContract.qualityBar is unassessed.",
+ "Do not proceed to code if the spec only contains a root component for a moderate or complex object.",
+ "Do not proceed to code if required featureGroups are not represented by componentTree, materials, or repetitionSystems.",
+ "Do not proceed to code if visible local features are described only in prose and not attached to components/materials/evidenceRefs.",
+ "Do not proceed past structural-pass if attached child parts lack attachment.parentSocket, localStart, localEnd, embedDepth/overlap, and gapTolerance.",
+ "Do not pass material look-dev when albedo is reused as roughness, height, normal, or AO.",
+ "Do not pass material look-dev without macro, meso, and micro surface frequency bands for close-up materials.",
+ "Do not pass reference-fidelity material look-dev from a source image without usable referencePbr maps or an explicit documented limitation.",
+ "Do not patch a spec with extracted PBR maps when extraction confidence is below the target threshold unless the user explicitly accepts lower fidelity.",
+ "Do not place adjacent separate-geometry parts below 0.02 world-unit seam overlap (source: grimoire/build/geometry_patterns.md).",
+ "Do not satisfy raised or recessed relief, fasteners, or grip structure with a map alone when the feature affects form; use geometry or displacement (source: grimoire/build/geometry_patterns.md).",
+ "Adjacent components must overlap by at least 0.02 world units at shared seams (source: grimoire/build/geometry_patterns.md).",
+ "Raised or recessed relief and fasteners must be geometry, instanced micro-parts, or displacement; a map alone is an approximation (source: grimoire/build/geometry_patterns.md)."
+ ]
+ },
+ "qualityTargets": {
+ "targetFidelity": 0.7,
+ "mustMatch": [
+ "macro silhouette and proportions",
+ "primary material albedo/roughness response",
+ "reference-derived PBR material response at or above 0.7 confidence when source pixels are usable",
+ "most recognizable local features"
+ ],
+ "niceToHave": [
+ "micro scratches, stains, chips, and dirt masks",
+ "secondary lighting match"
+ ],
+ "fpsTarget": 60,
+ "reviewViewpoints": [
+ "front-three-quarter-left",
+ "front",
+ "side-right",
+ "top-lid",
+ "rear"
+ ]
+ },
+ "selfCorrectLoop": {
+ "enabled": true,
+ "visualAcceptance": {
+ "reviewer": "ai-vision",
+ "threshold": 0.7,
+ "comparisonArtifactRequired": true,
+ "layerScoresRequired": true,
+ "codePixelDiffIsAcceptanceAuthority": false,
+ "scoringRule": "AI vision must inspect a side-by-side reference/render sheet and score the current pass from 0 to 1. Pixel-diff code may assist diagnostics but cannot approve a pass.",
+ "requiredLayerScores": [
+ "silhouetteProportion",
+ "componentStructure",
+ "formDetail",
+ "materialSurface",
+ "lightingCamera"
+ ],
+ "featureReviewPolicy": {
+ "enabled": true,
+ "reviewUnit": "semantic-subsystem",
+ "maxCriticalFeaturesPerPass": 5,
+ "maxImportantFeaturesPerPass": 3,
+ "criticalDefaultThreshold": 0.8,
+ "importantAverageThreshold": 0.65,
+ "adaptiveEscalation": true,
+ "singleImagePairOnly": true,
+ "selectionRule": "Choose only the most visually salient, identity-defining, user-prioritized, or high-risk semantic systems. Group repeated parts instead of reviewing every mesh. AI vision scores every selected feature from the same full reference/render pair."
+ }
+ },
+ "reviewAfterPasses": [
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+ "optimization-pass"
+ ],
+ "allowedActions": [
+ "continue",
+ "refine-spec",
+ "refine-code",
+ "request-input",
+ "stop"
+ ],
+ "specRefineTriggers": [
+ "missing component",
+ "wrong primitive family",
+ "wrong proportions",
+ "material layer under-specified",
+ "local feature not traceable to viewEvidence",
+ "reference ambiguity discovered during implementation"
+ ],
+ "codeRefineTriggers": [
+ "spec is adequate but generated geometry/material does not match",
+ "browser render differs from reference",
+ "performance budget exceeded",
+ "lighting hides geometry or material response"
+ ],
+ "stopCriteria": [
+ "target fidelity reached or user accepts current approximation",
+ "remaining gaps require new reference images or manual art"
+ ],
+ "screenshotPolicy": {
+ "requiredForPasses": [
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass"
+ ],
+ "preferredCapture": "in-app-browser-screenshot",
+ "fallbackCapture": "user-supplied-screenshot-path",
+ "minimumEvidence": "Each visual pass needs a reference image, rendered screenshot, side-by-side comparison sheet, AI vision score, layer scores, and critique before choosing continue.",
+ "reviewPairRule": "Compare the same camera/viewpoint whenever possible; do not judge a front reference against a random render angle.",
+ "acceptanceAuthority": "AI vision review of the comparison sheet. Code-generated pixel similarity is not sufficient evidence."
+ }
+ },
+ "featureReviewTargets": [
+ {
+ "id": "case-silhouette-taper",
+ "name": "Tapered body silhouette + rounded-bevel edges",
+ "tier": "critical",
+ "passIds": [
+ "blockout",
+ "form-refinement"
+ ],
+ "minimumScore": 0.8,
+ "mustPass": true,
+ "componentRefs": [
+ "root",
+ "lid"
+ ],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "draw-latch-geometry",
+ "name": "Over-center draw latch pair (cam + metal bail), mirrored placement",
+ "tier": "critical",
+ "passIds": [
+ "structural-pass",
+ "form-refinement"
+ ],
+ "minimumScore": 0.75,
+ "mustPass": true,
+ "componentRefs": [
+ "latch",
+ "latchCam",
+ "latchBail"
+ ],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "decal-logo-lockup",
+ "name": "TRADEIT wordmark + icon + diagonal chevron decal placement/colors",
+ "tier": "critical",
+ "passIds": [
+ "material-pass",
+ "surface-pass"
+ ],
+ "minimumScore": 0.75,
+ "mustPass": true,
+ "componentRefs": [
+ "root"
+ ],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "lid-rib-band",
+ "name": "3-rib lid stiffening band",
+ "tier": "important",
+ "passIds": [
+ "structural-pass"
+ ],
+ "minimumScore": 0.7,
+ "mustPass": false,
+ "componentRefs": [
+ "lid",
+ "lidRidge"
+ ],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "padlock-hasp-hardware",
+ "name": "Brass padlock + hasp loop, closed-state-only accessory",
+ "tier": "important",
+ "passIds": [
+ "structural-pass",
+ "material-pass"
+ ],
+ "minimumScore": 0.65,
+ "mustPass": false,
+ "componentRefs": [
+ "padlock",
+ "padlockBody",
+ "padlockShackle",
+ "haspLoop"
+ ],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "lid-open-hinge-mechanism",
+ "name": "Lid hinge opens/closes matching the second reference's rotation range",
+ "tier": "important",
+ "passIds": [
+ "interaction-pass"
+ ],
+ "minimumScore": 0.65,
+ "mustPass": false,
+ "componentRefs": [
+ "lid"
+ ],
+ "evidenceRefs": [
+ "open-mechanism"
+ ]
+ }
+ ],
+ "sculptPipeline": {
+ "passGateMode": "locked-sequential",
+ "passOrder": [
+ "blockout",
+ "structural-pass",
+ "form-refinement",
+ "material-pass",
+ "surface-pass",
+ "lighting-pass",
+ "interaction-pass",
+ "optimization-pass"
+ ],
+ "currentPass": "blockout",
+ "completedPasses": [],
+ "lastCompletedPass": "",
+ "blockedReason": "blockout requires a browser screenshot and self-correction review before structural-pass unlocks",
+ "nextRequiredEvidence": [
+ "blockout browser render screenshot from your agent's browser/screenshot tool",
+ "side-by-side reference/render comparison sheet",
+ "AI vision score >= 0.7 with layer scores and mismatch critique",
+ "critical semantic feature scores from the same image pair meeting their individual thresholds",
+ "reviewHistory entry for blockout with action=continue"
+ ]
+ },
+ "lookDevTargets": {
+ "qualityPriority": "reference-fidelity",
+ "materialPass": {
+ "albedoPaletteRequired": true,
+ "roughnessVariationRequired": true,
+ "normalOrBumpRequired": true,
+ "localOverridesRequired": true,
+ "minimumTextureResolution": 1024,
+ "preferredTextureResolution": 2048,
+ "independentMapChannels": [
+ "albedo",
+ "roughness",
+ "height",
+ "normal",
+ "ambient-occlusion"
+ ],
+ "requiredSurfaceFrequencyBands": [
+ "macro",
+ "meso",
+ "micro"
+ ],
+ "geometryReliefRequiredWhenSilhouetteAffected": true,
+ "referencePbrExtraction": {
+ "requiredWhenSourceImagePresent": false,
+ "targetThreshold": 0.7,
+ "stopOnLowConfidence": true,
+ "script": "forge/stage1_intake/extract_pbr_evidence.py",
+ "acceptedLimitation": "single-image extraction is reference-derived inference, not exact photogrammetry",
+ "skipReason": "Flat matte-plastic shell + 2-color printed decal, no patterned/photoreal skin -- scalar PBR values estimated by eye per grimoire/build/threejs_texture_reference.md 'solid albedo for flat paint' rule instead of extract_pbr_evidence.py. See spec.risks[0]."
+ },
+ "mustAvoid": [
+ "single flat albedo per material",
+ "uniform roughness",
+ "albedo texture reused as roughness/height/normal/AO",
+ "single-frequency random noise",
+ "plastic-looking smooth bark, stone, cloth, foliage, or aged material",
+ "local color/detail described only in prose without material masks",
+ "claiming exact PBR recovery when confidence is below the target threshold"
+ ]
+ },
+ "lightingPass": {
+ "requiredTerms": [
+ "key light",
+ "fill light",
+ "rim or environment light",
+ "exposure",
+ "tone mapping",
+ "background",
+ "contact shadow"
+ ],
+ "mustAvoid": [
+ "ambient-only lighting",
+ "flat value range",
+ "missing contact shadow",
+ "reference lighting copied without separating material readability"
+ ]
+ },
+ "screenshotReview": [
+ "Compare albedo palette and local color zones.",
+ "Compare roughness/normal/bump response under light.",
+ "Compare cavity dirt, edge wear, stains, moss, scratches, or other local masks.",
+ "Compare key/fill/rim structure, exposure, tone mapping, background, and contact shadows.",
+ "Capture a neutral-light render to verify material readability without reference lighting.",
+ "Capture a grazing-light close-up to expose flat normals, uniform roughness, tiling, and plastic highlights.",
+ "Capture a reference-matched render from the same camera framing as the source."
+ ]
+ },
+ "actionReadiness": {
+ "contract": "Every macro/meso component should be generated as a stable named Object3D pivot node with a mesh child, action metadata, optional sockets, collider proxy, and destruction metadata.",
+ "defaultRigType": "action-ready-static-rig",
+ "rootMotionNode": "root",
+ "requiredComponentFields": [
+ "id",
+ "parent",
+ "transform",
+ "attachment for child appendages, connectors, limbs, tubes, handles, legs, horns, wings, branches, or cables",
+ "actionProfile.animationRole",
+ "actionProfile.pivot",
+ "actionProfile.collider",
+ "actionProfile.destruction"
+ ],
+ "transformChannels": [
+ "translate",
+ "rotate",
+ "scale",
+ "bend",
+ "twist",
+ "detach",
+ "visibility",
+ "material-state"
+ ],
+ "authoringRules": [
+ "Do not collapse independently movable parts into one mesh.",
+ "Put transforms on component pivot groups, not only on raw meshes.",
+ "For attached child parts, put the pivot at the semantic root/socket and build visible geometry from localStart to localEnd.",
+ "Represent hinge, socket, detachable, and breakable intent even when no animation is implemented yet.",
+ "Use simplified collider proxies for runtime physics instead of visual mesh colliders by default."
+ ],
+ "destructionPolicy": {
+ "defaultBreakable": false,
+ "fractureGroupNaming": "Use stable semantic names such as body-shell, left-hinge, glass-panel, branch-segment.",
+ "debrisStrategy": "Prefer detachable component groups and a small number of procedural fragments over random mesh explosion."
+ }
+ },
+ "assumptions": [
+ "Back face, left face, and base/underside are plain shell (no visible evidence either way).",
+ "Hinge barrel/pin geometry is a generic rigid back-top pivot, not measured from pixels.",
+ "Body draft angle ~4-6deg/side, estimated from front-face convergence, not measured.",
+ "Decal graphic is redrawn as a vector canvas-baked texture matched to sampled hex values, not projected from the source photo (resolution/angle too low/oblique for clean de-lit projection).",
+ "Side handle's far-side cross-section is inferred generically from the visible near edge only.",
+ "Hardware layout corrected after a pixel-grid re-measurement pass on case-closed.png: the lid/body seam carries 3 rib-pair gussets (not 2 cam-action draw latches -- no bail/hook hardware is visible on any of them), the lid carries 6 evenly-spaced ribs (not 3), and the grab handle sits on the FRONT face at x-fraction ~0.75 (not on a side face). Two additional side-face handles were added on explicit user request (tay cam 2 ben) as an inferred, unphotographed pair. componentTree/materials below reflect the pre-correction pass and are superseded by src/demos/tradeit-case/createTradeitCaseModel.ts for hardware placement.",
+ "Second correction pass driven by an independent NotebookLM fidelity critique (transcript not stored here, only the verified findings): reduced body taper 0.86->0.95, sharpened bevel radii, replaced 3 short seam gussets with 2 full-height front rib pairs (split into body+lid parts so the seam rides with the hinge) plus 1 short hasp-mount gusset, enlarged the padlock/hasp, made all handles sit behind the shell surface instead of proud of it, and rebuilt the decal as a logo panel boxed into the inter-rib channel plus a solid-colour chevron that reaches and wraps the front-right corner. Two of the critique rounds claims were checked against a pixel grid on case-closed.png before acting: the missing-front-ribs claim was confirmed real (the rib pair at x-fraction ~0.30-0.38 runs the full case height, not just the seam); a repeated no-front-handle claim and an earlier decal-floats-off-the-corner claim did NOT hold up under zoom and were left as originally built -- LLM visual critique was useful but not taken as ground truth over a direct pixel check."
+ ],
+ "coordinateFrame": {
+ "front": "camera-facing side in the reference image",
+ "up": "image up direction",
+ "scaleReference": "unit scale; adjust after first browser render"
+ },
+ "silhouette": {
+ "boundingShape": "tapered rectangular box (frustum-like: full width at the lid seam, ~14% narrower at the base)",
+ "aspectRatios": [
+ "width:height ~ 1.0:0.62",
+ "width:depth ~ 1.0:0.78"
+ ],
+ "symmetry": "bilateral left-right through the vertical center plane; asymmetric front-vs-back",
+ "dominantCurves": [
+ "continuous rounded-fillet bevel on all 12 body/lid edges",
+ "inward body taper from lid seam to base (rotomold draft angle)",
+ "3 parallel rounded ribs across the lid top face"
+ ],
+ "negativeSpaces": [
+ "gap between padlock body and shell front face (padlock hangs free from the hasp loop)",
+ "recessed side-handle pocket reads as a dark negative shape against the shell"
+ ],
+ "landmarks": [
+ "lid/body seam line at ~78% total height",
+ "latch pair at ~30%/70% width, straddling the seam",
+ "hasp loop right of the latches at seam height",
+ "decal panel front-left, chevron front-right"
+ ]
+ },
+ "viewEvidence": [
+ {
+ "id": "closed-front-3q",
+ "view": "primary",
+ "imageRegion": {
+ "x": 0.0,
+ "y": 0.0,
+ "width": 1.0,
+ "height": 1.0,
+ "units": "normalized"
+ },
+ "observations": [
+ "Tapered body + ribbed lid, 2 draw latches, brass padlock on hasp loop, recessed side handle, TRADEIT logo/wordmark + diagonal chevron decal, all on the front-right 3/4 face.",
+ "Studio white background, single soft key light upper-left, low ambient fill."
+ ],
+ "confidence": 0.8
+ },
+ {
+ "id": "open-mechanism",
+ "view": "secondary-mechanism",
+ "imageRegion": {
+ "x": 0.0,
+ "y": 0.0,
+ "width": 1.0,
+ "height": 1.0,
+ "units": "normalized"
+ },
+ "observations": [
+ "Flat-shaded ghost/clay render, NOT a material/color reference.",
+ "Lid hinges at the back-top edge, rotates up+back past vertical to ~100-110 deg open.",
+ "Latches stay mounted to the body, shown flipped to a disengaged/open position near the seam.",
+ "Interior is a single flat-bottom rectangular cavity, no dividers/foam.",
+ "Hasp loop present with no padlock body attached -- padlock is a closed-state-only accessory."
+ ],
+ "confidence": 0.7
+ }
+ ],
+ "componentTree": [
+ {
+ "id": "root",
+ "name": "Body shell",
+ "level": "macro",
+ "role": "body",
+ "importance": 1.0,
+ "confidence": 0.75,
+ "primitive": "box",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Rigid molded lower shell assembled from a rounded box blockout with a taper deform; not an organic/continuous surface.",
+ "geometryDescriptor": {
+ "topologyIntent": "tapered rounded box, full width at the top seam narrowing toward the base",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.045,
+ "segments": 4
+ },
+ "deformationStack": [
+ {
+ "type": "taper",
+ "axis": "y",
+ "factor": 0.86,
+ "notes": "body narrows toward the base (rotomold draft angle); silhouette-affecting, estimated ~4-6deg/side"
+ }
+ ],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": null,
+ "attachment": null,
+ "dimensions": {
+ "width": 1.0,
+ "height": 0.46,
+ "depth": 0.78,
+ "units": "relative",
+ "confidence": 0.75
+ },
+ "transform": {
+ "position": [
+ 0,
+ 0,
+ 0
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "shellMatte",
+ "materialLayers": [
+ "shellMatte"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(33, 35, 39, 1.0)",
+ "secondaryAlbedo": "rgba(24, 26, 28, 1.0)",
+ "materialClass": "plastic",
+ "materialClassConfidence": 0.6,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."
+ },
+ "actionProfile": {
+ "animationRole": "static",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0,
+ 0
+ ],
+ "axis": [
+ 0,
+ 1,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [
+ {
+ "id": "rounded-bevel-edges",
+ "description": "Continuous rounded fillet on all 12 body/lid edges, molded in.",
+ "confidence": 0.8,
+ "level": "macro",
+ "evidence": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "body-taper",
+ "description": "Body narrows from lid seam to base.",
+ "confidence": 0.7,
+ "level": "macro",
+ "evidence": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "front-facet-lines",
+ "description": "Faint vertical panel lines, low-medium confidence -- see material localOverrides.frontFacetLines.",
+ "confidence": 0.35,
+ "level": "micro",
+ "evidence": [
+ "closed-front-3q"
+ ]
+ }
+ ],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "lid",
+ "name": "Lid",
+ "level": "macro",
+ "role": "hinge-lid",
+ "importance": 0.95,
+ "confidence": 0.7,
+ "primitive": "box",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Rigid molded upper shell, same construction family as the body, hinged as a rigid rotation not a deforming shell.",
+ "geometryDescriptor": {
+ "topologyIntent": "rounded box slab, front-bottom lip step at the seam",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.04,
+ "segments": 4
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "root",
+ "attachment": {
+ "parentId": "root",
+ "parentSocket": "lidHingeSocket",
+ "localStart": [
+ 0,
+ 0.23,
+ -0.39
+ ],
+ "localEnd": [
+ 0,
+ 0.23,
+ 0.39
+ ],
+ "contactType": "pivot-hinge",
+ "embedDepth": 0.01,
+ "gapTolerance": 0.004,
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ "dimensions": {
+ "width": 1.02,
+ "height": 0.16,
+ "depth": 0.7956000000000001,
+ "units": "relative",
+ "confidence": 0.7
+ },
+ "transform": {
+ "position": [
+ 0,
+ 0.31,
+ 0
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "shellMatte",
+ "materialLayers": [
+ "shellMatte"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(33, 35, 39, 1.0)",
+ "secondaryAlbedo": "rgba(24, 26, 28, 1.0)",
+ "materialClass": "plastic",
+ "materialClassConfidence": 0.6,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."
+ },
+ "actionProfile": {
+ "animationRole": "hinge",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0.23,
+ -0.39
+ ],
+ "axis": [
+ 1,
+ 0,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": false,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [
+ {
+ "id": "lid-front-lip-step",
+ "description": "Shallow step in the shell where the lid meets the body seam.",
+ "confidence": 0.6,
+ "level": "meso",
+ "evidence": [
+ "closed-front-3q"
+ ]
+ }
+ ],
+ "evidenceRefs": [
+ "closed-front-3q",
+ "open-mechanism"
+ ]
+ },
+ {
+ "id": "lidRidge",
+ "name": "Lid stiffening ridge (repetition template)",
+ "level": "meso",
+ "role": "surface-relief-band",
+ "importance": 0.6,
+ "confidence": 0.75,
+ "primitive": "box",
+ "topologyClass": "surface-relief",
+ "topologyRationale": "Thin raised band molded onto the lid's outer face; relief on a host surface, not an independent volume.",
+ "geometryDescriptor": {
+ "topologyIntent": "thin rounded raised band, instanced 3x via lidRidgeArray",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.006,
+ "segments": 2
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "lid",
+ "attachment": null,
+ "dimensions": {
+ "width": 0.7176,
+ "height": 0.012,
+ "depth": 0.03,
+ "units": "relative",
+ "confidence": 0.75
+ },
+ "transform": {
+ "position": [
+ 0,
+ 0.37,
+ 0
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 1.5708
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "shellMatte",
+ "materialLayers": [
+ "shellMatte"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(33, 35, 39, 1.0)",
+ "secondaryAlbedo": "rgba(24, 26, 28, 1.0)",
+ "materialClass": "plastic",
+ "materialClassConfidence": 0.6,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."
+ },
+ "actionProfile": {
+ "animationRole": "static",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0,
+ 0
+ ],
+ "axis": [
+ 0,
+ 1,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "lidFastener",
+ "name": "Lid edge rivet/screw head (repetition template)",
+ "level": "micro",
+ "role": "fastener",
+ "importance": 0.35,
+ "confidence": 0.55,
+ "primitive": "cylinder",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Small discrete rivet/screw head, a real fastened part, not relief.",
+ "geometryDescriptor": {
+ "topologyIntent": "short lathed cylinder cap",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.002,
+ "segments": 1
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "lid",
+ "attachment": {
+ "parentId": "lid",
+ "parentSocket": "lidEdgeFastenerRow",
+ "localStart": [
+ -0.39,
+ 0.0,
+ 0.0
+ ],
+ "localEnd": [
+ 0.39,
+ 0.0,
+ 0.0
+ ],
+ "contactType": "flush-mount",
+ "embedDepth": 0.003,
+ "gapTolerance": 0.001,
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ "dimensions": {
+ "width": 0.018,
+ "height": 0.006,
+ "depth": 0.018,
+ "units": "relative",
+ "confidence": 0.55
+ },
+ "transform": {
+ "position": [
+ 0,
+ 0.24000000000000002,
+ 0.36
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "hardwareSatin",
+ "materialLayers": [
+ "hardwareSatin"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(140, 142, 146, 1.0)",
+ "secondaryAlbedo": "rgba(90, 92, 96, 1.0)",
+ "materialClass": "metal",
+ "materialClassConfidence": 0.55,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Bright satin metal read on the latch bail / rivet heads / hasp loop, small in frame."
+ },
+ "actionProfile": {
+ "animationRole": "static",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0,
+ 0
+ ],
+ "axis": [
+ 0,
+ 1,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "latch",
+ "name": "Draw latch (left, repetition template)",
+ "level": "meso",
+ "role": "latch",
+ "importance": 0.85,
+ "confidence": 0.65,
+ "primitive": "box",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Assembled cam-latch housing; a compact rigid mechanism, not a continuous sculpt.",
+ "geometryDescriptor": {
+ "topologyIntent": "hard-surface blockout",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.02,
+ "segments": 3
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "root",
+ "attachment": {
+ "parentId": "root",
+ "parentSocket": "latchMountLeft",
+ "localStart": [
+ -0.3,
+ 0.17,
+ 0.39
+ ],
+ "localEnd": [
+ -0.3,
+ 0.25,
+ 0.39
+ ],
+ "contactType": "flush-mount",
+ "embedDepth": 0.008,
+ "gapTolerance": 0.002,
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ "dimensions": {
+ "width": 0.1,
+ "height": 0.09,
+ "depth": 0.05,
+ "units": "relative",
+ "confidence": 0.65
+ },
+ "transform": {
+ "position": [
+ -0.3,
+ 0.21000000000000002,
+ 0.39
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "shellMatte",
+ "materialLayers": [
+ "shellMatte"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(33, 35, 39, 1.0)",
+ "secondaryAlbedo": "rgba(24, 26, 28, 1.0)",
+ "materialClass": "plastic",
+ "materialClassConfidence": 0.6,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."
+ },
+ "actionProfile": {
+ "animationRole": "latch-cam",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ -0.3,
+ 0.21000000000000002,
+ 0.39
+ ],
+ "axis": [
+ 1,
+ 0,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "latchCam",
+ "name": "Latch cam body",
+ "level": "micro",
+ "role": "latch-cam",
+ "importance": 0.5,
+ "confidence": 0.6,
+ "primitive": "box",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "The thumb-actuated cam housing, a discrete rigid box with rounded corners.",
+ "geometryDescriptor": {
+ "topologyIntent": "rounded box cam housing",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.012,
+ "segments": 3
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "latch",
+ "attachment": null,
+ "dimensions": {
+ "width": 0.1,
+ "height": 0.09,
+ "depth": 0.04,
+ "units": "relative",
+ "confidence": 0.6
+ },
+ "transform": {
+ "position": [
+ 0,
+ 0,
+ 0.01
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "shellMatte",
+ "materialLayers": [
+ "shellMatte"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(33, 35, 39, 1.0)",
+ "secondaryAlbedo": "rgba(24, 26, 28, 1.0)",
+ "materialClass": "plastic",
+ "materialClassConfidence": 0.6,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."
+ },
+ "actionProfile": {
+ "animationRole": "static",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0,
+ 0
+ ],
+ "axis": [
+ 0,
+ 1,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "latchBail",
+ "name": "Latch wire bail",
+ "level": "micro",
+ "role": "connector",
+ "importance": 0.45,
+ "confidence": 0.55,
+ "primitive": "torus",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Bent-wire metal bail that hooks over the lid edge catch; a thin rigid loop.",
+ "geometryDescriptor": {
+ "topologyIntent": "half-arc torus bail",
+ "edgeTreatment": {
+ "type": "none",
+ "bevelRadius": 0.0,
+ "segments": 1
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "latch",
+ "attachment": {
+ "parentId": "latch",
+ "parentSocket": "bailPivot",
+ "localStart": [
+ 0,
+ 0.02,
+ 0.015
+ ],
+ "localEnd": [
+ 0,
+ 0.08,
+ 0.015
+ ],
+ "contactType": "hinge-catch",
+ "embedDepth": 0.004,
+ "gapTolerance": 0.002,
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ "dimensions": {
+ "width": 0.09,
+ "height": 0.05,
+ "depth": 0.01,
+ "units": "relative",
+ "confidence": 0.55
+ },
+ "transform": {
+ "position": [
+ 0,
+ 0.05,
+ 0.015
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "hardwareSatin",
+ "materialLayers": [
+ "hardwareSatin"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(140, 142, 146, 1.0)",
+ "secondaryAlbedo": "rgba(90, 92, 96, 1.0)",
+ "materialClass": "metal",
+ "materialClassConfidence": 0.55,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Bright satin metal read on the latch bail / rivet heads / hasp loop, small in frame."
+ },
+ "actionProfile": {
+ "animationRole": "bail-pivot",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0.02,
+ 0.015
+ ],
+ "axis": [
+ 1,
+ 0,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "sideHandle",
+ "name": "Side handle pocket",
+ "level": "meso",
+ "role": "handle-pocket",
+ "importance": 0.4,
+ "confidence": 0.5,
+ "primitive": "box",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "A discrete inset pocket + grip bar assembled from boxes; only the near edge is visible (single view), so this is the lowest-confidence macro/meso part.",
+ "geometryDescriptor": {
+ "topologyIntent": "hard-surface blockout",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.02,
+ "segments": 3
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "root",
+ "attachment": {
+ "parentId": "root",
+ "parentSocket": "sideHandleSocket",
+ "localStart": [
+ 0.47,
+ 0.07,
+ -0.03
+ ],
+ "localEnd": [
+ 0.47,
+ 0.19,
+ 0.13
+ ],
+ "contactType": "inset-socket",
+ "embedDepth": 0.01,
+ "gapTolerance": 0.003,
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ "dimensions": {
+ "width": 0.03,
+ "height": 0.1,
+ "depth": 0.16,
+ "units": "relative",
+ "confidence": 0.5
+ },
+ "transform": {
+ "position": [
+ 0.49,
+ 0.13,
+ 0.05
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "shellMatte",
+ "materialLayers": [
+ "shellMatte"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(33, 35, 39, 1.0)",
+ "secondaryAlbedo": "rgba(24, 26, 28, 1.0)",
+ "materialClass": "plastic",
+ "materialClassConfidence": 0.6,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."
+ },
+ "actionProfile": {
+ "animationRole": "static",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0,
+ 0
+ ],
+ "axis": [
+ 0,
+ 1,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [
+ {
+ "id": "side-handle-recess",
+ "description": "Recessed pocket with an inset grip bar; far side/full cross-section unmeasured.",
+ "confidence": 0.5,
+ "level": "meso",
+ "evidence": [
+ "closed-front-3q"
+ ]
+ }
+ ],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "haspLoop",
+ "name": "Padlock hasp eyeloop",
+ "level": "micro",
+ "role": "socket",
+ "importance": 0.4,
+ "confidence": 0.55,
+ "primitive": "torus",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Small bent-wire/eyebolt loop mounted flush on the shell; a discrete hardware part.",
+ "geometryDescriptor": {
+ "topologyIntent": "hard-surface blockout",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.02,
+ "segments": 3
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "root",
+ "attachment": {
+ "parentId": "root",
+ "parentSocket": "haspMount",
+ "localStart": [
+ 0.1,
+ 0.17500000000000002,
+ 0.39
+ ],
+ "localEnd": [
+ 0.14,
+ 0.20500000000000002,
+ 0.39
+ ],
+ "contactType": "flush-mount",
+ "embedDepth": 0.004,
+ "gapTolerance": 0.002,
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ "dimensions": {
+ "width": 0.03,
+ "height": 0.03,
+ "depth": 0.01,
+ "units": "relative",
+ "confidence": 0.55
+ },
+ "transform": {
+ "position": [
+ 0.12,
+ 0.19,
+ 0.39
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "hardwareSatin",
+ "materialLayers": [
+ "hardwareSatin"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(140, 142, 146, 1.0)",
+ "secondaryAlbedo": "rgba(90, 92, 96, 1.0)",
+ "materialClass": "metal",
+ "materialClassConfidence": 0.55,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Bright satin metal read on the latch bail / rivet heads / hasp loop, small in frame."
+ },
+ "actionProfile": {
+ "animationRole": "static",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0,
+ 0
+ ],
+ "axis": [
+ 0,
+ 1,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "padlock",
+ "name": "Padlock assembly",
+ "level": "meso",
+ "role": "appendage",
+ "importance": 0.55,
+ "confidence": 0.5,
+ "primitive": "box",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Rigid hanging accessory (body + shackle), attached only by the shackle through the hasp loop -- gravity-hung, not fixed.",
+ "geometryDescriptor": {
+ "topologyIntent": "hard-surface blockout",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.02,
+ "segments": 3
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "haspLoop",
+ "attachment": {
+ "parentId": "haspLoop",
+ "parentSocket": "shacklePassthrough",
+ "localStart": [
+ 0.12,
+ 0.17500000000000002,
+ 0.39
+ ],
+ "localEnd": [
+ 0.12,
+ 0.16,
+ 0.39
+ ],
+ "contactType": "through-embed",
+ "embedDepth": 0.006,
+ "gapTolerance": 0.002,
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ "dimensions": {
+ "width": 0.05,
+ "height": 0.08,
+ "depth": 0.02,
+ "units": "relative",
+ "confidence": 0.5
+ },
+ "transform": {
+ "position": [
+ 0.12,
+ 0.14,
+ 0.4
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "brassPlated",
+ "materialLayers": [
+ "brassPlated"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(201, 162, 39, 1.0)",
+ "secondaryAlbedo": "rgba(143, 112, 26, 1.0)",
+ "materialClass": "metal",
+ "materialClassConfidence": 0.5,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Warm gold-yellow padlock body, ~28x40px in frame -- color read solid, roughness/exact hue approximate."
+ },
+ "actionProfile": {
+ "animationRole": "idle-sway",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0.12,
+ 0.19,
+ 0.39
+ ],
+ "axis": [
+ 0,
+ 0,
+ 1
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "padlockBody",
+ "name": "Padlock body",
+ "level": "micro",
+ "role": "lock-body",
+ "importance": 0.4,
+ "confidence": 0.5,
+ "primitive": "box",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Plated brass rectangular body with rounded corners.",
+ "geometryDescriptor": {
+ "topologyIntent": "rounded box lock body",
+ "edgeTreatment": {
+ "type": "rounded",
+ "bevelRadius": 0.008,
+ "segments": 2
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "padlock",
+ "attachment": null,
+ "dimensions": {
+ "width": 0.05,
+ "height": 0.06,
+ "depth": 0.02,
+ "units": "relative",
+ "confidence": 0.5
+ },
+ "transform": {
+ "position": [
+ 0,
+ -0.02,
+ 0
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "brassPlated",
+ "materialLayers": [
+ "brassPlated"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(201, 162, 39, 1.0)",
+ "secondaryAlbedo": "rgba(143, 112, 26, 1.0)",
+ "materialClass": "metal",
+ "materialClassConfidence": 0.5,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Warm gold-yellow padlock body, ~28x40px in frame -- color read solid, roughness/exact hue approximate."
+ },
+ "actionProfile": {
+ "animationRole": "static",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0,
+ 0
+ ],
+ "axis": [
+ 0,
+ 1,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "id": "padlockShackle",
+ "name": "Padlock shackle",
+ "level": "micro",
+ "role": "shackle",
+ "importance": 0.4,
+ "confidence": 0.5,
+ "primitive": "torus",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": "Satin steel U-shaped shackle passing through the hasp loop.",
+ "geometryDescriptor": {
+ "topologyIntent": "half-arc torus shackle",
+ "edgeTreatment": {
+ "type": "none",
+ "bevelRadius": 0.0,
+ "segments": 1
+ },
+ "deformationStack": [],
+ "uvStrategy": "generated procedural coordinates",
+ "normalStrategy": "vertex normals from generated geometry"
+ },
+ "parent": "padlock",
+ "attachment": null,
+ "dimensions": {
+ "width": 0.03,
+ "height": 0.035,
+ "depth": 0.01,
+ "units": "relative",
+ "confidence": 0.5
+ },
+ "transform": {
+ "position": [
+ 0,
+ 0.02,
+ 0
+ ],
+ "rotation": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ]
+ },
+ "material": "steelSatin",
+ "materialLayers": [
+ "steelSatin"
+ ],
+ "colorMaterialRecipe": {
+ "dominantAlbedo": "rgba(154, 156, 162, 1.0)",
+ "secondaryAlbedo": "rgba(106, 108, 114, 1.0)",
+ "materialClass": "metal",
+ "materialClassConfidence": 0.5,
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "samplingNotes": "Cooler gray padlock shackle, small in frame, same finish class as hardwareSatin but slightly cooler/lower-roughness highlight."
+ },
+ "actionProfile": {
+ "animationRole": "static",
+ "pivot": {
+ "mode": "explicit",
+ "localPosition": [
+ 0,
+ 0,
+ 0
+ ],
+ "axis": [
+ 0,
+ 1,
+ 0
+ ],
+ "confidence": 0.6
+ },
+ "transformChannels": {
+ "translate": true,
+ "rotate": true,
+ "scale": false,
+ "bend": false,
+ "twist": false,
+ "detach": false,
+ "visibility": true,
+ "materialState": false
+ },
+ "sockets": [],
+ "collider": {
+ "type": "box",
+ "offset": [
+ 0,
+ 0,
+ 0
+ ],
+ "scale": [
+ 1,
+ 1,
+ 1
+ ],
+ "isTrigger": false,
+ "notes": "Coarse proxy; refine after first browser render."
+ },
+ "constraints": [],
+ "destruction": {
+ "breakable": false,
+ "breakImpulse": 0.0,
+ "fractureGroup": "",
+ "debrisMaterial": "",
+ "seamRefs": [],
+ "detachableFragments": []
+ }
+ },
+ "localFeatures": [],
+ "evidenceRefs": [
+ "closed-front-3q"
+ ]
+ }
+ ],
+ "materials": [
+ {
+ "id": "shellMatte",
+ "name": "Rotomolded shell (matte composite)",
+ "type": "standard",
+ "shaderModel": "MeshStandardMaterial / PBR approximation",
+ "baseColor": "#212327",
+ "color": "#212327",
+ "albedo": {
+ "dominant": "#212327",
+ "secondary": [
+ "#242629",
+ "#181a1c"
+ ],
+ "samplingNotes": "Estimated by eye from a 400x492px studio photo with light falloff toward the silhouette edge; not spectrophotometric. Near-black, slightly warm dark gray, matte -- no crisp specular hotspot on flat panels."
+ },
+ "colorVariation": {
+ "palette": [
+ "#212327",
+ "#242629",
+ "#181a1c"
+ ],
+ "pattern": "uniform",
+ "amplitude": 0.06,
+ "heightCorrelation": 0.1
+ },
+ "textureResolution": 1024,
+ "textureProjection": {
+ "mode": "uv",
+ "repeat": [
+ 1.0,
+ 1.0
+ ],
+ "anisotropy": 8,
+ "texelDensityIntent": "Preserve stable world-scale detail; decal graphics use a dedicated canvas-baked UV island, not tiled repeat."
+ },
+ "surfaceFrequencyBands": [
+ {
+ "id": "macro",
+ "frequency": 1.5,
+ "amplitude": 0.1,
+ "role": "broad color/value read"
+ },
+ {
+ "id": "meso",
+ "frequency": 8.0,
+ "amplitude": 0.05,
+ "role": "fine matte grain / brushing"
+ },
+ {
+ "id": "micro",
+ "frequency": 32.0,
+ "amplitude": 0.02,
+ "role": "highlight breakup under grazing light"
+ }
+ ],
+ "roughness": {
+ "base": 0.62,
+ "variation": 0.08,
+ "map": "independent-procedural-field",
+ "localResponse": "slightly lower roughness on rounded edges/ribs than on flat panels"
+ },
+ "metalness": {
+ "base": 0.0,
+ "variation": 0.03
+ },
+ "normal": {
+ "pattern": "derived-from-independent-height-field",
+ "strength": 0.15,
+ "scale": 20.0,
+ "space": "tangent"
+ },
+ "bump": {
+ "pattern": "fine-matte-grain",
+ "amplitude": 0.01,
+ "scale": 4.0
+ },
+ "displacement": {
+ "pattern": "none",
+ "amplitude": 0.0,
+ "scale": 1.0,
+ "silhouetteAffects": false
+ },
+ "ambientOcclusion": {
+ "cavityStrength": 0.3,
+ "contactShadowBias": 0.3,
+ "notes": "Darken the lid/body seam, latch mounts, hasp loop, and handle pocket."
+ },
+ "wear": {
+ "edgeWear": 0.05,
+ "scratches": [],
+ "chips": []
+ },
+ "dirt": {
+ "amount": 0.0,
+ "cavityBias": 0.0,
+ "color": "#2F2A22"
+ },
+ "localOverrides": [
+ {
+ "id": "tradeitLogoIcon",
+ "description": "Circular blue double-arrow/handshake icon baked into a canvas decal texture, flat print (#2e57e0 fill, white #f2f2f2 linework), no separate geometry/relief.",
+ "confidence": 0.75
+ },
+ {
+ "id": "tradeitWordmark",
+ "description": "White 'TRADEIT' wordmark below the icon, same canvas decal, flat print, no relief.",
+ "confidence": 0.75
+ },
+ {
+ "id": "diagonalChevron",
+ "description": "Wide diagonal blue (#2e57e0) wedge/chevron baked into the same canvas decal, widening from upper-right toward lower-left across the front-right third of the shell.",
+ "confidence": 0.7
+ },
+ {
+ "id": "frontFacetLines",
+ "description": "Faint vertical panel/facet lines on the lower front face \u2014 low-medium confidence, could be render/lighting artifact rather than molded relief; represented as a subtle normal-map micro-band, not geometry, so it can be safely wrong.",
+ "confidence": 0.35
+ }
+ ],
+ "shaderNotes": [
+ "Approximate PBR inference from a single low-resolution studio photo, not extracted measurement; confidence flagged per-field in preSpecAssessment.unknownsToResolveBeforeImplementation."
+ ]
+ },
+ {
+ "id": "hardwareSatin",
+ "name": "Latch/rivet/loop hardware (satin metal)",
+ "type": "physical",
+ "shaderModel": "MeshStandardMaterial / PBR approximation",
+ "baseColor": "#8c8e92",
+ "color": "#8c8e92",
+ "albedo": {
+ "dominant": "#8c8e92",
+ "secondary": [
+ "#a2a4a8",
+ "#5a5c60"
+ ],
+ "samplingNotes": "Estimated by eye from a 400x492px studio photo with light falloff toward the silhouette edge; not spectrophotometric. Latch wire bail, rivet/screw heads, hasp eyeloop -- brighter, higher-specular than the shell."
+ },
+ "colorVariation": {
+ "palette": [
+ "#8c8e92",
+ "#a2a4a8",
+ "#5a5c60"
+ ],
+ "pattern": "mottled",
+ "amplitude": 0.06,
+ "heightCorrelation": 0.1
+ },
+ "textureResolution": 1024,
+ "textureProjection": {
+ "mode": "uv",
+ "repeat": [
+ 1.0,
+ 1.0
+ ],
+ "anisotropy": 8,
+ "texelDensityIntent": "Preserve stable world-scale detail; decal graphics use a dedicated canvas-baked UV island, not tiled repeat."
+ },
+ "surfaceFrequencyBands": [
+ {
+ "id": "macro",
+ "frequency": 1.5,
+ "amplitude": 0.1,
+ "role": "broad color/value read"
+ },
+ {
+ "id": "meso",
+ "frequency": 8.0,
+ "amplitude": 0.05,
+ "role": "fine matte grain / brushing"
+ },
+ {
+ "id": "micro",
+ "frequency": 32.0,
+ "amplitude": 0.02,
+ "role": "highlight breakup under grazing light"
+ }
+ ],
+ "roughness": {
+ "base": 0.35,
+ "variation": 0.08,
+ "map": "independent-procedural-field",
+ "localResponse": "slightly lower roughness on rounded edges/ribs than on flat panels"
+ },
+ "metalness": {
+ "base": 0.78,
+ "variation": 0.03
+ },
+ "normal": {
+ "pattern": "derived-from-independent-height-field",
+ "strength": 0.3,
+ "scale": 20.0,
+ "space": "tangent"
+ },
+ "bump": {
+ "pattern": "brushed-linear",
+ "amplitude": 0.01,
+ "scale": 4.0
+ },
+ "displacement": {
+ "pattern": "none",
+ "amplitude": 0.0,
+ "scale": 1.0,
+ "silhouetteAffects": false
+ },
+ "ambientOcclusion": {
+ "cavityStrength": 0.3,
+ "contactShadowBias": 0.3,
+ "notes": "Darken the lid/body seam, latch mounts, hasp loop, and handle pocket."
+ },
+ "wear": {
+ "edgeWear": 0.05,
+ "scratches": [],
+ "chips": []
+ },
+ "dirt": {
+ "amount": 0.0,
+ "cavityBias": 0.0,
+ "color": "#2F2A22"
+ },
+ "localOverrides": [],
+ "shaderNotes": [
+ "Approximate PBR inference from a single low-resolution studio photo, not extracted measurement; confidence flagged per-field in preSpecAssessment.unknownsToResolveBeforeImplementation."
+ ]
+ },
+ {
+ "id": "brassPlated",
+ "name": "Padlock body (plated brass)",
+ "type": "physical",
+ "shaderModel": "MeshStandardMaterial / PBR approximation",
+ "baseColor": "#c9a227",
+ "color": "#c9a227",
+ "albedo": {
+ "dominant": "#c9a227",
+ "secondary": [
+ "#d8b646",
+ "#8f701a"
+ ],
+ "samplingNotes": "Estimated by eye from a 400x492px studio photo with light falloff toward the silhouette edge; not spectrophotometric. Warm gold-yellow plated metal, small in frame (~28x40px), color read solid, roughness estimated."
+ },
+ "colorVariation": {
+ "palette": [
+ "#c9a227",
+ "#d8b646",
+ "#8f701a"
+ ],
+ "pattern": "mottled",
+ "amplitude": 0.06,
+ "heightCorrelation": 0.1
+ },
+ "textureResolution": 1024,
+ "textureProjection": {
+ "mode": "uv",
+ "repeat": [
+ 1.0,
+ 1.0
+ ],
+ "anisotropy": 8,
+ "texelDensityIntent": "Preserve stable world-scale detail; decal graphics use a dedicated canvas-baked UV island, not tiled repeat."
+ },
+ "surfaceFrequencyBands": [
+ {
+ "id": "macro",
+ "frequency": 1.5,
+ "amplitude": 0.1,
+ "role": "broad color/value read"
+ },
+ {
+ "id": "meso",
+ "frequency": 8.0,
+ "amplitude": 0.05,
+ "role": "fine matte grain / brushing"
+ },
+ {
+ "id": "micro",
+ "frequency": 32.0,
+ "amplitude": 0.02,
+ "role": "highlight breakup under grazing light"
+ }
+ ],
+ "roughness": {
+ "base": 0.3,
+ "variation": 0.08,
+ "map": "independent-procedural-field",
+ "localResponse": "slightly lower roughness on rounded edges/ribs than on flat panels"
+ },
+ "metalness": {
+ "base": 0.75,
+ "variation": 0.03
+ },
+ "normal": {
+ "pattern": "derived-from-independent-height-field",
+ "strength": 0.3,
+ "scale": 20.0,
+ "space": "tangent"
+ },
+ "bump": {
+ "pattern": "brushed-linear",
+ "amplitude": 0.01,
+ "scale": 4.0
+ },
+ "displacement": {
+ "pattern": "none",
+ "amplitude": 0.0,
+ "scale": 1.0,
+ "silhouetteAffects": false
+ },
+ "ambientOcclusion": {
+ "cavityStrength": 0.3,
+ "contactShadowBias": 0.3,
+ "notes": "Darken the lid/body seam, latch mounts, hasp loop, and handle pocket."
+ },
+ "wear": {
+ "edgeWear": 0.05,
+ "scratches": [],
+ "chips": []
+ },
+ "dirt": {
+ "amount": 0.0,
+ "cavityBias": 0.0,
+ "color": "#2F2A22"
+ },
+ "localOverrides": [],
+ "shaderNotes": [
+ "Approximate PBR inference from a single low-resolution studio photo, not extracted measurement; confidence flagged per-field in preSpecAssessment.unknownsToResolveBeforeImplementation."
+ ]
+ },
+ {
+ "id": "steelSatin",
+ "name": "Padlock shackle + latch bail (satin steel)",
+ "type": "physical",
+ "shaderModel": "MeshStandardMaterial / PBR approximation",
+ "baseColor": "#9a9ca2",
+ "color": "#9a9ca2",
+ "albedo": {
+ "dominant": "#9a9ca2",
+ "secondary": [
+ "#b4b6bc",
+ "#6a6c72"
+ ],
+ "samplingNotes": "Estimated by eye from a 400x492px studio photo with light falloff toward the silhouette edge; not spectrophotometric. Cooler gray than the brass body; shared finish class with hardwareSatin but kept distinct for the shackle's slightly higher metalness/lower roughness observed highlight falloff."
+ },
+ "colorVariation": {
+ "palette": [
+ "#9a9ca2",
+ "#b4b6bc",
+ "#6a6c72"
+ ],
+ "pattern": "mottled",
+ "amplitude": 0.06,
+ "heightCorrelation": 0.1
+ },
+ "textureResolution": 1024,
+ "textureProjection": {
+ "mode": "uv",
+ "repeat": [
+ 1.0,
+ 1.0
+ ],
+ "anisotropy": 8,
+ "texelDensityIntent": "Preserve stable world-scale detail; decal graphics use a dedicated canvas-baked UV island, not tiled repeat."
+ },
+ "surfaceFrequencyBands": [
+ {
+ "id": "macro",
+ "frequency": 1.5,
+ "amplitude": 0.1,
+ "role": "broad color/value read"
+ },
+ {
+ "id": "meso",
+ "frequency": 8.0,
+ "amplitude": 0.05,
+ "role": "fine matte grain / brushing"
+ },
+ {
+ "id": "micro",
+ "frequency": 32.0,
+ "amplitude": 0.02,
+ "role": "highlight breakup under grazing light"
+ }
+ ],
+ "roughness": {
+ "base": 0.3,
+ "variation": 0.08,
+ "map": "independent-procedural-field",
+ "localResponse": "slightly lower roughness on rounded edges/ribs than on flat panels"
+ },
+ "metalness": {
+ "base": 0.85,
+ "variation": 0.03
+ },
+ "normal": {
+ "pattern": "derived-from-independent-height-field",
+ "strength": 0.3,
+ "scale": 20.0,
+ "space": "tangent"
+ },
+ "bump": {
+ "pattern": "brushed-linear",
+ "amplitude": 0.01,
+ "scale": 4.0
+ },
+ "displacement": {
+ "pattern": "none",
+ "amplitude": 0.0,
+ "scale": 1.0,
+ "silhouetteAffects": false
+ },
+ "ambientOcclusion": {
+ "cavityStrength": 0.3,
+ "contactShadowBias": 0.3,
+ "notes": "Darken the lid/body seam, latch mounts, hasp loop, and handle pocket."
+ },
+ "wear": {
+ "edgeWear": 0.05,
+ "scratches": [],
+ "chips": []
+ },
+ "dirt": {
+ "amount": 0.0,
+ "cavityBias": 0.0,
+ "color": "#2F2A22"
+ },
+ "localOverrides": [],
+ "shaderNotes": [
+ "Approximate PBR inference from a single low-resolution studio photo, not extracted measurement; confidence flagged per-field in preSpecAssessment.unknownsToResolveBeforeImplementation."
+ ]
+ }
+ ],
+ "repetitionSystems": [
+ {
+ "id": "latchMirrorPair",
+ "kind": "mirror-array",
+ "count": 2,
+ "pitch": 0.6,
+ "axis": "+X",
+ "target": "latch",
+ "realization": "Author 'latch' once at x=-0.3; mirror across the vertical center plane to produce the right-hand latch at x=+0.3 in the generated factory.",
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "confidence": 0.75,
+ "buildsGeometry": true,
+ "instances": 2
+ },
+ {
+ "id": "lidRidgeArray",
+ "kind": "linear-array",
+ "count": 3,
+ "pitch": 0.09,
+ "axis": "+Z",
+ "target": "lidRidge",
+ "realization": "Instance 'lidRidge' 3x evenly spaced across the lid depth.",
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "confidence": 0.8,
+ "buildsGeometry": true,
+ "instances": 3
+ },
+ {
+ "id": "lidFastenerRow",
+ "kind": "linear-array",
+ "count": 4,
+ "pitch": 0.26,
+ "axis": "+X",
+ "target": "lidFastener",
+ "realization": "THREE.InstancedMesh of 'lidFastener' along the lid's front-bottom lip.",
+ "evidence": [
+ "closed-front-3q"
+ ],
+ "confidence": 0.55,
+ "buildsGeometry": true,
+ "instances": 4
+ }
+ ],
+ "buildPasses": [
+ {
+ "id": "blockout",
+ "goal": "Match macro silhouette and proportions.",
+ "componentRefs": [
+ "root"
+ ],
+ "acceptance": [
+ "Silhouette reads correctly without materials.",
+ "Quality contract has named all required macro feature groups before code generation.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold."
+ ]
+ },
+ {
+ "id": "structural-pass",
+ "goal": "Build the component hierarchy implied by the pre-spec complexity assessment.",
+ "componentRefs": [
+ "root"
+ ],
+ "acceptance": [
+ "Macro, meso, and repeated structures meet qualityContract.minimumSpecDepth.",
+ "Parent-child relations, joints, seams, sockets, and contact points are explicit.",
+ "Every attached child appendage/connector has parentSocket, localStart/localEnd, contactType, embedDepth or overlap, and gapTolerance.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold."
+ ]
+ },
+ {
+ "id": "form-refinement",
+ "goal": "Refine shape, deformation, bevels, tapers, curves, asymmetry, and visible local geometry.",
+ "componentRefs": [
+ "root"
+ ],
+ "acceptance": [
+ "Important visible forms are represented in component geometryDescriptor, deformations, localFeatures, or repetitionSystems.",
+ "Endpoint-based child parts are rooted at their attachment sockets and do not visibly float away from parents.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold."
+ ]
+ },
+ {
+ "id": "material-pass",
+ "goal": "Match material color, roughness, bump, and local variation.",
+ "componentRefs": [
+ "root"
+ ],
+ "acceptance": [
+ "Reference-derived albedo palette records dominant, secondary, and accent colors per visible material.",
+ "Each important material defines roughness variation and at least one normal/bump/displacement response.",
+ "Local material overrides, dirt/wear/stains/moss/chips/scratches or equivalent masks are tied to evidenceRefs.",
+ "Thin, transparent, reflective, wet, or fibrous materials document alpha/transmission/clearcoat/metalness/fiber response when relevant.",
+ "Generated preview uses procedural albedo/roughness/bump texture or vertex color variation instead of one flat color.",
+ "Generated preview uses independent PBR maps at 1024px or higher for the quality-first tier.",
+ "If source pixels are available, referencePbr extraction passed at confidence >= 0.7 or the pass is stopped/requesting better references.",
+ "Macro, meso, and micro surface frequency bands are visible at the intended review distance without obvious tiling.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold."
+ ]
+ },
+ {
+ "id": "surface-pass",
+ "goal": "Add procedural surface locality such as normal/bump/displacement, AO, dirt, stains, chips, grain, moss, scratches, and wear.",
+ "componentRefs": [
+ "root"
+ ],
+ "acceptance": [
+ "Every required material feature group has local overrides or surfaceDetail tied to evidenceRefs.",
+ "A grazing-angle close-up proves that normal/height detail breaks highlights naturally and does not read as smooth plastic.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold."
+ ]
+ },
+ {
+ "id": "lighting-pass",
+ "goal": "Make material and form readable under neutral turntable lighting plus optional reference lighting.",
+ "componentRefs": [
+ "root"
+ ],
+ "acceptance": [
+ "lightingFromPhoto identifies key light direction/color/intensity, fill light, rim or environment light, and ambient color.",
+ "Exposure, tone mapping, background color/gradient, shadow softness, and contact shadow behavior are specified.",
+ "Lighting does not hide geometry/material gaps and screenshots can be compared fairly to the reference.",
+ "Neutral, grazing, and reference-matched lighting checks distinguish material errors from lighting errors.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold."
+ ]
+ },
+ {
+ "id": "interaction-pass",
+ "goal": "Make the model ready for future animation, transformation, physics, or destruction.",
+ "componentRefs": [
+ "root"
+ ],
+ "acceptance": [
+ "Macro and movable meso components have stable pivot nodes.",
+ "Sockets, collider proxies, and destruction metadata are present for future runtime actions.",
+ "AI vision comparison score meets selfCorrectLoop.visualAcceptance.threshold."
+ ]
+ },
+ {
+ "id": "optimization-pass",
+ "goal": "Protect runtime performance after visual fidelity is accepted.",
+ "componentRefs": [
+ "root"
+ ],
+ "acceptance": [
+ "Triangle count, draw calls, instancing, LOD strategy, and FPS target are documented or verified.",
+ "Repeated detail is instanced or simplified where possible without breaking silhouette/material believability."
+ ]
+ }
+ ],
+ "visualEvidence": [],
+ "reviewHistory": [],
+ "lodPlan": [
+ {
+ "tier": "near",
+ "distance": 0,
+ "strategy": "full component tree and material layers"
+ },
+ {
+ "tier": "far",
+ "distance": 30,
+ "strategy": "merge static components and reduce local feature geometry"
+ }
+ ],
+ "performanceBudget": {
+ "qualityPriority": "reference-fidelity",
+ "targetTriangles": 250000,
+ "maxDrawCalls": 160,
+ "textureSize": 2048,
+ "fpsTarget": 30,
+ "optimizationPolicy": "Reach accepted visual fidelity first, then optimize without removing reference-critical geometry or surface layers."
+ },
+ "lightingFromPhoto": [
+ {
+ "role": "key",
+ "direction": "upper-left, ~45deg elevation",
+ "colorTemp": "neutral-cool studio",
+ "intensity": "moderate",
+ "evidence": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "role": "fill",
+ "direction": "ambient/bounce, low contrast ratio",
+ "colorTemp": "neutral",
+ "intensity": "low",
+ "evidence": [
+ "closed-front-3q"
+ ]
+ },
+ {
+ "role": "environment",
+ "direction": "soft studio IBL",
+ "colorTemp": "neutral",
+ "intensity": "low",
+ "note": "ACES filmic tone mapping, exposure ~1.0; soft contact shadow under the case on the ground plane.",
+ "evidence": [
+ "closed-front-3q"
+ ]
+ }
+ ],
+ "proceduralStrategy": [
+ "Block out macro silhouette first.",
+ "Add component hierarchy and joints.",
+ "Create stable pivot groups, sockets, collider proxies, and destruction metadata before visual polish.",
+ "Refine forms with bevels, tapers, bends, and procedural noise.",
+ "Run reference PBR extraction for important source-image materials and stop when confidence is below the target threshold.",
+ "Add material variation before adding expensive micro-geometry."
+ ],
+ "animationAnchors": [
+ "root pivot node supports whole-object translation, rotation, scale, and visibility changes",
+ "component pivot groups support later local transforms without rebuilding geometry"
+ ],
+ "destructionAnchors": [
+ "actionProfile.destruction.fractureGroup marks detachable or breakable component sets",
+ "component seams and sockets define plausible break points instead of random explosions"
+ ],
+ "risks": [
+ "Shell and decal-blue hex values are eyeballed from a 400x492px photo with light falloff -- may need a hue/value correction pass after the first render.",
+ "front-facet-lines detail (confidence 0.35) may be a lighting artifact rather than real molded relief; kept as a subtle normal-map band so being wrong costs little fidelity.",
+ "Latch internal spring/pivot geometry is generic, not reference-derived -- only the exterior reads matter for fidelity.",
+ "A shared showcase ground/shadow-catcher plane sits at world Y=0 and depth-occludes any mesh below it; the factory now lifts the whole model so its base rests at Y=0 (see root.position.y in createTradeitCaseModel.ts) -- this is a showcase-integration constraint, not a reference-fidelity one."
+ ],
+ "localSpecSearch": {
+ "collection": "core_3d",
+ "query": "TradeIt Hard Case rotomolded case draft angle taper over-center draw latch cam bail canvas decal texture logo hinge pivot lid rotation brass padlock shackle matte plastic roughness PBR",
+ "index": {
+ "status": "hit",
+ "reason": "current",
+ "fingerprint": "6857e5ab528b42ac12f4f411f862610a0bffce8e47aee3610a7603c318072fe8"
+ },
+ "matches": [
+ {
+ "record_id": "core.socket-pivot",
+ "file_path": "grimoire/glossary/3d_vocabulary.md",
+ "heading": "Animation, Physics, And Destruction",
+ "key_path": null,
+ "score": 18.725599378212,
+ "snippets": [
+ "A pivot is a local rotation origin; a socket is an attachment point for a child part. In a runtime hierarchy, a socket Object3D is a child of the relevant pivot."
+ ],
+ "source_refs": [
+ {
+ "path": "grimoire/glossary/3d_vocabulary.md",
+ "heading": "Animation, Physics, And Destruction",
+ "key_path": null
+ },
+ {
+ "path": "grimoire/readiness/action_rigging.md",
+ "heading": "Hierarchy Pattern",
+ "key_path": null
+ }
+ ],
+ "evidence_refs": [
+ {
+ "kind": "source",
+ "ref": "grimoire/readiness/action_rigging.md"
+ },
+ {
+ "kind": "notebooklm-research",
+ "ref": "notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843",
+ "note": "Validated generic schema vocabulary; numeric claims remain backed by local source_refs."
+ }
+ ]
+ },
+ {
+ "record_id": "core.pbr-roughness",
+ "file_path": "grimoire/glossary/3d_vocabulary.md",
+ "heading": "Material And PBR",
+ "key_path": null,
+ "score": 11.159824817191,
+ "snippets": [
+ "Roughness is microfacet scatter: high roughness reads matte and low roughness reads glossy. Recognition cues: low roughness reads as a sharp, mirror-like, tight specular highlight; high roughness reads as a blurry, wide, dim highlight and matte ..."
+ ],
+ "source_refs": [
+ {
+ "path": "grimoire/glossary/3d_vocabulary.md",
+ "heading": "Material And PBR",
+ "key_path": null
+ },
+ {
+ "path": "grimoire/intake/image_analysis.md",
+ "heading": "Layer 5 \u2014 Materials & surface (PBR)",
+ "key_path": null
+ },
+ {
+ "path": "docs/raw/img2threejs-skill-dataset.json",
+ "heading": null,
+ "key_path": "categories.material_pbr[1]"
+ }
+ ],
+ "evidence_refs": [
+ {
+ "kind": "source",
+ "ref": "grimoire/glossary/3d_vocabulary.md"
+ },
+ {
+ "kind": "notebooklm-research",
+ "ref": "notebooklm:4b03c2f9-8393-411f-b5b4-039ab9532843",
+ "note": "Validated generic schema vocabulary; numeric claims remain backed by local source_refs."
+ },
+ {
+ "kind": "source",
+ "ref": "docs/raw/img2threejs-skill-dataset.json",
+ "note": "img2threejs NotebookLM research distillation \u2014 merged recognition cues + Three.js target instead of duplicating this entity."
+ }
+ ]
+ },
+ {
+ "record_id": "core.pbr-hand-painted-vs-pbr-texture",
+ "file_path": "docs/raw/img2threejs-skill-dataset.json",
+ "heading": null,
+ "key_path": "categories.material_pbr[12]",
+ "score": 10.098736381353,
+ "snippets": [
+ "... baked directly into color (static, stylized) from textures that respond dynamically to scene lighting via separate PBR channels. Ph\u00e2n bi\u1ec7t k\u1ebft c\u1ea5u c\u00f3 \u00e1nh s\u00e1ng \u0111\u01b0\u1ee3c n\u01b0\u1edbng tr\u1ef1c ti\u1ebfp v\u00e0o m\u00e0u (t\u0129nh, c\u00e1ch \u0111i\u1ec7u) v\u1edbi k\u1ebft c\u1ea5u ph\u1ea3n h\u1ed3i \u0111\u1ed9ng ..."
+ ],
+ "source_refs": [
+ {
+ "path": "docs/raw/img2threejs-skill-dataset.json",
+ "heading": null,
+ "key_path": "categories.material_pbr[12]"
+ }
+ ],
+ "evidence_refs": [
+ {
+ "kind": "source",
+ "ref": "docs/raw/img2threejs-skill-dataset.json",
+ "note": "img2threejs NotebookLM research distillation"
+ }
+ ]
+ }
+ ]
+ }
+}
\ No newline at end of file
diff --git a/forge/tests/fixtures/reference_target_oracle.ts b/forge/tests/fixtures/reference_target_oracle.ts
new file mode 100644
index 0000000..85512b9
--- /dev/null
+++ b/forge/tests/fixtures/reference_target_oracle.ts
@@ -0,0 +1,824 @@
+import * as THREE from 'three';
+import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
+import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
+import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';
+import { BokehPass } from 'three/examples/jsm/postprocessing/BokehPass.js';
+import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';
+import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
+
+export type ProceduralModelOptions = {
+ wireframe?: boolean;
+ castShadow?: boolean;
+ receiveShadow?: boolean;
+ textureSize?: number;
+ textureAnisotropy?: number;
+ qualityPriority?: 'reference-fidelity' | 'balanced';
+};
+
+export type ProceduralModelRuntime = {
+ nodes: Record<string, THREE.Object3D>;
+ meshes: Record<string, THREE.Mesh>;
+ sockets: Record<string, THREE.Object3D>;
+ colliders: Record<string, unknown>;
+ destructionGroups: Record<string, THREE.Object3D[]>;
+};
+
+type SculptMaterialSpec = Record<string, any>;
+
+function hashString(value: string): number {
+ let hash = 2166136261;
+ for (let index = 0; index < value.length; index += 1) {
+ hash ^= value.charCodeAt(index);
+ hash = Math.imul(hash, 16777619);
+ }
+ return hash >>> 0;
+}
+
+function readLayerNumber(value: unknown, keys: string[], fallback: number): number {
+ if (typeof value === 'number') return value;
+ if (value && typeof value === 'object') {
+ const record = value as Record<string, unknown>;
+ for (const key of keys) {
+ if (typeof record[key] === 'number') return record[key] as number;
+ }
+ }
+ return fallback;
+}
+
+function hexToRgb(hex: string): [number, number, number] {
+ const normalized = /^#[0-9a-f]{3}$/i.test(hex)
+ ? '#' + hex.slice(1).split('').map((part) => part + part).join('')
+ : hex;
+ const value = /^#[0-9a-f]{6}$/i.test(normalized) ? Number.parseInt(normalized.slice(1), 16) : 0x8a7a5f;
+ return [clampAlbedoChannel((value >> 16) & 255), clampAlbedoChannel((value >> 8) & 255), clampAlbedoChannel(value & 255)];
+}
+
+function materialPalette(spec: SculptMaterialSpec): string[] {
+ const palette = spec.colorVariation?.palette;
+ if (Array.isArray(palette) && palette.length > 0) return palette.filter((value) => typeof value === 'string');
+ const secondary = spec.albedo?.secondary;
+ const colors = [spec.baseColor ?? spec.color ?? spec.albedo?.dominant, ...(Array.isArray(secondary) ? secondary : [])];
+ return colors.filter((value): value is string => typeof value === 'string' && value.startsWith('#'));
+}
+
+function clamp01(value: number): number {
+ return Math.max(0, Math.min(1, value));
+}
+
+function clampAlbedoChannel(value: number): number {
+ return Math.max(30, Math.min(240, Math.round(value)));
+}
+
+function clampPbrF0(value: number): number {
+ return Math.max(0.02, Math.min(1, value));
+}
+
+function clampPbrIor(value: number): number {
+ return Math.max(1, Math.min(2.5, value));
+}
+
+function clampPbrMetalness(value: number): number {
+ return value >= 0.5 ? 1 : 0;
+}
+
+function clampedAlbedoColor(spec: SculptMaterialSpec): THREE.Color {
+ const source = typeof spec.baseColor === 'string' ? spec.baseColor : '#8A7A5F';
+ // setStyle with an explicit SRGBColorSpace, NOT the numeric constructor.
+ //
+ // `new THREE.Color(r, g, b)` treats its arguments as LINEAR working-space components,
+ // while an authored `baseColor` hex is sRGB. Feeding one to the other skipped the
+ // transfer function and lifted every dark albedo: #2e2a28, authored as a near-black
+ // vinyl, rendered at roughly sRGB 0.46 — a mid grey. The error is largest exactly where
+ // it matters most, because the transfer curve is steepest near black.
+ return new THREE.Color().setStyle(source, THREE.SRGBColorSpace);
+}
+
+function smoothCurve(value: number): number {
+ return value * value * (3 - 2 * value);
+}
+
+function periodicHash(x: number, y: number, seed: number, periodX: number, periodY: number): number {
+ const wrappedX = ((x % periodX) + periodX) % periodX;
+ const wrappedY = ((y % periodY) + periodY) % periodY;
+ let value = Math.imul(wrappedX + seed * 17, 374761393) ^ Math.imul(wrappedY + seed * 31, 668265263);
+ value = Math.imul(value ^ (value >>> 13), 1274126177);
+ return ((value ^ (value >>> 16)) >>> 0) / 4294967295;
+}
+
+function periodicValueNoise(u: number, v: number, seed: number, periodX: number, periodY: number): number {
+ const x = u * periodX;
+ const y = v * periodY;
+ const x0 = Math.floor(x);
+ const y0 = Math.floor(y);
+ const tx = smoothCurve(x - x0);
+ const ty = smoothCurve(y - y0);
+ const a = periodicHash(x0, y0, seed, periodX, periodY);
+ const b = periodicHash(x0 + 1, y0, seed, periodX, periodY);
+ const c = periodicHash(x0, y0 + 1, seed, periodX, periodY);
+ const d = periodicHash(x0 + 1, y0 + 1, seed, periodX, periodY);
+ return THREE.MathUtils.lerp(THREE.MathUtils.lerp(a, b, tx), THREE.MathUtils.lerp(c, d, tx), ty);
+}
+
+type SurfaceBand = {
+ frequency: number;
+ amplitude: number;
+ stretchX: number;
+ stretchY: number;
+ ridge: boolean;
+};
+
+function surfaceBands(spec: SculptMaterialSpec): SurfaceBand[] {
+ const source = Array.isArray(spec.surfaceFrequencyBands) ? spec.surfaceFrequencyBands : [];
+ const parsed = source.flatMap((item: unknown) => {
+ if (!item || typeof item !== 'object') return [];
+ const band = item as Record<string, unknown>;
+ const frequency = typeof band.frequency === 'number' ? band.frequency : 0;
+ const amplitude = typeof band.amplitude === 'number' ? band.amplitude : 0;
+ if (frequency <= 0 || amplitude <= 0) return [];
+ const stretch = Array.isArray(band.stretch) ? band.stretch : [1, 1];
+ const description = `${String(band.pattern ?? '')} ${String(band.role ?? '')}`.toLowerCase();
+ return [{
+ frequency,
+ amplitude,
+ stretchX: typeof stretch[0] === 'number' ? Math.max(0.1, stretch[0]) : 1,
+ stretchY: typeof stretch[1] === 'number' ? Math.max(0.1, stretch[1]) : 1,
+ ridge: /(ridge|groove|grain|fiber|striated|crack)/.test(description),
+ }];
+ });
+ return parsed.length > 0 ? parsed : [
+ { frequency: 2, amplitude: 0.42, stretchX: 1, stretchY: 1, ridge: false },
+ { frequency: 12, amplitude: 0.22, stretchX: 1, stretchY: 1, ridge: false },
+ { frequency: 56, amplitude: 0.08, stretchX: 1, stretchY: 1, ridge: false },
+ ];
+}
+
+function sampleSurface(u: number, v: number, bands: SurfaceBand[], seed: number): number {
+ let value = 0;
+ let weight = 0;
+ for (let index = 0; index < bands.length; index += 1) {
+ const band = bands[index];
+ const periodX = Math.max(1, Math.round(band.frequency * band.stretchX));
+ const periodY = Math.max(1, Math.round(band.frequency * band.stretchY));
+ let sample = periodicValueNoise(u, v, seed + index * 1013, periodX, periodY);
+ if (band.ridge) sample = 1 - Math.abs(sample * 2 - 1);
+ value += sample * band.amplitude;
+ weight += band.amplitude;
+ }
+ return weight > 0 ? clamp01(value / weight) : 0.5;
+}
+
+function mixPalette(colors: [number, number, number][], value: number): [number, number, number] {
+ if (colors.length === 1) return colors[0];
+ const scaled = clamp01(value) * (colors.length - 1);
+ const index = Math.min(colors.length - 2, Math.floor(scaled));
+ const mix = scaled - index;
+ const a = colors[index];
+ const b = colors[index + 1];
+ return [
+ Math.round(THREE.MathUtils.lerp(a[0], b[0], mix)),
+ Math.round(THREE.MathUtils.lerp(a[1], b[1], mix)),
+ Math.round(THREE.MathUtils.lerp(a[2], b[2], mix)),
+ ];
+}
+
+type ColorGradientStop = { offset: number; color: string };
+type ColorGradientSpec = {
+ type: 'linear' | 'radial';
+ axis: [number, number];
+ stops: ColorGradientStop[];
+};
+
+function parseRgba(value: string): [number, number, number] {
+ const match = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(value);
+ if (!match) return [138, 122, 95];
+ return [clampAlbedoChannel(Number(match[1])), clampAlbedoChannel(Number(match[2])), clampAlbedoChannel(Number(match[3]))];
+}
+
+// Analytical per-pixel gradient sample. The extraction schema's colorGradient carries
+// exact rgba(...) stop colors (see extract_part_color_recipe.py), so this samples the
+// same trend directly in JS math rather than round-tripping through a Canvas 2D
+// createLinearGradient/createRadialGradient object — same visual result, and it composes
+// directly with the existing noise/height-correlated colorVariation blend below.
+function sampleColorGradient(gradient: ColorGradientSpec, u: number, v: number): [number, number, number] {
+ const stops = gradient.stops.length >= 2 ? gradient.stops : [{ offset: 0, color: 'rgba(138,122,95,1)' }, { offset: 1, color: 'rgba(138,122,95,1)' }];
+ let t: number;
+ if (gradient.type === 'radial') {
+ const [cx, cy] = gradient.axis;
+ const dx = u - cx;
+ const dy = v - cy;
+ const maxRadius = Math.max(0.001, Math.hypot(Math.max(cx, 1 - cx), Math.max(cy, 1 - cy)));
+ t = clamp01(Math.hypot(dx, dy) / maxRadius);
+ } else {
+ const [ax, ay] = gradient.axis;
+ const projection = (u - 0.5) * ax + (v - 0.5) * ay;
+ const maxProjection = 0.5 * (Math.abs(ax) + Math.abs(ay)) || 0.5;
+ t = clamp01(projection / maxProjection + 0.5);
+ }
+ const scaled = t * (stops.length - 1);
+ const index = Math.min(stops.length - 2, Math.max(0, Math.floor(scaled)));
+ const mix = scaled - index;
+ const a = parseRgba(stops[index].color);
+ const b = parseRgba(stops[index + 1].color);
+ return [
+ THREE.MathUtils.lerp(a[0], b[0], mix),
+ THREE.MathUtils.lerp(a[1], b[1], mix),
+ THREE.MathUtils.lerp(a[2], b[2], mix),
+ ];
+}
+
+function writePixel(data: Uint8ClampedArray, offset: number, red: number, green: number, blue: number): void {
+ data[offset] = Math.max(0, Math.min(255, Math.round(red)));
+ data[offset + 1] = Math.max(0, Math.min(255, Math.round(green)));
+ data[offset + 2] = Math.max(0, Math.min(255, Math.round(blue)));
+ data[offset + 3] = 255;
+}
+
+function makeCanvas(size: number): HTMLCanvasElement {
+ const canvas = document.createElement('canvas');
+ canvas.width = size;
+ canvas.height = size;
+ return canvas;
+}
+
+function createMapTexture(
+ canvas: HTMLCanvasElement,
+ colorSpace: THREE.ColorSpace,
+ spec: SculptMaterialSpec,
+ options: ProceduralModelOptions,
+): THREE.CanvasTexture {
+ const texture = new THREE.CanvasTexture(canvas);
+ const projection = spec.textureProjection && typeof spec.textureProjection === 'object' ? spec.textureProjection : {};
+ const repeat = Array.isArray(projection.repeat) ? projection.repeat : [2, 2];
+ texture.colorSpace = colorSpace;
+ texture.wrapS = THREE.RepeatWrapping;
+ texture.wrapT = THREE.RepeatWrapping;
+ texture.repeat.set(
+ typeof repeat[0] === 'number' ? repeat[0] : 2,
+ typeof repeat[1] === 'number' ? repeat[1] : 2,
+ );
+ texture.anisotropy = Math.max(1, Math.round(options.textureAnisotropy ?? projection.anisotropy ?? 8));
+ texture.needsUpdate = true;
+ return texture;
+}
+
+type ProceduralTextureSet = {
+ albedo: THREE.Texture;
+ roughness: THREE.Texture;
+ height: THREE.Texture;
+ normal: THREE.Texture;
+ ao: THREE.Texture;
+ source: 'reference-pixel-extraction' | 'procedural';
+};
+
+function referenceMapUrl(spec: SculptMaterialSpec, channel: string): string | null {
+ const reference = spec.referencePbr;
+ if (!reference || typeof reference !== 'object') return null;
+ if (reference.usable === false) return null;
+ const confidence = typeof reference.confidence === 'number'
+ ? reference.confidence
+ : (typeof reference.estimatedFidelity === 'number' ? reference.estimatedFidelity : 0);
+ const threshold = typeof reference.targetThreshold === 'number' ? reference.targetThreshold : 0.7;
+ if (confidence < threshold) return null;
+ const maps = reference.maps;
+ if (!maps || typeof maps !== 'object') return null;
+ const map = (maps as Record<string, unknown>)[channel];
+ if (!map || typeof map !== 'object') return null;
+ const record = map as Record<string, unknown>;
+ const url = typeof record.url === 'string' && record.url.trim() ? record.url : record.path;
+ return typeof url === 'string' && url.trim() ? url : null;
+}
+
+function createLoadedMapTexture(
+ url: string,
+ colorSpace: THREE.ColorSpace,
+ spec: SculptMaterialSpec,
+ options: ProceduralModelOptions,
+): THREE.Texture {
+ const texture = new THREE.TextureLoader().load(url);
+ const projection = spec.textureProjection && typeof spec.textureProjection === 'object' ? spec.textureProjection : {};
+ const repeat = Array.isArray(projection.repeat) ? projection.repeat : [1, 1];
+ texture.colorSpace = colorSpace;
+ texture.wrapS = THREE.RepeatWrapping;
+ texture.wrapT = THREE.RepeatWrapping;
+ texture.repeat.set(
+ typeof repeat[0] === 'number' ? repeat[0] : 1,
+ typeof repeat[1] === 'number' ? repeat[1] : 1,
+ );
+ texture.anisotropy = Math.max(1, Math.round(options.textureAnisotropy ?? projection.anisotropy ?? 8));
+ texture.needsUpdate = true;
+ return texture;
+}
+
+function makeReferenceTextureSet(spec: SculptMaterialSpec, options: ProceduralModelOptions): ProceduralTextureSet | null {
+ const albedo = referenceMapUrl(spec, 'albedo');
+ const roughness = referenceMapUrl(spec, 'roughness');
+ const height = referenceMapUrl(spec, 'height');
+ const normal = referenceMapUrl(spec, 'normal');
+ const ao = referenceMapUrl(spec, 'ao');
+ if (!albedo || !roughness || !height || !normal || !ao) return null;
+ return {
+ albedo: createLoadedMapTexture(albedo, THREE.SRGBColorSpace, spec, options),
+ roughness: createLoadedMapTexture(roughness, THREE.NoColorSpace, spec, options),
+ height: createLoadedMapTexture(height, THREE.NoColorSpace, spec, options),
+ normal: createLoadedMapTexture(normal, THREE.NoColorSpace, spec, options),
+ ao: createLoadedMapTexture(ao, THREE.NoColorSpace, spec, options),
+ source: 'reference-pixel-extraction',
+ };
+}
+
+function makeProceduralTextureSet(
+ id: string,
+ spec: SculptMaterialSpec,
+ options: ProceduralModelOptions,
+): ProceduralTextureSet | null {
+ if (typeof document === 'undefined') return null;
+ const qualityFirst = (options.qualityPriority ?? 'reference-fidelity') === 'reference-fidelity';
+ const requested = options.textureSize ?? spec.textureResolution;
+ const requestedSize = typeof requested === 'number' && Number.isFinite(requested)
+ ? requested
+ : (qualityFirst ? 1024 : 512);
+ const size = Math.max(256, Math.min(2048, 2 ** Math.round(Math.log2(requestedSize))));
+ const canvases = {
+ albedo: makeCanvas(size),
+ roughness: makeCanvas(size),
+ height: makeCanvas(size),
+ normal: makeCanvas(size),
+ ao: makeCanvas(size),
+ };
+ const contexts = {
+ albedo: canvases.albedo.getContext('2d'),
+ roughness: canvases.roughness.getContext('2d'),
+ height: canvases.height.getContext('2d'),
+ normal: canvases.normal.getContext('2d'),
+ ao: canvases.ao.getContext('2d'),
+ };
+ if (!contexts.albedo || !contexts.roughness || !contexts.height || !contexts.normal || !contexts.ao) return null;
+ const images = {
+ albedo: contexts.albedo.createImageData(size, size),
+ roughness: contexts.roughness.createImageData(size, size),
+ height: contexts.height.createImageData(size, size),
+ normal: contexts.normal.createImageData(size, size),
+ ao: contexts.ao.createImageData(size, size),
+ };
+ const seed = hashString(id);
+ const bands = surfaceBands(spec);
+ const heightField = new Float32Array(size * size);
+ const roughnessField = new Float32Array(size * size);
+ const palette = materialPalette(spec);
+ const fallback = typeof spec.baseColor === 'string' ? spec.baseColor : '#8A7A5F';
+ const colors = (palette.length >= 2 ? palette : [fallback, '#6E614B', '#A08F70']).map(hexToRgb);
+ const baseRoughness = clamp01(readLayerNumber(spec.roughness, ['base'], 0.76));
+ const roughnessVariation = clamp01(readLayerNumber(spec.roughness, ['variation'], 0.18));
+ const colorAmplitude = clamp01(readLayerNumber(spec.colorVariation, ['amplitude', 'variation'], 0.18));
+ const heightCorrelation = clamp01(readLayerNumber(spec.colorVariation, ['heightCorrelation'], 0.3));
+ const colorGradient: ColorGradientSpec | undefined = spec.colorGradient;
+ for (let y = 0; y < size; y += 1) {
+ const v = y / size;
+ for (let x = 0; x < size; x += 1) {
+ const u = x / size;
+ const index = y * size + x;
+ const height = sampleSurface(u, v, bands, seed + 101);
+ const roughNoise = sampleSurface(u, v, bands, seed + 7001);
+ const colorNoise = sampleSurface(u, v, bands, seed + 15013);
+ heightField[index] = height;
+ roughnessField[index] = clamp01(baseRoughness + (roughNoise - 0.5) * roughnessVariation * 2);
+ let color: [number, number, number];
+ if (colorGradient) {
+ // Evidence-derived spatial gradient (Plan 1.3 Workstream C) takes priority
+ // over the noise-based palette blend below — it is a measured trend, not a guess.
+ color = sampleColorGradient(colorGradient, u, v);
+ } else {
+ const paletteValue = clamp01(
+ 0.5 + (colorNoise - 0.5) * colorAmplitude * 2 + (height - 0.5) * heightCorrelation
+ );
+ color = mixPalette(colors, paletteValue);
+ }
+ writePixel(images.albedo.data, index * 4, color[0], color[1], color[2]);
+ }
+ }
+ const normalStrength = Math.max(0.05, readLayerNumber(spec.normal, ['strength', 'amplitude'], 0.35));
+ const aoStrength = clamp01(readLayerNumber(spec.ambientOcclusion, ['cavityStrength', 'strength'], 0.35));
+ for (let y = 0; y < size; y += 1) {
+ const up = ((y - 1 + size) % size) * size;
+ const down = ((y + 1) % size) * size;
+ for (let x = 0; x < size; x += 1) {
+ const left = (x - 1 + size) % size;
+ const right = (x + 1) % size;
+ const index = y * size + x;
+ const center = heightField[index];
+ const dx = (heightField[y * size + right] - heightField[y * size + left]) * normalStrength * 6;
+ const dy = (heightField[down + x] - heightField[up + x]) * normalStrength * 6;
+ const inverseLength = 1 / Math.sqrt(dx * dx + dy * dy + 1);
+ const normalX = -dx * inverseLength;
+ const normalY = -dy * inverseLength;
+ const normalZ = inverseLength;
+ const neighborAverage = (
+ heightField[y * size + left] + heightField[y * size + right]
+ + heightField[up + x] + heightField[down + x]
+ ) * 0.25;
+ const cavity = Math.max(0, neighborAverage - center);
+ const ao = clamp01(1 - aoStrength * (cavity * 12 + (1 - center) * 0.16));
+ const offset = index * 4;
+ const heightByte = center * 255;
+ const roughnessByte = roughnessField[index] * 255;
+ writePixel(images.height.data, offset, heightByte, heightByte, heightByte);
+ writePixel(images.roughness.data, offset, roughnessByte, roughnessByte, roughnessByte);
+ writePixel(
+ images.normal.data, offset,
+ (normalX * 0.5 + 0.5) * 255,
+ (normalY * 0.5 + 0.5) * 255,
+ (normalZ * 0.5 + 0.5) * 255,
+ );
+ writePixel(images.ao.data, offset, ao * 255, ao * 255, ao * 255);
+ }
+ }
+ contexts.albedo.putImageData(images.albedo, 0, 0);
+ contexts.roughness.putImageData(images.roughness, 0, 0);
+ contexts.height.putImageData(images.height, 0, 0);
+ contexts.normal.putImageData(images.normal, 0, 0);
+ contexts.ao.putImageData(images.ao, 0, 0);
+ return {
+ albedo: createMapTexture(canvases.albedo, THREE.SRGBColorSpace, spec, options),
+ roughness: createMapTexture(canvases.roughness, THREE.NoColorSpace, spec, options),
+ height: createMapTexture(canvases.height, THREE.NoColorSpace, spec, options),
+ normal: createMapTexture(canvases.normal, THREE.NoColorSpace, spec, options),
+ ao: createMapTexture(canvases.ao, THREE.NoColorSpace, spec, options),
+ source: 'procedural',
+ };
+}
+
+function createSculptMaterial(id: string, spec: SculptMaterialSpec, options: ProceduralModelOptions, denseComponent = false): THREE.MeshPhysicalMaterial {
+ // A material that declares -- with evidence -- that its subject carries no texture
+ // detail gets NO texture set. Synthesising one anyway is not a harmless default: the
+ // branch below then forces color to white and roughness to 1 and reads both from the
+ // generated maps, so the authored albedo and the reference-derived roughness are both
+ // discarded, and the model gains mottling the reference does not have. Measured on the
+ // tuxedo cat, whose black fur rendered as speckled grey-and-white from a palette that
+ // only ever described two flat regions.
+ const textureless = (spec.textureless as { declared?: boolean } | undefined)?.declared === true;
+ const textures = textureless
+ ? null
+ : makeReferenceTextureSet(spec, options) ?? makeProceduralTextureSet(id, spec, options);
+ const material = new THREE.MeshPhysicalMaterial({
+ color: textures ? 0xffffff : clampedAlbedoColor(spec),
+ roughness: textures ? 1 : clamp01(readLayerNumber(spec.roughness, ['base'], 0.76)),
+ metalness: clampPbrMetalness(readLayerNumber(spec.metalness, ['base'], 0.0)),
+ clearcoat: clamp01(readLayerNumber(spec.clearcoat, ['base', 'amount'], 0)),
+ clearcoatRoughness: clamp01(readLayerNumber(spec.clearcoatRoughness, ['base'], 0.25)),
+ transmission: clamp01(readLayerNumber(spec.transmission, ['base', 'amount'], 0)),
+ ior: clampPbrIor(readLayerNumber(spec.ior, ['base', 'value'], 1.5)),
+ thickness: Math.max(0, readLayerNumber(spec.thickness, ['base', 'amount'], 0)),
+ attenuationDistance: Math.max(0.001, readLayerNumber(spec.attenuationDistance, ['base', 'value'], Infinity)),
+ attenuationColor: new THREE.Color(typeof spec.attenuationColor === 'string' ? spec.attenuationColor : '#ffffff'),
+ sheen: clamp01(readLayerNumber(spec.sheen, ['base', 'amount'], 0)),
+ sheenColor: new THREE.Color(typeof spec.sheenColor === 'string' ? spec.sheenColor : '#ffffff'),
+ sheenRoughness: clamp01(readLayerNumber(spec.sheenRoughness, ['base'], 1.0)),
+ iridescence: clamp01(readLayerNumber(spec.iridescence, ['base', 'amount'], 0)),
+ iridescenceIOR: clampPbrIor(readLayerNumber(spec.iridescenceIOR, ['base', 'value'], 1.3)),
+ anisotropy: clamp01(readLayerNumber(spec.anisotropy, ['base', 'amount'], 0)),
+ anisotropyRotation: readLayerNumber(spec.anisotropy, ['rotation'], 0),
+ specularIntensity: clampPbrF0(readLayerNumber(spec.specularF0 ?? spec.f0 ?? spec.specularIntensity, ['base', 'value'], 1.0)),
+ specularColor: new THREE.Color(typeof spec.specularColor === 'string' ? spec.specularColor : '#ffffff'),
+ emissive: new THREE.Color(typeof spec.emissive === 'string' ? spec.emissive : '#000000'),
+ emissiveIntensity: Math.max(0, readLayerNumber(spec.emissiveIntensity, ['base'], 1.0)),
+ opacity: clamp01(readLayerNumber(spec.opacity, ['base'], 1)),
+ transparent: readLayerNumber(spec.transmission, ['base', 'amount'], 0) > 0 || readLayerNumber(spec.opacity, ['base'], 1) < 1,
+ alphaTest: Math.max(0, readLayerNumber(spec.alpha, ['cutoff', 'alphaTest'], 0)),
+ wireframe: options.wireframe ?? false,
+ side: spec.doubleSided === true ? THREE.DoubleSide : THREE.FrontSide,
+ flatShading: spec.flatShading === true,
+ });
+ if (textures) {
+ material.map = textures.albedo;
+ material.roughnessMap = textures.roughness;
+ material.normalMap = textures.normal;
+ material.normalScale.setScalar(Math.max(0.05, readLayerNumber(spec.normal, ['strength', 'amplitude'], 0.35)));
+ material.aoMap = textures.ao;
+ material.aoMap.channel = 0;
+ material.aoMapIntensity = readLayerNumber(spec.ambientOcclusion, ['cavityStrength', 'strength'], 0.35);
+ const denseMesh = denseComponent || spec.denseMesh === true || spec.geometryDensity === 'dense' || spec.topologyClass === 'dense';
+ const bumpScale = Math.max(0, readLayerNumber(spec.bump, ['amplitude', 'strength'], 0));
+ const effectiveBumpScale = denseMesh ? Math.max(0.05, bumpScale) : bumpScale;
+ if (effectiveBumpScale > 0) {
+ material.bumpMap = textures.height;
+ material.bumpScale = effectiveBumpScale;
+ }
+ const displacementScale = Math.max(0, readLayerNumber(spec.displacement, ['amplitude', 'strength'], 0));
+ const effectiveDisplacementScale = denseMesh ? Math.max(0.005, displacementScale) : displacementScale;
+ if (effectiveDisplacementScale > 0) {
+ material.displacementMap = textures.height;
+ material.displacementScale = effectiveDisplacementScale;
+ material.displacementBias = -effectiveDisplacementScale * 0.5;
+ }
+ }
+ material.envMapIntensity = readLayerNumber(spec, ['envMapIntensity'], 0.8);
+ material.userData.sculptMaterial = spec;
+ material.userData.proceduralMapsIndependent = true;
+ material.userData.pbrConstraints = { albedoRange: [30, 240], binaryMetalness: true, f0Range: [0.02, 1], iorRange: [1, 2.5] };
+ material.userData.pbrTextureSource = textures?.source ?? 'flat-fallback';
+ material.userData.referencePbr = spec.referencePbr ?? null;
+ material.userData.referenceMaterialId = spec.referenceMaterialId ?? spec.materialReference?.profileId ?? null;
+ material.userData.materialEvidence = spec.materialEvidence ?? null;
+ material.userData.validationViews = spec.materialReference?.validationViews ?? [];
+ material.needsUpdate = true;
+ return material;
+}
+
+type AttachmentEndpoint = {
+ start: THREE.Vector3;
+ midpoint: THREE.Vector3;
+ quaternion: THREE.Quaternion;
+ length: number;
+ baseRadius: number;
+ endRadius: number;
+};
+
+function readVector3(value: unknown, fallback: [number, number, number]): THREE.Vector3 {
+ if (Array.isArray(value) && value.length === 3 && value.every((item) => typeof item === 'number')) {
+ return new THREE.Vector3(value[0], value[1], value[2]);
+ }
+ return new THREE.Vector3(fallback[0], fallback[1], fallback[2]);
+}
+
+function readNumber(value: unknown, fallback: number): number {
+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
+}
+
+function makeAttachmentEndpoint(attachment: unknown): AttachmentEndpoint | null {
+ if (!attachment || typeof attachment !== 'object') return null;
+ const record = attachment as Record<string, unknown>;
+ const start = readVector3(record.localStart, [0, 0, 0]);
+ const end = readVector3(record.localEnd, [0, 1, 0]);
+ const delta = end.clone().sub(start);
+ const length = delta.length();
+ if (length <= 0.0001) return null;
+ const direction = delta.clone().normalize();
+ const quaternion = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 1, 0), direction);
+ const baseRadius = Math.max(0.005, readNumber(record.baseRadius, 0.06));
+ const endRadius = Math.max(0.003, readNumber(record.endRadius, baseRadius * 0.55));
+ return {
+ start,
+ midpoint: delta.multiplyScalar(0.5),
+ quaternion,
+ length,
+ baseRadius,
+ endRadius,
+ };
+}
+
+// Generated from ObjectSculptSpec target: TradeIt Hard Case
+// Sculpt build pass: blockout
+// This factory is intentionally pass-gated. Finish browser screenshot review before unlocking deeper passes.
+export function createTradeItHardCaseModel(options: ProceduralModelOptions = {}): THREE.Group {
+ const root = new THREE.Group();
+ root.name = "TradeIt Hard Case";
+ root.userData.reconstructionEvidence = {"itemFamily": null, "subtype": null, "componentAdapter": null, "route": null, "exactnessTier": null, "referenceCamera": {"solved": false, "fovDegrees": 35.0, "aspect": 1.0, "orientation": {"yaw": 28.0, "pitch": 12.0, "roll": 0.0}, "positionHint": [1.1, 0.55, 1.8], "note": "3/4 front-left studio framing, not solved via solve_camera_pose.py (flat print decal route does not require pixel-exact projection); used only as a review-render hint."}, "approximationNotes": []};
+ root.userData.materialPipeline = {};
+ root.userData.materialReferenceRegistry = null;
+
+ const materialMap: Record<string, THREE.Material> = {};
+ materialMap["shellMatte"] = createSculptMaterial(
+ "shellMatte",
+ {"id": "shellMatte", "name": "Rotomolded shell (matte composite)", "type": "standard", "shaderModel": "MeshStandardMaterial / PBR approximation", "baseColor": "#212327", "color": "#212327", "albedo": {"dominant": "#212327", "secondary": ["#242629", "#181a1c"], "samplingNotes": "Estimated by eye from a 400x492px studio photo with light falloff toward the silhouette edge; not spectrophotometric. Near-black, slightly warm dark gray, matte -- no crisp specular hotspot on flat panels."}, "colorVariation": {"palette": ["#212327", "#242629", "#181a1c"], "pattern": "uniform", "amplitude": 0.06, "heightCorrelation": 0.1}, "textureResolution": 1024, "textureProjection": {"mode": "uv", "repeat": [1.0, 1.0], "anisotropy": 8, "texelDensityIntent": "Preserve stable world-scale detail; decal graphics use a dedicated canvas-baked UV island, not tiled repeat."}, "surfaceFrequencyBands": [{"id": "macro", "frequency": 1.5, "amplitude": 0.1, "role": "broad color/value read"}, {"id": "meso", "frequency": 8.0, "amplitude": 0.05, "role": "fine matte grain / brushing"}, {"id": "micro", "frequency": 32.0, "amplitude": 0.02, "role": "highlight breakup under grazing light"}], "roughness": {"base": 0.62, "variation": 0.08, "map": "independent-procedural-field", "localResponse": "slightly lower roughness on rounded edges/ribs than on flat panels"}, "metalness": {"base": 0.0, "variation": 0.03}, "normal": {"pattern": "derived-from-independent-height-field", "strength": 0.15, "scale": 20.0, "space": "tangent"}, "bump": {"pattern": "fine-matte-grain", "amplitude": 0.01, "scale": 4.0}, "displacement": {"pattern": "none", "amplitude": 0.0, "scale": 1.0, "silhouetteAffects": false}, "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.3, "notes": "Darken the lid/body seam, latch mounts, hasp loop, and handle pocket."}, "wear": {"edgeWear": 0.05, "scratches": [], "chips": []}, "dirt": {"amount": 0.0, "cavityBias": 0.0, "color": "#2F2A22"}, "localOverrides": [{"id": "tradeitLogoIcon", "description": "Circular blue double-arrow/handshake icon baked into a canvas decal texture, flat print (#2e57e0 fill, white #f2f2f2 linework), no separate geometry/relief.", "confidence": 0.75}, {"id": "tradeitWordmark", "description": "White 'TRADEIT' wordmark below the icon, same canvas decal, flat print, no relief.", "confidence": 0.75}, {"id": "diagonalChevron", "description": "Wide diagonal blue (#2e57e0) wedge/chevron baked into the same canvas decal, widening from upper-right toward lower-left across the front-right third of the shell.", "confidence": 0.7}, {"id": "frontFacetLines", "description": "Faint vertical panel/facet lines on the lower front face — low-medium confidence, could be render/lighting artifact rather than molded relief; represented as a subtle normal-map micro-band, not geometry, so it can be safely wrong.", "confidence": 0.35}], "shaderNotes": ["Approximate PBR inference from a single low-resolution studio photo, not extracted measurement; confidence flagged per-field in preSpecAssessment.unknownsToResolveBeforeImplementation."]},
+ options
+ );
+ materialMap["hardwareSatin"] = createSculptMaterial(
+ "hardwareSatin",
+ {"id": "hardwareSatin", "name": "Latch/rivet/loop hardware (satin metal)", "type": "physical", "shaderModel": "MeshStandardMaterial / PBR approximation", "baseColor": "#8c8e92", "color": "#8c8e92", "albedo": {"dominant": "#8c8e92", "secondary": ["#a2a4a8", "#5a5c60"], "samplingNotes": "Estimated by eye from a 400x492px studio photo with light falloff toward the silhouette edge; not spectrophotometric. Latch wire bail, rivet/screw heads, hasp eyeloop -- brighter, higher-specular than the shell."}, "colorVariation": {"palette": ["#8c8e92", "#a2a4a8", "#5a5c60"], "pattern": "mottled", "amplitude": 0.06, "heightCorrelation": 0.1}, "textureResolution": 1024, "textureProjection": {"mode": "uv", "repeat": [1.0, 1.0], "anisotropy": 8, "texelDensityIntent": "Preserve stable world-scale detail; decal graphics use a dedicated canvas-baked UV island, not tiled repeat."}, "surfaceFrequencyBands": [{"id": "macro", "frequency": 1.5, "amplitude": 0.1, "role": "broad color/value read"}, {"id": "meso", "frequency": 8.0, "amplitude": 0.05, "role": "fine matte grain / brushing"}, {"id": "micro", "frequency": 32.0, "amplitude": 0.02, "role": "highlight breakup under grazing light"}], "roughness": {"base": 0.35, "variation": 0.08, "map": "independent-procedural-field", "localResponse": "slightly lower roughness on rounded edges/ribs than on flat panels"}, "metalness": {"base": 0.78, "variation": 0.03}, "normal": {"pattern": "derived-from-independent-height-field", "strength": 0.3, "scale": 20.0, "space": "tangent"}, "bump": {"pattern": "brushed-linear", "amplitude": 0.01, "scale": 4.0}, "displacement": {"pattern": "none", "amplitude": 0.0, "scale": 1.0, "silhouetteAffects": false}, "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.3, "notes": "Darken the lid/body seam, latch mounts, hasp loop, and handle pocket."}, "wear": {"edgeWear": 0.05, "scratches": [], "chips": []}, "dirt": {"amount": 0.0, "cavityBias": 0.0, "color": "#2F2A22"}, "localOverrides": [], "shaderNotes": ["Approximate PBR inference from a single low-resolution studio photo, not extracted measurement; confidence flagged per-field in preSpecAssessment.unknownsToResolveBeforeImplementation."]},
+ options
+ );
+ materialMap["brassPlated"] = createSculptMaterial(
+ "brassPlated",
+ {"id": "brassPlated", "name": "Padlock body (plated brass)", "type": "physical", "shaderModel": "MeshStandardMaterial / PBR approximation", "baseColor": "#c9a227", "color": "#c9a227", "albedo": {"dominant": "#c9a227", "secondary": ["#d8b646", "#8f701a"], "samplingNotes": "Estimated by eye from a 400x492px studio photo with light falloff toward the silhouette edge; not spectrophotometric. Warm gold-yellow plated metal, small in frame (~28x40px), color read solid, roughness estimated."}, "colorVariation": {"palette": ["#c9a227", "#d8b646", "#8f701a"], "pattern": "mottled", "amplitude": 0.06, "heightCorrelation": 0.1}, "textureResolution": 1024, "textureProjection": {"mode": "uv", "repeat": [1.0, 1.0], "anisotropy": 8, "texelDensityIntent": "Preserve stable world-scale detail; decal graphics use a dedicated canvas-baked UV island, not tiled repeat."}, "surfaceFrequencyBands": [{"id": "macro", "frequency": 1.5, "amplitude": 0.1, "role": "broad color/value read"}, {"id": "meso", "frequency": 8.0, "amplitude": 0.05, "role": "fine matte grain / brushing"}, {"id": "micro", "frequency": 32.0, "amplitude": 0.02, "role": "highlight breakup under grazing light"}], "roughness": {"base": 0.3, "variation": 0.08, "map": "independent-procedural-field", "localResponse": "slightly lower roughness on rounded edges/ribs than on flat panels"}, "metalness": {"base": 0.75, "variation": 0.03}, "normal": {"pattern": "derived-from-independent-height-field", "strength": 0.3, "scale": 20.0, "space": "tangent"}, "bump": {"pattern": "brushed-linear", "amplitude": 0.01, "scale": 4.0}, "displacement": {"pattern": "none", "amplitude": 0.0, "scale": 1.0, "silhouetteAffects": false}, "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.3, "notes": "Darken the lid/body seam, latch mounts, hasp loop, and handle pocket."}, "wear": {"edgeWear": 0.05, "scratches": [], "chips": []}, "dirt": {"amount": 0.0, "cavityBias": 0.0, "color": "#2F2A22"}, "localOverrides": [], "shaderNotes": ["Approximate PBR inference from a single low-resolution studio photo, not extracted measurement; confidence flagged per-field in preSpecAssessment.unknownsToResolveBeforeImplementation."]},
+ options
+ );
+ materialMap["steelSatin"] = createSculptMaterial(
+ "steelSatin",
+ {"id": "steelSatin", "name": "Padlock shackle + latch bail (satin steel)", "type": "physical", "shaderModel": "MeshStandardMaterial / PBR approximation", "baseColor": "#9a9ca2", "color": "#9a9ca2", "albedo": {"dominant": "#9a9ca2", "secondary": ["#b4b6bc", "#6a6c72"], "samplingNotes": "Estimated by eye from a 400x492px studio photo with light falloff toward the silhouette edge; not spectrophotometric. Cooler gray than the brass body; shared finish class with hardwareSatin but kept distinct for the shackle's slightly higher metalness/lower roughness observed highlight falloff."}, "colorVariation": {"palette": ["#9a9ca2", "#b4b6bc", "#6a6c72"], "pattern": "mottled", "amplitude": 0.06, "heightCorrelation": 0.1}, "textureResolution": 1024, "textureProjection": {"mode": "uv", "repeat": [1.0, 1.0], "anisotropy": 8, "texelDensityIntent": "Preserve stable world-scale detail; decal graphics use a dedicated canvas-baked UV island, not tiled repeat."}, "surfaceFrequencyBands": [{"id": "macro", "frequency": 1.5, "amplitude": 0.1, "role": "broad color/value read"}, {"id": "meso", "frequency": 8.0, "amplitude": 0.05, "role": "fine matte grain / brushing"}, {"id": "micro", "frequency": 32.0, "amplitude": 0.02, "role": "highlight breakup under grazing light"}], "roughness": {"base": 0.3, "variation": 0.08, "map": "independent-procedural-field", "localResponse": "slightly lower roughness on rounded edges/ribs than on flat panels"}, "metalness": {"base": 0.85, "variation": 0.03}, "normal": {"pattern": "derived-from-independent-height-field", "strength": 0.3, "scale": 20.0, "space": "tangent"}, "bump": {"pattern": "brushed-linear", "amplitude": 0.01, "scale": 4.0}, "displacement": {"pattern": "none", "amplitude": 0.0, "scale": 1.0, "silhouetteAffects": false}, "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.3, "notes": "Darken the lid/body seam, latch mounts, hasp loop, and handle pocket."}, "wear": {"edgeWear": 0.05, "scratches": [], "chips": []}, "dirt": {"amount": 0.0, "cavityBias": 0.0, "color": "#2F2A22"}, "localOverrides": [], "shaderNotes": ["Approximate PBR inference from a single low-resolution studio photo, not extracted measurement; confidence flagged per-field in preSpecAssessment.unknownsToResolveBeforeImplementation."]},
+ options
+ );
+
+ const nodes: Record<string, THREE.Object3D> = { root };
+ const meshes: Record<string, THREE.Mesh> = {};
+ const sockets: Record<string, THREE.Object3D> = {};
+ const colliders: Record<string, unknown> = {};
+ const destructionGroups: Record<string, THREE.Object3D[]> = {};
+
+ const endpoint_root_0 = makeAttachmentEndpoint(null);
+ const node_root_0 = new THREE.Group();
+ node_root_0.name = "Body shell__pivot";
+ node_root_0.scale.set(1, 1, 1);
+ if (endpoint_root_0) {
+ node_root_0.position.copy(endpoint_root_0.start);
+ node_root_0.rotation.set(0.0, 0.0, 0.0);
+ } else {
+ node_root_0.position.set(0.0, 0.0, 0.0);
+ node_root_0.rotation.set(0.0, 0.0, 0.0);
+ }
+ node_root_0.userData.sculptComponent = {"id": "root", "name": "Body shell", "level": "macro", "role": "body", "importance": 1.0, "confidence": 0.75, "primitive": "box", "topologyClass": "assembled-solid", "topologyRationale": "Rigid molded lower shell assembled from a rounded box blockout with a taper deform; not an organic/continuous surface.", "geometryDescriptor": {"topologyIntent": "tapered rounded box, full width at the top seam narrowing toward the base", "edgeTreatment": {"type": "rounded", "bevelRadius": 0.045, "segments": 4}, "deformationStack": [{"type": "taper", "axis": "y", "factor": 0.86, "notes": "body narrows toward the base (rotomold draft angle); silhouette-affecting, estimated ~4-6deg/side"}], "uvStrategy": "generated procedural coordinates", "normalStrategy": "vertex normals from generated geometry"}, "parent": null, "attachment": null, "dimensions": {"width": 1.0, "height": 0.46, "depth": 0.78, "units": "relative", "confidence": 0.75}, "transform": {"position": [0, 0, 0], "rotation": [0, 0, 0], "scale": [1, 1, 1]}, "material": "shellMatte", "materialLayers": ["shellMatte"], "colorMaterialRecipe": {"dominantAlbedo": "rgba(33, 35, 39, 1.0)", "secondaryAlbedo": "rgba(24, 26, 28, 1.0)", "materialClass": "plastic", "materialClassConfidence": 0.6, "evidence": ["closed-front-3q"], "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."}, "actionProfile": {"animationRole": "static", "pivot": {"mode": "explicit", "localPosition": [0, 0, 0], "axis": [0, 1, 0], "confidence": 0.6}, "transformChannels": {"translate": true, "rotate": true, "scale": false, "bend": false, "twist": false, "detach": false, "visibility": true, "materialState": false}, "sockets": [], "collider": {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1], "isTrigger": false, "notes": "Coarse proxy; refine after first browser render."}, "constraints": [], "destruction": {"breakable": false, "breakImpulse": 0.0, "fractureGroup": "", "debrisMaterial": "", "seamRefs": [], "detachableFragments": []}}, "localFeatures": [{"id": "rounded-bevel-edges", "description": "Continuous rounded fillet on all 12 body/lid edges, molded in.", "confidence": 0.8, "level": "macro", "evidence": ["closed-front-3q"]}, {"id": "body-taper", "description": "Body narrows from lid seam to base.", "confidence": 0.7, "level": "macro", "evidence": ["closed-front-3q"]}, {"id": "front-facet-lines", "description": "Faint vertical panel lines, low-medium confidence -- see material localOverrides.frontFacetLines.", "confidence": 0.35, "level": "micro", "evidence": ["closed-front-3q"]}], "evidenceRefs": ["closed-front-3q"]};
+ node_root_0.userData.actionProfile = {"animationRole": "static", "pivot": {"mode": "explicit", "localPosition": [0, 0, 0], "axis": [0, 1, 0], "confidence": 0.6}, "transformChannels": {"translate": true, "rotate": true, "scale": false, "bend": false, "twist": false, "detach": false, "visibility": true, "materialState": false}, "sockets": [], "collider": {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1], "isTrigger": false, "notes": "Coarse proxy; refine after first browser render."}, "constraints": [], "destruction": {"breakable": false, "breakImpulse": 0.0, "fractureGroup": "", "debrisMaterial": "", "seamRefs": [], "detachableFragments": []}};
+ (nodes["root"] ?? root).add(node_root_0);
+ nodes["root"] = node_root_0;
+ const mesh_root_0Geometry = endpoint_root_0
+ ? new THREE.CylinderGeometry(endpoint_root_0.endRadius, endpoint_root_0.baseRadius, endpoint_root_0.length, 32, 12)
+ : new THREE.BoxGeometry(1, 1, 1, 12, 12, 12);
+ if (!endpoint_root_0) {
+ mesh_root_0Geometry.scale(1.0, 1.0, 1.0);
+ }
+ const mesh_root_0 = new THREE.Mesh(
+ mesh_root_0Geometry,
+ materialMap["shellMatte"] ?? new THREE.MeshStandardMaterial({ color: 0x888888 })
+ );
+ mesh_root_0.name = "Body shell";
+ if (endpoint_root_0) {
+ mesh_root_0.position.copy(endpoint_root_0.midpoint);
+ mesh_root_0.quaternion.copy(endpoint_root_0.quaternion);
+ }
+ mesh_root_0.castShadow = options.castShadow ?? true;
+ mesh_root_0.receiveShadow = options.receiveShadow ?? true;
+ mesh_root_0.userData.sculptComponent = {"id": "root", "name": "Body shell", "level": "macro", "role": "body", "importance": 1.0, "confidence": 0.75, "primitive": "box", "topologyClass": "assembled-solid", "topologyRationale": "Rigid molded lower shell assembled from a rounded box blockout with a taper deform; not an organic/continuous surface.", "geometryDescriptor": {"topologyIntent": "tapered rounded box, full width at the top seam narrowing toward the base", "edgeTreatment": {"type": "rounded", "bevelRadius": 0.045, "segments": 4}, "deformationStack": [{"type": "taper", "axis": "y", "factor": 0.86, "notes": "body narrows toward the base (rotomold draft angle); silhouette-affecting, estimated ~4-6deg/side"}], "uvStrategy": "generated procedural coordinates", "normalStrategy": "vertex normals from generated geometry"}, "parent": null, "attachment": null, "dimensions": {"width": 1.0, "height": 0.46, "depth": 0.78, "units": "relative", "confidence": 0.75}, "transform": {"position": [0, 0, 0], "rotation": [0, 0, 0], "scale": [1, 1, 1]}, "material": "shellMatte", "materialLayers": ["shellMatte"], "colorMaterialRecipe": {"dominantAlbedo": "rgba(33, 35, 39, 1.0)", "secondaryAlbedo": "rgba(24, 26, 28, 1.0)", "materialClass": "plastic", "materialClassConfidence": 0.6, "evidence": ["closed-front-3q"], "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."}, "actionProfile": {"animationRole": "static", "pivot": {"mode": "explicit", "localPosition": [0, 0, 0], "axis": [0, 1, 0], "confidence": 0.6}, "transformChannels": {"translate": true, "rotate": true, "scale": false, "bend": false, "twist": false, "detach": false, "visibility": true, "materialState": false}, "sockets": [], "collider": {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1], "isTrigger": false, "notes": "Coarse proxy; refine after first browser render."}, "constraints": [], "destruction": {"breakable": false, "breakImpulse": 0.0, "fractureGroup": "", "debrisMaterial": "", "seamRefs": [], "detachableFragments": []}}, "localFeatures": [{"id": "rounded-bevel-edges", "description": "Continuous rounded fillet on all 12 body/lid edges, molded in.", "confidence": 0.8, "level": "macro", "evidence": ["closed-front-3q"]}, {"id": "body-taper", "description": "Body narrows from lid seam to base.", "confidence": 0.7, "level": "macro", "evidence": ["closed-front-3q"]}, {"id": "front-facet-lines", "description": "Faint vertical panel lines, low-medium confidence -- see material localOverrides.frontFacetLines.", "confidence": 0.35, "level": "micro", "evidence": ["closed-front-3q"]}], "evidenceRefs": ["closed-front-3q"]};
+ node_root_0.add(mesh_root_0);
+ meshes["root"] = mesh_root_0;
+ colliders["root"] = {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1], "isTrigger": false, "notes": "Coarse proxy; refine after first browser render."};
+
+ const endpoint_lid_1 = makeAttachmentEndpoint(null);
+ const node_lid_1 = new THREE.Group();
+ node_lid_1.name = "Lid__pivot";
+ node_lid_1.scale.set(1, 1, 1);
+ if (endpoint_lid_1) {
+ node_lid_1.position.copy(endpoint_lid_1.start);
+ node_lid_1.rotation.set(0.0, 0.0, 0.0);
+ } else {
+ node_lid_1.position.set(0.0, 0.31, 0.0);
+ node_lid_1.rotation.set(0.0, 0.0, 0.0);
+ }
+ node_lid_1.userData.sculptComponent = {"id": "lid", "name": "Lid", "level": "macro", "role": "hinge-lid", "importance": 0.95, "confidence": 0.7, "primitive": "box", "topologyClass": "assembled-solid", "topologyRationale": "Rigid molded upper shell, same construction family as the body, hinged as a rigid rotation not a deforming shell.", "geometryDescriptor": {"topologyIntent": "rounded box slab, front-bottom lip step at the seam", "edgeTreatment": {"type": "rounded", "bevelRadius": 0.04, "segments": 4}, "deformationStack": [], "uvStrategy": "generated procedural coordinates", "normalStrategy": "vertex normals from generated geometry"}, "parent": "root", "attachment": {"parentId": "root", "parentSocket": "lidHingeSocket", "localStart": [0, 0.23, -0.39], "localEnd": [0, 0.23, 0.39], "contactType": "pivot-hinge", "embedDepth": 0.01, "gapTolerance": 0.004, "evidenceRefs": ["closed-front-3q"]}, "dimensions": {"width": 1.02, "height": 0.16, "depth": 0.7956000000000001, "units": "relative", "confidence": 0.7}, "transform": {"position": [0, 0.31, 0], "rotation": [0, 0, 0], "scale": [1, 1, 1]}, "material": "shellMatte", "materialLayers": ["shellMatte"], "colorMaterialRecipe": {"dominantAlbedo": "rgba(33, 35, 39, 1.0)", "secondaryAlbedo": "rgba(24, 26, 28, 1.0)", "materialClass": "plastic", "materialClassConfidence": 0.6, "evidence": ["closed-front-3q"], "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."}, "actionProfile": {"animationRole": "hinge", "pivot": {"mode": "explicit", "localPosition": [0, 0.23, -0.39], "axis": [1, 0, 0], "confidence": 0.6}, "transformChannels": {"translate": false, "rotate": true, "scale": false, "bend": false, "twist": false, "detach": false, "visibility": true, "materialState": false}, "sockets": [], "collider": {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1], "isTrigger": false, "notes": "Coarse proxy; refine after first browser render."}, "constraints": [], "destruction": {"breakable": false, "breakImpulse": 0.0, "fractureGroup": "", "debrisMaterial": "", "seamRefs": [], "detachableFragments": []}}, "localFeatures": [{"id": "lid-front-lip-step", "description": "Shallow step in the shell where the lid meets the body seam.", "confidence": 0.6, "level": "meso", "evidence": ["closed-front-3q"]}], "evidenceRefs": ["closed-front-3q", "open-mechanism"]};
+ node_lid_1.userData.actionProfile = {"animationRole": "hinge", "pivot": {"mode": "explicit", "localPosition": [0, 0.23, -0.39], "axis": [1, 0, 0], "confidence": 0.6}, "transformChannels": {"translate": false, "rotate": true, "scale": false, "bend": false, "twist": false, "detach": false, "visibility": true, "materialState": false}, "sockets": [], "collider": {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1], "isTrigger": false, "notes": "Coarse proxy; refine after first browser render."}, "constraints": [], "destruction": {"breakable": false, "breakImpulse": 0.0, "fractureGroup": "", "debrisMaterial": "", "seamRefs": [], "detachableFragments": []}};
+ (nodes["root"] ?? root).add(node_lid_1);
+ nodes["lid"] = node_lid_1;
+ const mesh_lid_1Geometry = endpoint_lid_1
+ ? new THREE.CylinderGeometry(endpoint_lid_1.endRadius, endpoint_lid_1.baseRadius, endpoint_lid_1.length, 32, 12)
+ : new THREE.BoxGeometry(1, 1, 1, 12, 12, 12);
+ if (!endpoint_lid_1) {
+ mesh_lid_1Geometry.scale(1.0, 1.0, 1.0);
+ }
+ const mesh_lid_1 = new THREE.Mesh(
+ mesh_lid_1Geometry,
+ materialMap["shellMatte"] ?? new THREE.MeshStandardMaterial({ color: 0x888888 })
+ );
+ mesh_lid_1.name = "Lid";
+ if (endpoint_lid_1) {
+ mesh_lid_1.position.copy(endpoint_lid_1.midpoint);
+ mesh_lid_1.quaternion.copy(endpoint_lid_1.quaternion);
+ }
+ mesh_lid_1.castShadow = options.castShadow ?? true;
+ mesh_lid_1.receiveShadow = options.receiveShadow ?? true;
+ mesh_lid_1.userData.sculptComponent = {"id": "lid", "name": "Lid", "level": "macro", "role": "hinge-lid", "importance": 0.95, "confidence": 0.7, "primitive": "box", "topologyClass": "assembled-solid", "topologyRationale": "Rigid molded upper shell, same construction family as the body, hinged as a rigid rotation not a deforming shell.", "geometryDescriptor": {"topologyIntent": "rounded box slab, front-bottom lip step at the seam", "edgeTreatment": {"type": "rounded", "bevelRadius": 0.04, "segments": 4}, "deformationStack": [], "uvStrategy": "generated procedural coordinates", "normalStrategy": "vertex normals from generated geometry"}, "parent": "root", "attachment": {"parentId": "root", "parentSocket": "lidHingeSocket", "localStart": [0, 0.23, -0.39], "localEnd": [0, 0.23, 0.39], "contactType": "pivot-hinge", "embedDepth": 0.01, "gapTolerance": 0.004, "evidenceRefs": ["closed-front-3q"]}, "dimensions": {"width": 1.02, "height": 0.16, "depth": 0.7956000000000001, "units": "relative", "confidence": 0.7}, "transform": {"position": [0, 0.31, 0], "rotation": [0, 0, 0], "scale": [1, 1, 1]}, "material": "shellMatte", "materialLayers": ["shellMatte"], "colorMaterialRecipe": {"dominantAlbedo": "rgba(33, 35, 39, 1.0)", "secondaryAlbedo": "rgba(24, 26, 28, 1.0)", "materialClass": "plastic", "materialClassConfidence": 0.6, "evidence": ["closed-front-3q"], "samplingNotes": "Near-black warm dark gray read from mid-tone shell pixels, discounting studio falloff toward pure black at the silhouette edge."}, "actionProfile": {"animationRole": "hinge", "pivot": {"mode": "explicit", "localPosition": [0, 0.23, -0.39], "axis": [1, 0, 0], "confidence": 0.6}, "transformChannels": {"translate": false, "rotate": true, "scale": false, "bend": false, "twist": false, "detach": false, "visibility": true, "materialState": false}, "sockets": [], "collider": {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1], "isTrigger": false, "notes": "Coarse proxy; refine after first browser render."}, "constraints": [], "destruction": {"breakable": false, "breakImpulse": 0.0, "fractureGroup": "", "debrisMaterial": "", "seamRefs": [], "detachableFragments": []}}, "localFeatures": [{"id": "lid-front-lip-step", "description": "Shallow step in the shell where the lid meets the body seam.", "confidence": 0.6, "level": "meso", "evidence": ["closed-front-3q"]}], "evidenceRefs": ["closed-front-3q", "open-mechanism"]};
+ node_lid_1.add(mesh_lid_1);
+ meshes["lid"] = mesh_lid_1;
+ colliders["lid"] = {"type": "box", "offset": [0, 0, 0], "scale": [1, 1, 1], "isTrigger": false, "notes": "Coarse proxy; refine after first browser render."};
+
+ root.userData.sculptRuntime = { nodes, meshes, sockets, colliders, destructionGroups } satisfies ProceduralModelRuntime;
+ root.userData.lookDevTargets = {"qualityPriority": "reference-fidelity", "materialPass": {"albedoPaletteRequired": true, "roughnessVariationRequired": true, "normalOrBumpRequired": true, "localOverridesRequired": true, "minimumTextureResolution": 1024, "preferredTextureResolution": 2048, "independentMapChannels": ["albedo", "roughness", "height", "normal", "ambient-occlusion"], "requiredSurfaceFrequencyBands": ["macro", "meso", "micro"], "geometryReliefRequiredWhenSilhouetteAffected": true, "referencePbrExtraction": {"requiredWhenSourceImagePresent": false, "targetThreshold": 0.7, "stopOnLowConfidence": true, "script": "forge/stage1_intake/extract_pbr_evidence.py", "acceptedLimitation": "single-image extraction is reference-derived inference, not exact photogrammetry", "skipReason": "Flat matte-plastic shell + 2-color printed decal, no patterned/photoreal skin -- scalar PBR values estimated by eye per grimoire/build/threejs_texture_reference.md 'solid albedo for flat paint' rule instead of extract_pbr_evidence.py. See spec.risks[0]."}, "mustAvoid": ["single flat albedo per material", "uniform roughness", "albedo texture reused as roughness/height/normal/AO", "single-frequency random noise", "plastic-looking smooth bark, stone, cloth, foliage, or aged material", "local color/detail described only in prose without material masks", "claiming exact PBR recovery when confidence is below the target threshold"]}, "lightingPass": {"requiredTerms": ["key light", "fill light", "rim or environment light", "exposure", "tone mapping", "background", "contact shadow"], "mustAvoid": ["ambient-only lighting", "flat value range", "missing contact shadow", "reference lighting copied without separating material readability"]}, "screenshotReview": ["Compare albedo palette and local color zones.", "Compare roughness/normal/bump response under light.", "Compare cavity dirt, edge wear, stains, moss, scratches, or other local masks.", "Compare key/fill/rim structure, exposure, tone mapping, background, and contact shadows.", "Capture a neutral-light render to verify material readability without reference lighting.", "Capture a grazing-light close-up to expose flat normals, uniform roughness, tiling, and plastic highlights.", "Capture a reference-matched render from the same camera framing as the source."]};
+ root.userData.actionReadiness = {
+ note: 'Use root.userData.sculptRuntime.nodes for transforms, sockets for attachments, colliders for physics proxies, and destructionGroups for breakable sets.',
+ };
+ return root;
+}
+
+export function createTradeItHardCaseLookDevLights(
+ mode: 'neutral' | 'grazing' | 'reference' = 'neutral',
+): THREE.Group {
+ const lights = new THREE.Group();
+ lights.name = "TradeIt Hard Case look-dev lights";
+ const hemi = new THREE.HemisphereLight(
+ mode === 'reference' ? 0xfff0d6 : 0xf2f4ff,
+ 0x363b42,
+ mode === 'grazing' ? 0.28 : mode === 'reference' ? 0.72 : 0.85,
+ );
+ lights.add(hemi);
+ const key = new THREE.DirectionalLight(
+ mode === 'reference' ? 0xffcf8a : 0xfff4e8,
+ mode === 'grazing' ? 4.2 : mode === 'reference' ? 2.6 : 2.15,
+ );
+ if (mode === 'grazing') key.position.set(7.5, 1.1, 4.0);
+ else if (mode === 'reference') key.position.set(-4.5, 7.5, 5.0);
+ else key.position.set(-4.0, 6.0, 5.5);
+ key.castShadow = true;
+ key.shadow.mapSize.set(4096, 4096);
+ key.shadow.bias = -0.00025;
+ key.shadow.normalBias = 0.018;
+ key.shadow.radius = 7;
+ key.shadow.blurSamples = 24;
+ key.shadow.camera.near = 0.5;
+ key.shadow.camera.far = 30;
+ key.shadow.camera.left = -2.6;
+ key.shadow.camera.right = 2.6;
+ key.shadow.camera.top = 2.6;
+ key.shadow.camera.bottom = -2.6;
+ key.shadow.camera.updateProjectionMatrix();
+ lights.add(key);
+ const fill = new THREE.DirectionalLight(0xa8c4ff, mode === 'grazing' ? 0.12 : 0.42);
+ fill.position.set(4.0, 3.0, 3.5);
+ lights.add(fill);
+ const rim = new THREE.DirectionalLight(0xfff1c4, mode === 'grazing' ? 0.28 : 0.85);
+ rim.position.set(0.5, 4.5, -6.0);
+ lights.add(rim);
+ lights.userData.reviewMode = mode;
+ lights.userData.lightingFromPhoto = [{"role": "key", "direction": "upper-left, ~45deg elevation", "colorTemp": "neutral-cool studio", "intensity": "moderate", "evidence": ["closed-front-3q"]}, {"role": "fill", "direction": "ambient/bounce, low contrast ratio", "colorTemp": "neutral", "intensity": "low", "evidence": ["closed-front-3q"]}, {"role": "environment", "direction": "soft studio IBL", "colorTemp": "neutral", "intensity": "low", "note": "ACES filmic tone mapping, exposure ~1.0; soft contact shadow under the case on the ground plane.", "evidence": ["closed-front-3q"]}];
+ lights.userData.lookDevTargets = {"qualityPriority": "reference-fidelity", "materialPass": {"albedoPaletteRequired": true, "roughnessVariationRequired": true, "normalOrBumpRequired": true, "localOverridesRequired": true, "minimumTextureResolution": 1024, "preferredTextureResolution": 2048, "independentMapChannels": ["albedo", "roughness", "height", "normal", "ambient-occlusion"], "requiredSurfaceFrequencyBands": ["macro", "meso", "micro"], "geometryReliefRequiredWhenSilhouetteAffected": true, "referencePbrExtraction": {"requiredWhenSourceImagePresent": false, "targetThreshold": 0.7, "stopOnLowConfidence": true, "script": "forge/stage1_intake/extract_pbr_evidence.py", "acceptedLimitation": "single-image extraction is reference-derived inference, not exact photogrammetry", "skipReason": "Flat matte-plastic shell + 2-color printed decal, no patterned/photoreal skin -- scalar PBR values estimated by eye per grimoire/build/threejs_texture_reference.md 'solid albedo for flat paint' rule instead of extract_pbr_evidence.py. See spec.risks[0]."}, "mustAvoid": ["single flat albedo per material", "uniform roughness", "albedo texture reused as roughness/height/normal/AO", "single-frequency random noise", "plastic-looking smooth bark, stone, cloth, foliage, or aged material", "local color/detail described only in prose without material masks", "claiming exact PBR recovery when confidence is below the target threshold"]}, "lightingPass": {"requiredTerms": ["key light", "fill light", "rim or environment light", "exposure", "tone mapping", "background", "contact shadow"], "mustAvoid": ["ambient-only lighting", "flat value range", "missing contact shadow", "reference lighting copied without separating material readability"]}, "screenshotReview": ["Compare albedo palette and local color zones.", "Compare roughness/normal/bump response under light.", "Compare cavity dirt, edge wear, stains, moss, scratches, or other local masks.", "Compare key/fill/rim structure, exposure, tone mapping, background, and contact shadows.", "Capture a neutral-light render to verify material readability without reference lighting.", "Capture a grazing-light close-up to expose flat normals, uniform roughness, tiling, and plastic highlights.", "Capture a reference-matched render from the same camera framing as the source."]};
+ return lights;
+}
+
+// PBR materials (clearcoat/iridescence/transmission/anisotropy) need an environment
+// map to visually behave as intended — call this once per renderer and assign the
+// result to scene.environment before rendering. No external HDR asset required.
+export function createTradeItHardCaseEnvironment(renderer: THREE.WebGLRenderer): THREE.Texture {
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ const texture = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ pmrem.dispose();
+ return texture;
+}
+
+// Plan 1.3 §3.2 — auto-framing by bounding box. The Divine Eye can only compare a
+// render to the reference if the object is FRAMED consistently (an object framed
+// differently scores as wrong even when its shape is right). This positions the camera
+// deterministically from the object's bounding box so it fills the frame at a stable
+// margin, and sets near/far to the object scale. Call after adding the model to the
+// scene, and again on resize (after updating camera.aspect).
+export function frameTradeItHardCaseCamera(
+ camera: THREE.PerspectiveCamera,
+ object: THREE.Object3D,
+ options: { margin?: number; azimuthDeg?: number; elevationDeg?: number } = {},
+): void {
+ const box = new THREE.Box3().setFromObject(object);
+ if (box.isEmpty()) return;
+ const size = box.getSize(new THREE.Vector3());
+ const center = box.getCenter(new THREE.Vector3());
+ const margin = options.margin ?? 1.15;
+ const maxDim = Math.max(size.x, size.y, size.z) * margin;
+ const fov = (camera.fov * Math.PI) / 180;
+ // distance so the largest object dimension fits vertically in the frame
+ const distance = (maxDim / 2) / Math.tan(fov / 2);
+ const az = ((options.azimuthDeg ?? 0) * Math.PI) / 180;
+ const el = ((options.elevationDeg ?? 0) * Math.PI) / 180;
+ const dir = new THREE.Vector3(
+ Math.sin(az) * Math.cos(el),
+ Math.sin(el),
+ Math.cos(az) * Math.cos(el),
+ );
+ camera.position.copy(center).addScaledVector(dir, distance);
+ camera.near = Math.max(0.01, distance - maxDim);
+ camera.far = distance + maxDim * 2;
+ camera.lookAt(center);
+ camera.updateProjectionMatrix();
+}
+
+// Plan 1.3 §3.2c — PRESENTATION composer (DOF + bloom). CRITICAL (R-POSTFX): this is
+// for the showcase/hero render ONLY. The Divine Eye's EVALUATION render MUST use a
+// plain renderer with NO composer — bloom blows highlights and DOF blurs edges, which
+// would corrupt the deterministic IoU/DCD/edge/blowout signals. Enable dof/bloom ONLY
+// when the reference photo actually exhibits them (detect_reference_effects.py authorizes).
+export function createTradeItHardCasePresentationComposer(
+ renderer: THREE.WebGLRenderer,
+ scene: THREE.Scene,
+ camera: THREE.Camera,
+ options: { dof?: boolean; bloom?: boolean; bloomStrength?: number; dofFocus?: number; dofAperture?: number } = {},
+): EffectComposer {
+ const composer = new EffectComposer(renderer);
+ composer.addPass(new RenderPass(scene, camera));
+ if (options.dof) {
+ composer.addPass(new BokehPass(scene, camera, {
+ focus: options.dofFocus ?? 10.0,
+ aperture: options.dofAperture ?? 0.0002,
+ maxblur: 0.01,
+ }));
+ }
+ if (options.bloom) {
+ const size = new THREE.Vector2();
+ renderer.getSize(size);
+ composer.addPass(new UnrealBloomPass(size, options.bloomStrength ?? 0.4, 0.4, 0.85));
+ }
+ return composer;
+}
+
+export function configureTradeItHardCaseRenderer(renderer: THREE.WebGLRenderer): void {
+ // Load-bearing for view-dependent finishes (anodized / Doppler): without ACES + sRGB
+ // the environment reflection reads flat/washed instead of a believable metal response.
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+}
+
+export function createTradeItHardCaseInspectControls(
+ camera: THREE.Camera,
+ domElement: HTMLElement,
+): OrbitControls {
+ // View-dependent finishes only read correctly once the user orbits — their color
+ // comes from the environment reflection, not albedo, so free rotation matters here.
+ const controls = new OrbitControls(camera, domElement);
+ controls.enableDamping = true;
+ controls.minDistance = 1.0;
+ controls.maxDistance = 8.0;
+ controls.autoRotate = false;
+ return controls;
+}
diff --git a/forge/tests/oracle_support.py b/forge/tests/oracle_support.py
new file mode 100644
index 0000000..6a8128a
--- /dev/null
+++ b/forge/tests/oracle_support.py
@@ -0,0 +1,51 @@
+"""Shared byte-equality oracle-replay harness (task 3.11, `establish-the-emission-target-contract`).
+
+Extracted from plugin-cs2's `test_cs2_oracle_replay.py` pattern (`:28-63`): replay a fixed input
+through a real subprocess, assert its output is byte-identical to a recorded oracle fixture, and
+run an anti-tamper guard first -- a byte comparison against a hollow or degenerate oracle proves
+nothing about a working pipeline. Not named `test_*.py`: it holds no `TestCase` of its own and must
+not be picked up by `unittest.TestLoader().discover(...)`, only imported by tests that use it.
+
+Fixtures are per-change -- this change freezes its own (`forge/tests/fixtures/
+reference_target_*`) -- only this harness is shared, meant to be reused by
+`extract-character-into-its-own-plugin` and any future oracle-style replay test.
+"""
+
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+from typing import Callable, Sequence
+
+
+def assert_replay_matches_oracle(
+ testcase,
+ argv: Sequence[str],
+ *,
+ cwd: Path,
+ expected_path: Path,
+ out_path: Path,
+ tamper_guard: Callable[[], None] | None = None,
+) -> bytes:
+ """Run `argv`, then assert `out_path`'s bytes equal `expected_path`'s recorded bytes.
+
+ `tamper_guard`, if given, runs BEFORE the replay and must raise (via the testcase's own
+ assertions) if the oracle fixture itself looks degenerate -- e.g. empty, or recording a failed
+ run -- so a byte comparison cannot pass trivially against a fixture that no longer proves
+ anything. Returns the actual bytes, for any assertion the caller wants to layer on top.
+ """
+ if tamper_guard is not None:
+ tamper_guard()
+ expected = expected_path.read_bytes()
+ proc = subprocess.run(list(argv), cwd=cwd, capture_output=True, text=False)
+ testcase.assertEqual(
+ proc.returncode, 0, f"replay command failed:\n{proc.stderr.decode('utf-8', errors='replace')}"
+ )
+ actual = out_path.read_bytes()
+ testcase.assertEqual(
+ actual,
+ expected,
+ "Replay drifted from the recorded oracle. If the change was intentional, re-record the "
+ "fixture in the same commit and say so -- do not relax this assertion.",
+ )
+ return actual
diff --git a/forge/tests/test_emit_target.py b/forge/tests/test_emit_target.py
new file mode 100644
index 0000000..25dad87
--- /dev/null
+++ b/forge/tests/test_emit_target.py
@@ -0,0 +1,279 @@
+"""emit_target.py socket matrix (task 3.12, `establish-the-emission-target-contract`).
+
+Covers: null default (no file written, mtime unchanged); installed target produces a verified
+artifact; missing target fails naming it; crash surfaces exit code; hang trips the first timeout;
+wrong-kind refused naming both kinds; mid-pass invocation refused naming the unmet step; every test
+pins IMG2_HOME to a temp/empty directory (`test_search_specs.py:243` pattern); one test runs
+against a deliberately malformed plugins.json asserting the no-target path still succeeds.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import textwrap
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "forge"))
+sys.path.insert(0, str(ROOT / "forge" / "_shared"))
+sys.path.insert(0, str(ROOT / "forge" / "stage3_build"))
+
+import emit_target # noqa: E402
+from workflow_state import new_state, save_state # noqa: E402
+
+EMIT_TARGET = ROOT / "forge" / "stage3_build" / "emit_target.py"
+
+
+def _action_ready_state_path(workspace: Path) -> Path:
+ """A workspace whose state has reached action-ready -- built directly rather than driven
+ through the real sequential mark_steps() API, which is out of scope for this module (it is
+ covered by test_workflow_state.py); this file only needs a state.json where the precondition
+ check reads "done"."""
+ state = new_state("ref.png", spec=str(workspace / "spec.json"))
+ for entry in state["checklist"]:
+ entry["status"] = "done"
+ entry["evidence"] = ["fixture"]
+ state["currentPass"] = "complete"
+ state["status"] = "complete"
+ state["currentStep"] = "complete"
+ path = workspace / ".img2threejs" / "state.json"
+ save_state(path, state)
+ return path
+
+
+def _write_plugin_target(
+ home: Path,
+ plugin_id: str,
+ kind: str,
+ *,
+ tool_source: str,
+ artifact_rel: str,
+ deterministic: bool = False,
+ timeout_seconds: int | None = None,
+ harness_version: str = "0.5.0",
+) -> None:
+ (home / "harness").mkdir(parents=True, exist_ok=True)
+ (home / "harness" / "package.json").write_text(json.dumps({"version": harness_version}), encoding="utf-8")
+ plugin_dir = home / "plugins" / plugin_id
+ (plugin_dir / "tools").mkdir(parents=True, exist_ok=True)
+ (plugin_dir / "tools" / "emit.py").write_text(textwrap.dedent(tool_source), encoding="utf-8")
+ manifest = {
+ "schema": 1, "name": plugin_id, "version": "0.1.0", "description": "fixture",
+ "capabilities": [{"from": "sculpt-spec", "to": kind}],
+ "requires": {"harness": ">=0.1.0", "coreApi": 1},
+ }
+ (plugin_dir / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
+ step = {
+ "id": "emit", "after": [],
+ "command": "python3 {plugin_dir}/tools/emit.py --spec {spec} --out {workspace}/" + artifact_rel,
+ "provides": {"version": 1, "from": "sculpt-spec", "to": kind,
+ "artifact": {"kind": kind, "path": artifact_rel}},
+ "deterministic": deterministic,
+ }
+ if timeout_seconds is not None:
+ step["timeoutSeconds"] = timeout_seconds
+ (plugin_dir / "steps.json").write_text(json.dumps([step]), encoding="utf-8")
+ registry_path = home / "plugins.json"
+ registry = json.loads(registry_path.read_text(encoding="utf-8")) if registry_path.is_file() else {"plugins": []}
+ registry["plugins"].append({"id": plugin_id, "repo": "x", "ref": "v1", "resolvedSha": f"sha-{plugin_id}", "addedAt": "2026-01-01"})
+ registry_path.write_text(json.dumps(registry), encoding="utf-8")
+
+
+WRITES_JSON_TOOL = """
+ import argparse, json, os
+ p = argparse.ArgumentParser(); p.add_argument("--spec", required=True); p.add_argument("--out", required=True)
+ a = p.parse_args()
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
+ with open(a.out, "w") as f:
+ json.dump({"ok": True}, f)
+"""
+
+CRASHES_TOOL = """
+ import argparse, os, sys
+ p = argparse.ArgumentParser(); p.add_argument("--spec", required=True); p.add_argument("--out", required=True)
+ a = p.parse_args()
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
+ open(a.out, "w").write("partial")
+ sys.exit(1)
+"""
+
+HANGS_TOOL = """
+ import argparse, os, time
+ p = argparse.ArgumentParser(); p.add_argument("--spec", required=True); p.add_argument("--out", required=True)
+ a = p.parse_args()
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
+ open(a.out, "w").write("x")
+ time.sleep(30)
+"""
+
+WRONG_KIND_GLB_TOOL = """
+ import argparse, os
+ p = argparse.ArgumentParser(); p.add_argument("--spec", required=True); p.add_argument("--out", required=True)
+ a = p.parse_args()
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
+ open(a.out, "wb").write(b"not a real glb")
+"""
+
+
+class EmitTargetTestBase(unittest.TestCase):
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self._tmp.cleanup)
+ self.root = Path(self._tmp.name)
+ self.home = self.root / "img2home-empty"
+ self.home.mkdir()
+ self.workspace = self.root / "ws"
+ self.workspace.mkdir()
+ self.spec_path = self.workspace / "spec.json"
+ self.spec_path.write_text(json.dumps({"buildPasses": [{"id": "blockout"}]}), encoding="utf-8")
+ self.env = {**os.environ, "IMG2_HOME": str(self.home)}
+
+ def run_cli(self, *args):
+ return subprocess.run(
+ [sys.executable, str(EMIT_TARGET), "--spec", str(self.spec_path), "--workspace", str(self.workspace), *args],
+ env=self.env, capture_output=True, text=True,
+ )
+
+
+class NullDefault(EmitTargetTestBase):
+ def test_no_target_writes_nothing_and_succeeds(self):
+ candidate = self.workspace / "src" / "createObjectModel.ts"
+ candidate.parent.mkdir(parents=True, exist_ok=True)
+ candidate.write_text("// pre-existing", encoding="utf-8")
+ before_mtime = candidate.stat().st_mtime_ns
+ proc = self.run_cli()
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ self.assertIn("src/createObjectModel.ts", proc.stdout)
+ self.assertEqual(candidate.stat().st_mtime_ns, before_mtime)
+ self.assertEqual(candidate.read_text(encoding="utf-8"), "// pre-existing")
+
+ def test_no_target_never_reads_the_registry_even_when_it_is_malformed(self):
+ (self.home / "plugins.json").write_text("not valid json {{{", encoding="utf-8")
+ proc = self.run_cli()
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+
+ def test_help_does_not_touch_the_registry_either(self):
+ (self.home / "plugins.json").write_text("not valid json {{{", encoding="utf-8")
+ proc = subprocess.run([sys.executable, str(EMIT_TARGET), "--help"], env=self.env, capture_output=True, text=True)
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+
+
+class ActionReadyPrecondition(EmitTargetTestBase):
+ def test_no_state_file_refuses_naming_the_gap(self):
+ proc = self.run_cli("--target", "threejs-ts")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("action-ready", proc.stderr)
+ self.assertIn("has not reached action-ready", proc.stderr)
+
+ def test_mid_pass_state_refuses_naming_the_unmet_step(self):
+ state = new_state("ref.png", spec=str(self.spec_path))
+ # Leave everything pending -- the state exists but nothing is action-ready yet.
+ save_state(self.workspace / ".img2threejs" / "state.json", state)
+ proc = self.run_cli("--target", "threejs-ts")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("next required step", proc.stderr)
+ self.assertIn(state["currentStep"], proc.stderr)
+ self.assertNotIn("no target subprocess", proc.stdout)
+
+ def test_action_ready_state_passes_the_precondition(self):
+ _action_ready_state_path(self.workspace)
+ # No plugin installed, so resolution itself fails -- but that proves the precondition was
+ # cleared: the message is about resolution, not about action-ready.
+ proc = self.run_cli("--target", "nope")
+ self.assertEqual(proc.returncode, 1)
+ self.assertNotIn("action-ready", proc.stderr)
+ self.assertIn("nope", proc.stderr)
+
+
+class InstalledTargetProducesAVerifiedArtifact(EmitTargetTestBase):
+ def test_success_writes_artifact_and_provenance(self):
+ _action_ready_state_path(self.workspace)
+ _write_plugin_target(self.home, "echo-plugin", "echo", tool_source=WRITES_JSON_TOOL,
+ artifact_rel=".img2/artifacts/echo-plugin/echo.json")
+ proc = self.run_cli("--target", "echo")
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ artifact = self.workspace / ".img2" / "artifacts" / "echo-plugin" / "echo.json"
+ self.assertTrue(artifact.is_file())
+ provenance = json.loads(Path(str(artifact) + ".provenance.json").read_text(encoding="utf-8"))
+ self.assertEqual(provenance["plugin"]["id"], "echo-plugin")
+ self.assertEqual(provenance["plugin"]["resolvedSha"], "sha-echo-plugin")
+ self.assertIn("specContentHash", provenance)
+
+
+class MissingTargetFailsNamingIt(EmitTargetTestBase):
+ def test_unresolved_kind_fails_naming_it(self):
+ _action_ready_state_path(self.workspace)
+ proc = self.run_cli("--target", "does-not-exist")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("does-not-exist", proc.stderr)
+
+
+class CrashSurfacesExitCode(EmitTargetTestBase):
+ def test_a_crashing_target_fails_and_deletes_the_partial_artifact(self):
+ _action_ready_state_path(self.workspace)
+ _write_plugin_target(self.home, "crash-plugin", "crash-kind", tool_source=CRASHES_TOOL,
+ artifact_rel=".img2/artifacts/crash-plugin/out.json")
+ proc = self.run_cli("--target", "crash-kind")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("exited 1", proc.stderr)
+ self.assertFalse((self.workspace / ".img2" / "artifacts" / "crash-plugin" / "out.json").exists())
+
+
+class HangTripsTheFirstTimeout(EmitTargetTestBase):
+ def test_a_hanging_target_is_killed_and_names_the_bound(self):
+ _action_ready_state_path(self.workspace)
+ _write_plugin_target(self.home, "hang-plugin", "hang-kind", tool_source=HANGS_TOOL,
+ artifact_rel=".img2/artifacts/hang-plugin/out.json", timeout_seconds=1)
+ proc = self.run_cli("--target", "hang-kind")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("timed out after 1s", proc.stderr)
+ self.assertFalse((self.workspace / ".img2" / "artifacts" / "hang-plugin" / "out.json").exists())
+
+ def test_a_declared_timeout_over_the_ceiling_is_refused(self):
+ _action_ready_state_path(self.workspace)
+ _write_plugin_target(self.home, "greedy-plugin", "greedy-kind", tool_source=WRITES_JSON_TOOL,
+ artifact_rel=".img2/artifacts/greedy-plugin/out.json", timeout_seconds=999999)
+ proc = self.run_cli("--target", "greedy-kind")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("exceeds the base-owned ceiling", proc.stderr)
+
+
+class WrongKindRefusedNamingBothKinds(EmitTargetTestBase):
+ def test_a_declared_glb_that_is_not_a_glb_is_refused(self):
+ _action_ready_state_path(self.workspace)
+ _write_plugin_target(self.home, "fake-glb-plugin", "glb", tool_source=WRONG_KIND_GLB_TOOL,
+ artifact_rel=".img2/artifacts/fake-glb-plugin/out.glb")
+ proc = self.run_cli("--target", "glb")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("glb", proc.stderr)
+ self.assertIn("container check failed", proc.stderr)
+ self.assertFalse((self.workspace / ".img2" / "artifacts" / "fake-glb-plugin" / "out.glb").exists())
+
+
+class DeterminismMismatchFailsNamingTheTarget(EmitTargetTestBase):
+ def test_a_target_that_lies_about_determinism_is_refused(self):
+ _action_ready_state_path(self.workspace)
+ nondeterministic_tool = textwrap.dedent("""
+ import argparse, os, random, json
+ p = argparse.ArgumentParser(); p.add_argument("--spec", required=True); p.add_argument("--out", required=True)
+ a = p.parse_args()
+ os.makedirs(os.path.dirname(a.out), exist_ok=True)
+ with open(a.out, "w") as f:
+ json.dump({"nonce": random.random()}, f)
+ """)
+ _write_plugin_target(self.home, "flaky-plugin", "flaky-kind", tool_source=nondeterministic_tool,
+ artifact_rel=".img2/artifacts/flaky-plugin/out.json", deterministic=True)
+ proc = self.run_cli("--target", "flaky-kind")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("flaky-kind", proc.stderr)
+ self.assertIn("different bytes", proc.stderr)
+ self.assertFalse((self.workspace / ".img2" / "artifacts" / "flaky-plugin" / "out.json").exists())
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_sculpt_echo_failure_matrix.py b/forge/tests/test_sculpt_echo_failure_matrix.py
new file mode 100644
index 0000000..797ac19
--- /dev/null
+++ b/forge/tests/test_sculpt_echo_failure_matrix.py
@@ -0,0 +1,159 @@
+"""The failure matrix against `plugin-sculpt-echo` (task 3.15,
+`establish-the-emission-target-contract`).
+
+Uninstall / crash / hang / wrong-kind, run against the real fixture plugin rather than a synthetic
+stand-in -- `test_emit_target.py` already covers this matrix against throwaway fixture plugins;
+this module exists so the one plugin authored from the wiki (task 3.13) is also exercised by it.
+
+Every test pins IMG2_HOME to a temp/empty directory populated directly (no `img2 add`/`sync`, so no
+host skill-symlink side effects here -- see `test_sculpt_echo_roundtrip.py` for the one test that
+legitimately needs those).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+ORG_ROOT = ROOT.parent
+PLUGIN_DIR = ORG_ROOT / "plugin-sculpt-echo"
+HARNESS_DIR = ORG_ROOT / "img2-harness"
+EMIT_TARGET = ROOT / "forge" / "stage3_build" / "emit_target.py"
+
+sys.path.insert(0, str(ROOT / "forge" / "_shared"))
+
+
+def _action_ready_state_path(workspace: Path, spec_path: Path) -> Path:
+ from workflow_state import new_state, save_state
+
+ state = new_state("ref.png", spec=str(spec_path))
+ for entry in state["checklist"]:
+ entry["status"] = "done"
+ entry["evidence"] = ["fixture"]
+ state["currentPass"] = "complete"
+ state["status"] = "complete"
+ state["currentStep"] = "complete"
+ path = workspace / ".img2threejs" / "state.json"
+ save_state(path, state)
+ return path
+
+
[email protected](PLUGIN_DIR.is_dir(), f"sibling checkout not found: {PLUGIN_DIR}")
[email protected](HARNESS_DIR.is_dir(), f"sibling checkout not found: {HARNESS_DIR}")
+class SculptEchoFailureMatrixBase(unittest.TestCase):
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self._tmp.cleanup)
+ self.root = Path(self._tmp.name)
+ self.home = self.root / "img2home"
+ self.home.mkdir()
+ (self.home / "plugins").mkdir()
+ # A real img2_core, copied rather than installed, so the plugin's bootstrap stanza
+ # (`sys.path.insert(0, IMG2_HOME/harness)`) resolves it exactly as it would for real.
+ shutil.copytree(HARNESS_DIR / "img2_core", self.home / "harness" / "img2_core",
+ ignore=shutil.ignore_patterns("__pycache__"))
+ (self.home / "harness" / "package.json").write_text(json.dumps({"version": "0.5.0"}), encoding="utf-8")
+ self.workspace = self.root / "ws"
+ self.workspace.mkdir()
+ self.spec_path = self.workspace / "spec.json"
+ self.spec_path.write_text(
+ json.dumps({"targetId": "matrix", "buildPasses": [{"id": "blockout"}], "componentTree": [{"id": "body"}]}),
+ encoding="utf-8",
+ )
+ self.env = {**os.environ, "IMG2_HOME": str(self.home)}
+
+ def _install_real_plugin(self):
+ (self.home / "plugins" / "sculpt-echo").symlink_to(PLUGIN_DIR)
+ (self.home / "plugins.json").write_text(
+ json.dumps({"version": 1, "plugins": [
+ {"id": "sculpt-echo", "repo": "local", "ref": "local", "resolvedSha": "local", "addedAt": "2026-01-01"}
+ ]}),
+ encoding="utf-8",
+ )
+
+ def run_cli(self, *args):
+ return subprocess.run(
+ [sys.executable, str(EMIT_TARGET), "--spec", str(self.spec_path), "--workspace", str(self.workspace), *args],
+ env=self.env, capture_output=True, text=True,
+ )
+
+
+class Uninstalled(SculptEchoFailureMatrixBase):
+ def test_selecting_echo_with_no_plugin_installed_fails_naming_it(self):
+ (self.home / "plugins.json").write_text(json.dumps({"version": 1, "plugins": []}), encoding="utf-8")
+ _action_ready_state_path(self.workspace, self.spec_path)
+ proc = self.run_cli("--target", "echo")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("echo", proc.stderr)
+ self.assertIn("no installed plugin provides", proc.stderr)
+
+
+class Crashes(SculptEchoFailureMatrixBase):
+ def test_a_crashing_echo_emitter_surfaces_its_exit_code(self):
+ self._install_real_plugin()
+ _action_ready_state_path(self.workspace, self.spec_path)
+ # Corrupt the spec so emit_echo.py's own JSON parse fails and it exits non-zero -- exactly
+ # the shape "the plugin's own tool crashed" takes here, without needing a second fixture.
+ self.spec_path.write_text("not valid json {{{", encoding="utf-8")
+ proc = self.run_cli("--target", "echo")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("exited 1", proc.stderr)
+ self.assertFalse((self.workspace / ".img2" / "artifacts" / "sculpt-echo" / "echo.json").exists())
+
+
+class Hangs(SculptEchoFailureMatrixBase):
+ def test_a_hung_echo_emitter_is_killed_at_the_declared_bound(self):
+ # A copy of the real plugin with its emit tool swapped for one that hangs -- the fixture
+ # plugin itself has no reason to ship a hanging code path, so the matrix supplies one.
+ hanging_plugin = self.root / "sculpt-echo-hangs"
+ shutil.copytree(PLUGIN_DIR, hanging_plugin, ignore=shutil.ignore_patterns(".git", "__pycache__"))
+ (hanging_plugin / "tools" / "emit_echo.py").write_text(
+ "import time\n"
+ "import sys\n"
+ "sys.path.insert(0, __file__.rsplit('/', 1)[0])\n"
+ "time.sleep(30)\n",
+ encoding="utf-8",
+ )
+ steps = json.loads((hanging_plugin / "steps.json").read_text(encoding="utf-8"))
+ steps[0]["timeoutSeconds"] = 1
+ (hanging_plugin / "steps.json").write_text(json.dumps(steps), encoding="utf-8")
+
+ (self.home / "plugins" / "sculpt-echo").symlink_to(hanging_plugin)
+ (self.home / "plugins.json").write_text(
+ json.dumps({"version": 1, "plugins": [
+ {"id": "sculpt-echo", "repo": "local", "ref": "local", "resolvedSha": "local", "addedAt": "2026-01-01"}
+ ]}),
+ encoding="utf-8",
+ )
+ _action_ready_state_path(self.workspace, self.spec_path)
+ proc = self.run_cli("--target", "echo")
+ self.assertEqual(proc.returncode, 1)
+ self.assertIn("timed out after 1s", proc.stderr)
+ self.assertFalse((self.workspace / ".img2" / "artifacts" / "sculpt-echo" / "echo.json").exists())
+
+
+class WrongKind(SculptEchoFailureMatrixBase):
+ def test_an_echo_artifact_that_is_not_json_would_still_pass_since_echo_has_no_prober(self):
+ # Honest limit, not a defect: "echo" has no container prober (only "glb" does today), so a
+ # wrong-shaped echo.json is accepted on existence/size/location alone -- recorded here so
+ # the matrix documents the limit rather than silently skipping this case.
+ self._install_real_plugin()
+ _action_ready_state_path(self.workspace, self.spec_path)
+ proc = self.run_cli("--target", "echo")
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ provenance = json.loads(
+ (self.workspace / ".img2" / "artifacts" / "sculpt-echo" / "echo.json.provenance.json").read_text(encoding="utf-8")
+ )
+ self.assertEqual(provenance["verification"]["level"], "existence+size+location")
+ self.assertIn("no further base quality warranty applies", provenance["verification"]["note"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_sculpt_echo_roundtrip.py b/forge/tests/test_sculpt_echo_roundtrip.py
new file mode 100644
index 0000000..6e9db18
--- /dev/null
+++ b/forge/tests/test_sculpt_echo_roundtrip.py
@@ -0,0 +1,181 @@
+"""The fixture round-trip, wired as a hard gate (task 3.14, `establish-the-emission-target-contract`).
+
+install -> doctor -> resolve -> --target echo -> artifact produced -> the base repo's working tree
+is unchanged. This is the mechanically falsifiable form of "zero base changes" (D8) -- the only
+non-base evidence for the ecosystem claim.
+
+No `.github/workflows/*.yml` exists in either repo today, so there is no separate CI pipeline file
+to add a step to; this test module IS the enforcement mechanism, in the same sense
+`test_suite_integrity.py`'s COLLECTED_FLOOR is -- it runs every time the base suite runs.
+
+This test genuinely invokes `img2 add --link` and `img2 doctor` -- `doctor` requires the on-disk
+state `add`/`sync` produces (host skill symlinks under `~/.claude/skills/` etc., `_img2_local.py`
+sync stubs inside the plugin checkout) to pass at all; there is no hermetic shortcut that bypasses
+those checks and still exercises real `doctor`. Those host-linking side effects are real and are
+NOT scoped to the scratch `$IMG2_HOME` this test builds, so this snapshots every location `add`
+touches before running and restores it exactly in `addCleanup` (registered before any mutation, so
+it runs even on assertion failure) -- a developer's actual `~/.claude/skills/`, `~/.codex/skills/`,
+`~/.config/opencode/skills/` and `~/.claude/settings.json` must read identically before and after.
+
+Deliberately does NOT call `img2 install`: it provisions the harness via `git clone` from the local
+checkout, which captures only the last COMMIT -- any uncommitted harness work (there is some, from
+other lanes of this same change) would silently be missing from the scratch home, and this test
+would then be exercising a stale harness instead of the one actually on disk. `$IMG2_HOME/harness`
+is populated with a plain recursive copy of the live working tree instead, so uncommitted changes
+are exercised the same way a developer running this by hand would see them.
+
+Skips (does not fail) when `node` is not on PATH, or when the sibling `img2-harness` /
+`plugin-sculpt-echo` checkouts are not present -- this repository does not vendor either.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+ORG_ROOT = ROOT.parent
+HARNESS_DIR = ORG_ROOT / "img2-harness"
+PLUGIN_DIR = ORG_ROOT / "plugin-sculpt-echo"
+EMIT_TARGET = ROOT / "forge" / "stage3_build" / "emit_target.py"
+
+SKILL_LINKS = (
+ Path.home() / ".claude" / "skills" / "img2-sculpt-echo",
+ Path.home() / ".codex" / "skills" / "img2-sculpt-echo",
+ Path.home() / ".config" / "opencode" / "skills" / "img2-sculpt-echo",
+)
+CLAUDE_SETTINGS = Path.home() / ".claude" / "settings.json"
+PLUGIN_SYNC_STUBS = (PLUGIN_DIR / "_img2_local.py", PLUGIN_DIR / "tools" / "_img2_local.py")
+
+sys.path.insert(0, str(ROOT / "forge" / "_shared"))
+
+
+def _node_available() -> bool:
+ return shutil.which("node") is not None
+
+
+def _git_status(repo: Path) -> str:
+ proc = subprocess.run(["git", "status", "--porcelain"], cwd=repo, capture_output=True, text=True)
+ return proc.stdout if proc.returncode == 0 else ""
+
+
+def _snapshot_link(path: Path) -> str | None:
+ return os.readlink(path) if path.is_symlink() else None
+
+
+def _restore_link(path: Path, previous_target: str | None) -> None:
+ if path.is_symlink() or path.exists():
+ path.unlink()
+ if previous_target is not None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.symlink_to(previous_target)
+
+
+def _snapshot_additional_directories() -> list | None:
+ if not CLAUDE_SETTINGS.is_file():
+ return None
+ try:
+ data = json.loads(CLAUDE_SETTINGS.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return None
+ return list(data.get("permissions", {}).get("additionalDirectories", []))
+
+
+def _restore_additional_directories(previous: list | None) -> None:
+ if previous is None or not CLAUDE_SETTINGS.is_file():
+ return
+ data = json.loads(CLAUDE_SETTINGS.read_text(encoding="utf-8"))
+ data.setdefault("permissions", {})["additionalDirectories"] = previous
+ CLAUDE_SETTINGS.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+
+
[email protected](_node_available(), "node is not on PATH")
[email protected](HARNESS_DIR.is_dir(), f"sibling checkout not found: {HARNESS_DIR}")
[email protected](PLUGIN_DIR.is_dir(), f"sibling checkout not found: {PLUGIN_DIR}")
+class SculptEchoRoundTrip(unittest.TestCase):
+ def setUp(self):
+ # Registered before any mutating command runs, so a failed assertion mid-test still
+ # restores every host location `add --link` / `sync` can touch.
+ for link in SKILL_LINKS:
+ self.addCleanup(_restore_link, link, _snapshot_link(link))
+ self.addCleanup(_restore_additional_directories, _snapshot_additional_directories())
+ for stub in PLUGIN_SYNC_STUBS:
+ self.addCleanup(lambda p=stub: p.unlink(missing_ok=True))
+
+ self._tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self._tmp.cleanup)
+ root = Path(self._tmp.name)
+ self.home = root / "img2home"
+ # Plain copy, not `img2 install` (see module docstring): captures the live working tree,
+ # including any uncommitted harness changes, instead of only the last git commit.
+ shutil.copytree(
+ HARNESS_DIR, self.home / "harness",
+ ignore=shutil.ignore_patterns("node_modules", ".git", "__pycache__"),
+ )
+ for name in ("plugins", "generated", "backups"):
+ (self.home / name).mkdir(parents=True, exist_ok=True)
+ (self.home / "plugins.json").write_text(json.dumps({"version": 1, "plugins": []}), encoding="utf-8")
+ (self.home / "receipts.json").write_text("[]", encoding="utf-8")
+ self.workspace = root / "ws"
+ self.workspace.mkdir()
+ self.env = {**os.environ, "IMG2_HOME": str(self.home)}
+
+ def run_node(self, *args):
+ return subprocess.run(
+ ["node", str(self.home / "harness" / "bin" / "img2.mjs"), *args],
+ env=self.env, capture_output=True, text=True,
+ )
+
+ def test_install_doctor_resolve_target_round_trips_with_a_clean_base_tree(self):
+ before = _git_status(ROOT)
+
+ added = self.run_node("add", "--link", str(PLUGIN_DIR))
+ self.assertEqual(added.returncode, 0, added.stdout + added.stderr)
+
+ doctor = self.run_node("doctor")
+ self.assertEqual(doctor.returncode, 0, doctor.stdout + doctor.stderr)
+ self.assertIn("ok (1 plugin", doctor.stdout)
+
+ capabilities = self.run_node("capabilities", "--from-kind", "sculpt-spec", "--to-kind", "echo", "--json")
+ self.assertEqual(capabilities.returncode, 0, capabilities.stderr)
+ answer = json.loads(capabilities.stdout)
+ self.assertEqual(len(answer["providers"]), 1)
+ self.assertEqual(answer["providers"][0]["plugin"], "sculpt-echo")
+
+ from workflow_state import new_state, save_state # noqa: E402 (sys.path set at module scope)
+
+ spec_path = self.workspace / "spec.json"
+ spec_path.write_text(
+ json.dumps({"targetId": "ci-roundtrip", "buildPasses": [{"id": "blockout"}], "componentTree": [{"id": "body"}]}),
+ encoding="utf-8",
+ )
+ state = new_state("ref.png", spec=str(spec_path))
+ for entry in state["checklist"]:
+ entry["status"] = "done"
+ entry["evidence"] = ["fixture"]
+ state["currentPass"] = "complete"
+ state["status"] = "complete"
+ state["currentStep"] = "complete"
+ save_state(self.workspace / ".img2threejs" / "state.json", state)
+
+ proc = subprocess.run(
+ [sys.executable, str(EMIT_TARGET), "--spec", str(spec_path), "--workspace", str(self.workspace), "--target", "echo"],
+ env=self.env, capture_output=True, text=True,
+ )
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ artifact = self.workspace / ".img2" / "artifacts" / "sculpt-echo" / "echo.json"
+ self.assertTrue(artifact.is_file())
+ self.assertEqual(json.loads(artifact.read_text(encoding="utf-8"))["passCount"], 1)
+
+ after = _git_status(ROOT)
+ self.assertEqual(before, after, "the round-trip modified the base repository's working tree")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_target_reference_conformance.py b/forge/tests/test_target_reference_conformance.py
new file mode 100644
index 0000000..78f30bb
--- /dev/null
+++ b/forge/tests/test_target_reference_conformance.py
@@ -0,0 +1,202 @@
+"""Reference-target conformance (task 3.10, `establish-the-emission-target-contract`, D8).
+
+Two honestly-scoped proofs that the base emitter conforms through the reference target
+(`--target threejs-ts`), never that production traverses it -- the no-target path stays in-process
+and unchanged (D2, D8).
+
+The envelope-parity test was written first, per the task, and failed exactly as predicted: `main()`
+overloads exit 2 between a structured BLOCKED envelope on stderr and plain argparse usage-error
+prose, and `emit_target.py` had no classifier at all. The lead's reconciliation: classify by
+envelope, not by exit code, with zero changes to `generate_threejs_factory.py` -- implemented in
+`emit_target._classify_reference_failure`. This module does not touch the emitter itself; only
+`emit_target.py`'s own parsing changed.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "forge"))
+sys.path.insert(0, str(ROOT / "forge" / "_shared"))
+sys.path.insert(0, str(ROOT / "forge" / "stage2_spec"))
+sys.path.insert(0, str(ROOT / "forge" / "stage3_build"))
+
+import generate_threejs_factory as generator # noqa: E402
+import emit_target # noqa: E402
+from targets import reference_target # noqa: E402
+from forge.tests.oracle_support import assert_replay_matches_oracle # noqa: E402
+
+FIXTURES = Path(__file__).resolve().parent / "fixtures"
+FROZEN_SPEC = FIXTURES / "reference_target_conformance_spec.json"
+ORACLE_TS = FIXTURES / "reference_target_oracle.ts"
+EMITTER = ROOT / "forge" / "stage3_build" / "generate_threejs_factory.py"
+FROZEN_PASS_ID = "blockout"
+
+
+def _oracle_is_not_degenerate() -> None:
+ """Anti-tamper guard: the recorded oracle must be a real, non-trivial TypeScript factory, not
+ an empty or truncated file that would make the byte comparison pass for the wrong reason."""
+ text = ORACLE_TS.read_text(encoding="utf-8")
+ assert len(text.splitlines()) > 100, "oracle fixture looks truncated"
+ assert "BoxGeometry" in text or "THREE." in text, "oracle fixture does not look like emitted Three.js"
+ assert "export function create" in text, "oracle fixture is missing its factory export"
+
+
+class ReferenceTargetOracleReplay(unittest.TestCase):
+ """Regression oracle: `generate_threejs_factory.py`'s own CLI output for this frozen
+ (spec, pass_id) must never silently drift. If it does, re-record the fixture in the same
+ commit as the change that caused it -- do not relax this assertion."""
+
+ def test_cli_replay_matches_the_frozen_oracle(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ out = Path(tmp) / "replay.ts"
+ assert_replay_matches_oracle(
+ self,
+ [
+ sys.executable, str(EMITTER), str(FROZEN_SPEC),
+ "--out", str(out), "--pass-id", FROZEN_PASS_ID, "--force",
+ ],
+ cwd=ROOT,
+ expected_path=ORACLE_TS,
+ out_path=out,
+ tamper_guard=_oracle_is_not_degenerate,
+ )
+
+
+class ReferenceTargetByteEquality(unittest.TestCase):
+ """D8's own conformance claim: the subprocess boundary changes nothing. The in-process
+ `generate()` call and the CLI's `--out` file must be byte-identical for the same
+ (spec, pass_id) -- this is what "the reference target conforms" actually means."""
+
+ def test_in_process_and_subprocess_agree_byte_for_byte(self) -> None:
+ spec = json.loads(FROZEN_SPEC.read_text(encoding="utf-8"))
+ in_process = generator.generate(spec, FROZEN_PASS_ID)
+ with tempfile.TemporaryDirectory() as tmp:
+ out = Path(tmp) / "subprocess.ts"
+ proc = subprocess.run(
+ [sys.executable, str(EMITTER), str(FROZEN_SPEC), "--out", str(out), "--pass-id", FROZEN_PASS_ID],
+ cwd=ROOT, capture_output=True, text=True,
+ )
+ self.assertEqual(proc.returncode, 0, proc.stderr)
+ via_subprocess = out.read_text(encoding="utf-8")
+ self.assertEqual(in_process, via_subprocess)
+
+
+class ReferenceTargetBoundsParity(unittest.TestCase):
+ """A stalled build trips the same first timeout a plugin target would. `_run_reference_target`
+ invokes the emitter through `run_bounded` -- the identical function `_run_plugin_target` uses --
+ so parity here is structural, not a parallel implementation to keep in sync by hand."""
+
+ def test_run_bounded_kills_a_stalled_command_and_names_the_bound(self) -> None:
+ with self.assertRaises(emit_target.EmitTargetError) as ctx:
+ emit_target.run_bounded(
+ [sys.executable, "-c", "import time; time.sleep(30)"],
+ cwd=ROOT, timeout=1, declared_env=[], target_kind="threejs-ts",
+ )
+ self.assertIn("timed out after 1s", str(ctx.exception))
+
+
+class ReferenceTargetKindParity(unittest.TestCase):
+ """The reference target's declared kind (`threejs-ts`) has no container prober, same as any
+ plugin declaring a kind the base cannot structurally check -- it gets the identical
+ existence/size/location verification level and the identical stated limit, not special
+ treatment for being base-owned."""
+
+ def test_unprobed_kind_gets_the_generic_verification_level(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ artifact = Path(tmp) / "model.ts"
+ artifact.write_text("// arbitrary", encoding="utf-8")
+ result = emit_target.verify_artifact(artifact, reference_target().artifact_kind)
+ self.assertEqual(result["level"], "existence+size+location")
+ self.assertIn("no further base quality warranty applies", result["note"])
+
+
+class ReferenceTargetEnvelopeParity(unittest.TestCase):
+ """Scenario (spec.md): "The socket's parser handles the reference target's failure envelope" --
+ WHEN the reference target is invoked against a spec that fails strict quality, THEN the
+ socket's envelope parser SHALL classify the outcome as a quality block, distinguishable from a
+ usage error.
+
+ Reconciliation (decided by the lead after this test first failed exactly as task 3.10
+ predicted): classify by envelope, not by exit code, with zero changes to
+ `generate_threejs_factory.py`. See `emit_target._classify_reference_failure`'s docstring for
+ the full reasoning; `main()`'s exit-2 overload between a BLOCKED envelope and plain argparse
+ usage-error prose remains the emitter's own pre-existing surface, untouched here.
+ """
+
+ def test_a_strict_quality_block_is_classified_as_a_quality_block_not_a_usage_error(self) -> None:
+ # A spec that is well-formed enough to have a completed pass (so emit_target.py's own
+ # "at least one completed build pass" precondition is satisfied) but that fails strict
+ # quality when the emitter's main() actually validates it -- exactly D8's scenario.
+ shallow_spec = {
+ "targetName": "Shallow",
+ "targetId": "shallow",
+ "schemaVersion": "2.1",
+ "materials": [{"id": "base", "name": "Base", "baseColor": "#808080"}],
+ "buildPasses": [{"id": "blockout", "acceptance": []}],
+ "reviewHistory": [
+ {
+ "passId": "blockout",
+ "action": "continue",
+ "visualEvidence": {"renderScreenshot": "x.png", "comparisonImage": "c.png"},
+ "aiVisionScore": 0.9,
+ "visualAcceptanceThreshold": 0.7,
+ }
+ ],
+ "suitability": "pass",
+ "coordinateFrame": {"front": "+Z", "up": "+Y", "scaleReference": "unit"},
+ "silhouette": {"boundingShape": "test", "symmetry": "bilateral"},
+ "proceduralStrategy": ["blockout"],
+ "componentTree": [
+ {
+ "id": "body", "name": "Body", "level": "macro", "role": "body",
+ "primitive": "ellipsoid", "topologyClass": "continuous-sculpt",
+ "topologyRationale": "test", "parent": None, "material": "base",
+ "dimensions": {"width": 1.0, "height": 0.6, "depth": 1.4, "units": "relative"},
+ "transform": {"position": [0, 0.5, 0], "rotation": [0, 0, 0]},
+ },
+ ],
+ }
+ with tempfile.TemporaryDirectory() as tmp:
+ workspace = Path(tmp) / "ws"
+ workspace.mkdir()
+ spec_path = workspace / "spec.json"
+ spec_path.write_text(json.dumps(shallow_spec), encoding="utf-8")
+ with self.assertRaises(emit_target.EmitTargetError) as ctx:
+ emit_target._run_reference_target(reference_target(), spec_path=spec_path, workspace=workspace)
+ self.assertEqual(ctx.exception.classification, "quality-block")
+ message = str(ctx.exception)
+ self.assertIn("strict-quality blocked", message)
+ # The cause list is surfaced verbatim, not flattened into an opaque summary.
+ self.assertIn("missing preSpecAssessment", message)
+ self.assertIn("refine-spec", message) # the BLOCKED report's own nextAction
+
+ def test_a_plain_usage_error_is_classified_as_error_not_a_quality_block(self) -> None:
+ # Unit-level, at the classifier itself: coaxing generate_threejs_factory.py's real CLI into
+ # its OTHER exit-2 shape (a bare argparse.error(), no JSON at all) requires a spec that
+ # passes strict-quality but fails structural validation -- an edge case not worth chasing
+ # through the full subprocess boundary when the classifier is the thing actually at risk.
+ usage_error_stderr = b"usage: generate_threejs_factory.py [-h] --out OUT spec\ngenerate_threejs_factory.py: error: spec validation failed: componentTree must be a non-empty array\n"
+ error = emit_target._classify_reference_failure(2, usage_error_stderr)
+ self.assertEqual(error.classification, "error")
+ self.assertIn("exited 2", str(error))
+ self.assertIn("spec validation failed", str(error))
+
+ def test_malformed_json_on_stderr_is_classified_as_error_never_a_pass(self) -> None:
+ # "A malformed envelope is an error, not a pass" (gate_runner.parse_verdict's own rule) --
+ # JSON that only half-parses, or parses but isn't a BLOCKED envelope, must not be mistaken
+ # for a quality block either.
+ half_json = b'{"status": "BLOCKED", "cause": [oops not valid json'
+ self.assertEqual(emit_target._classify_reference_failure(2, half_json).classification, "error")
+ wrong_shape = b'{"status": "ok", "somethingElse": true}'
+ self.assertEqual(emit_target._classify_reference_failure(2, wrong_shape).classification, "error")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_targets.py b/forge/tests/test_targets.py
new file mode 100644
index 0000000..cbb1f20
--- /dev/null
+++ b/forge/tests/test_targets.py
@@ -0,0 +1,249 @@
+"""forge/_shared/targets.py resolution tests (task 3.12, `establish-the-emission-target-contract`).
+
+Every test here pins IMG2_HOME to a temp/empty directory (the `test_search_specs.py:243` pattern) --
+the un-isolated registry read is exactly what turned PR #106's CI red.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "forge" / "_shared"))
+
+import targets # noqa: E402
+
+
+def _write_plugin(home: Path, plugin_id: str, *, capabilities, steps, requires=None, harness_version="0.5.0"):
+ (home / "harness").mkdir(parents=True, exist_ok=True)
+ (home / "harness" / "package.json").write_text(json.dumps({"version": harness_version}), encoding="utf-8")
+ plugin_dir = home / "plugins" / plugin_id
+ plugin_dir.mkdir(parents=True, exist_ok=True)
+ manifest = {
+ "schema": 1,
+ "name": plugin_id,
+ "version": "0.1.0",
+ "description": "test fixture plugin",
+ "capabilities": capabilities,
+ "requires": requires or {"harness": ">=0.1.0", "coreApi": 1},
+ }
+ (plugin_dir / "plugin.json").write_text(json.dumps(manifest), encoding="utf-8")
+ (plugin_dir / "steps.json").write_text(json.dumps(steps), encoding="utf-8")
+
+ registry_path = home / "plugins.json"
+ registry = {"plugins": []}
+ if registry_path.is_file():
+ registry = json.loads(registry_path.read_text(encoding="utf-8"))
+ registry["plugins"].append({
+ "id": plugin_id, "repo": f"img2threejs/{plugin_id}", "ref": "v0.1.0",
+ "resolvedSha": f"sha-{plugin_id}", "addedAt": "2026-01-01",
+ })
+ registry_path.write_text(json.dumps(registry), encoding="utf-8")
+
+
+def _target_step(kind: str, *, path: str, deterministic=True, timeout=None, version=1):
+ row = {
+ "id": f"emit-{kind}",
+ "command": "true",
+ "after": [],
+ "provides": {"version": version, "from": "sculpt-spec", "to": kind, "artifact": {"kind": kind, "path": path}},
+ "deterministic": deterministic,
+ }
+ if timeout is not None:
+ row["timeoutSeconds"] = timeout
+ return row
+
+
+class TargetsTestBase(unittest.TestCase):
+ def setUp(self):
+ self._tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self._tmp.cleanup)
+ self.home = Path(self._tmp.name) / "img2home-empty"
+ self.home.mkdir()
+
+
+class NoRegistryResolvesToTheReferenceTargetOnly(TargetsTestBase):
+ def test_empty_home_still_resolves_threejs_ts(self):
+ target = targets.resolve_target("threejs-ts", home=self.home)
+ self.assertIsNone(target.plugin_id)
+ self.assertEqual(target.kind, "threejs-ts")
+
+ def test_empty_home_refuses_an_unknown_kind_naming_it(self):
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("glb", home=self.home)
+ self.assertIn("glb", str(ctx.exception))
+
+
+class PluginTargetResolution(TargetsTestBase):
+ def test_installed_plugin_resolves_by_kind(self):
+ _write_plugin(
+ self.home, "echo-plugin",
+ capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path=".img2/artifacts/echo-plugin/echo.json")],
+ )
+ target = targets.resolve_target("echo", home=self.home)
+ self.assertEqual(target.plugin_id, "echo-plugin")
+ self.assertEqual(target.artifact_path, ".img2/artifacts/echo-plugin/echo.json")
+ self.assertEqual(target.resolved_sha, "sha-echo-plugin")
+ self.assertEqual(target.plugin_version, "0.1.0")
+
+ def test_two_plugins_providing_one_kind_is_refused_naming_both(self):
+ _write_plugin(
+ self.home, "echo-a", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path=".img2/artifacts/echo-a/echo.json")],
+ )
+ _write_plugin(
+ self.home, "echo-b", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path=".img2/artifacts/echo-b/echo.json")],
+ )
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", home=self.home)
+ message = str(ctx.exception)
+ self.assertIn("echo-a", message)
+ self.assertIn("echo-b", message)
+
+ def test_plugin_flag_disambiguates(self):
+ _write_plugin(
+ self.home, "echo-a", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path=".img2/artifacts/echo-a/echo.json")],
+ )
+ _write_plugin(
+ self.home, "echo-b", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path=".img2/artifacts/echo-b/echo.json")],
+ )
+ target = targets.resolve_target("echo", plugin="echo-b", home=self.home)
+ self.assertEqual(target.plugin_id, "echo-b")
+
+ def test_a_missing_plugin_flag_target_is_refused_naming_it(self):
+ _write_plugin(
+ self.home, "echo-a", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path=".img2/artifacts/echo-a/echo.json")],
+ )
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", plugin="not-installed", home=self.home)
+ self.assertIn("not-installed", str(ctx.exception))
+
+ def test_capability_edge_with_no_matching_step_is_refused(self):
+ _write_plugin(
+ self.home, "half-declared", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[],
+ )
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", home=self.home)
+ self.assertIn("no installed plugin provides", str(ctx.exception))
+
+ def test_step_provides_a_kind_with_no_manifest_edge_is_refused(self):
+ _write_plugin(
+ self.home, "mismatched", capabilities=[{"from": "sculpt-spec", "to": "other-kind"}],
+ steps=[_target_step("echo", path=".img2/artifacts/mismatched/echo.json")],
+ )
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", home=self.home)
+ self.assertIn("no matching manifest capability edge", str(ctx.exception))
+
+ def test_provides_version_newer_than_max_is_refused(self):
+ _write_plugin(
+ self.home, "too-new", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path=".img2/artifacts/too-new/echo.json", version=99)],
+ )
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", home=self.home)
+ self.assertIn("newer than this base reads", str(ctx.exception))
+
+ def test_escaping_artifact_path_is_refused(self):
+ _write_plugin(
+ self.home, "escaper", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path="../../etc/passwd")],
+ )
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", home=self.home)
+ self.assertIn("must resolve under", str(ctx.exception))
+
+ def test_missing_deterministic_declaration_is_refused(self):
+ _write_plugin(
+ self.home, "no-determinism", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[{
+ "id": "emit-echo", "command": "true", "after": [],
+ "provides": {"version": 1, "from": "sculpt-spec", "to": "echo",
+ "artifact": {"kind": "echo", "path": ".img2/artifacts/no-determinism/echo.json"}},
+ }],
+ )
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", home=self.home)
+ self.assertIn("deterministic", str(ctx.exception))
+
+ def test_harness_version_mismatch_is_refused(self):
+ _write_plugin(
+ self.home, "too-strict", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path=".img2/artifacts/too-strict/echo.json")],
+ requires={"harness": ">=99.0.0", "coreApi": 1},
+ )
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", home=self.home)
+ self.assertIn("requires harness", str(ctx.exception))
+
+ def test_core_api_mismatch_is_refused(self):
+ _write_plugin(
+ self.home, "wrong-core-api", capabilities=[{"from": "sculpt-spec", "to": "echo"}],
+ steps=[_target_step("echo", path=".img2/artifacts/wrong-core-api/echo.json")],
+ requires={"harness": ">=0.1.0", "coreApi": 2},
+ )
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", home=self.home)
+ self.assertIn("coreApi", str(ctx.exception))
+
+ def test_non_sculpt_spec_capabilities_are_ignored(self):
+ # A plugin providing a capability from an unrelated kind (e.g. image -> threejs-code, the
+ # old hello-cube shape) is not a target and must not appear in target resolution at all.
+ _write_plugin(
+ self.home, "not-a-target", capabilities=[{"from": "image", "to": "threejs-code"}],
+ steps=[{"id": "step", "command": "true", "after": []}],
+ )
+ with self.assertRaises(targets.TargetResolutionError):
+ targets.resolve_target("threejs-code", home=self.home)
+
+
+class MalformedRegistryFailsLoudOnlyWhenAskedFor(TargetsTestBase):
+ """D5: fail-loud is scoped to selection time. `resolve_target` (called only when --target was
+ requested) DOES read a malformed registry and must fail loud naming the problem -- this module
+ never silently swallows it. The no-target path never calling into this module at all is
+ emit_target.py's own responsibility, tested in test_emit_target.py."""
+
+ def test_malformed_plugins_json_fails_loud_when_a_target_is_requested(self):
+ (self.home / "plugins.json").write_text("not valid json {{{", encoding="utf-8")
+ with self.assertRaises(targets.TargetResolutionError) as ctx:
+ targets.resolve_target("echo", home=self.home)
+ self.assertIn("not valid JSON", str(ctx.exception))
+
+
+class PathEscapesMirrorsTheHarness(unittest.TestCase):
+ """Mirrors img2.mjs's artifactPathEscapes -- the doctor-time and runtime checks must never
+ disagree about what escapes."""
+
+ def test_a_conforming_path_does_not_escape(self):
+ self.assertFalse(targets.path_escapes(".img2/artifacts/echo/echo.json", "echo"))
+
+ def test_an_absolute_path_escapes(self):
+ self.assertTrue(targets.path_escapes("/etc/passwd", "echo"))
+
+ def test_a_tilde_path_escapes(self):
+ self.assertTrue(targets.path_escapes("~/echo.json", "echo"))
+
+ def test_a_dotdot_escape_is_refused(self):
+ self.assertTrue(targets.path_escapes("../../etc/passwd", "echo"))
+
+ def test_another_plugins_prefix_escapes(self):
+ self.assertTrue(targets.path_escapes(".img2/artifacts/other-plugin/echo.json", "echo"))
+
+ def test_a_bare_filename_with_no_prefix_escapes(self):
+ # The full workspace-relative prefix is part of the declared value itself (D6) -- a bare
+ # filename is not silently joined under the prefix, it is refused.
+ self.assertTrue(targets.path_escapes("echo.json", "echo"))
+
+
+if __name__ == "__main__":
+ unittest.main()