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.

v1.3: Upgrade quality and efficiency (#14)

Hoài Nhớ2c78038d315e
diff --git a/.gitignore b/.gitignore
index 0523447..54d82d3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,3 +11,9 @@ __pycache__/
# Scratch / generated review artifacts (keep committed demos in assets/)
*.tmp
+
+# Local-only planning docs — never committed (feature work is committed, plans are not)
+docs/PLAN_*.md
+
+# OMC planning/team state — local orchestration artifacts, never part of a release
+.omc/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7cad833..35790af 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,65 @@ All notable changes to **img2threejs** are documented here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.3.0] — 2026-07-22
+
+The "quality & efficiency" line: a deterministic-first review harness (Divine Eye), stronger
+input integrity, geometry-truth gates, and reference-grounded texture/material analysis.
+
+### Added — Plan 1.3 (Phases 1–7)
+- **Input integrity** — reference admission (`check_reference_admission.py`), intake-correctness
+ cross-check (`check_intake_correctness.py`), property auto-binding, shared pHash.
+- **Geometry truth** — curve-sweep (F.6), flatness gate (G.1), Blum lathe-profile derivation.
+- **Divine Eye** — deterministic multi-signal ensemble (`divine_eye.py`): IoU/scale hard gates;
+ proportion / symmetry-parity / pHash / SSIM / edge / blowout / flat / tonal-parity soft signals;
+ self-uncertainty `probe` routing.
+- **Multi-angle** — degenerate-view detection (`diagnose_render_multi_angle.py`) with reference-free
+ self-consistency; auto-framing.
+- **Eye judgment layers** — gated VLM gate (`vlm_gate.py`), per-feature verification (§3.8),
+ bounded stop policy (§3.6), calibration harness (report-only + separation check).
+- **Efficiency** — per-module codegen cache (§3.7 neighbor invalidation).
+- **Presentation** — reference-conditional post-fx (DOF/bloom) strictly off the evaluation path.
+
+### Added — session capability work (folded into 1.3)
+- **Texture-finish analysis** — `stage1_intake/analyze_texture.py`: classifies finish
+ (gem-metal / gemstone / painted-metal / worn-composite / brushed-steel / plastic) and writes
+ doc-grounded MeshPhysicalMaterial scalars; `grimoire/build/threejs_texture_reference.md`.
+- **Objectness (OSIM-lite)** — `stage4_review/objectness.py`: pure-stdlib HOG-like descriptor +
+ cosine similarity; wired into Divine Eye as a soft signal + reconstruction-mode rescue.
+- **`ground-blade` primitive** — lofted beveled cross-section (primary bevel + swedge/false edge)
+ in the generator + validator whitelist.
+- **Color-gate fix** — `diagnose_render.py` `color_is_gated(pass_id)` (color hard-fail only from
+ the material pass onward, so clay blockouts don't false-fail).
+
+### Added — reconstruction-fidelity upgrades (folded into 1.3)
+- **Reference-grounded gradient stops** — `stage1_intake/extract_gradient_stops.py`: foreground-masked
+ per-band median sampling extracts a material's true gradient from the reference (kills hand-guessed
+ STOPS), names hue zones, and flags blue-leaning violet/blue stops (`B > R`) as `blue-collapse`
+ (collapses to blue under tone-mapping) with a magenta-lean suggested correction.
+- **`candy-coat` finish class** — `stage1_intake/analyze_texture.py`: an anodized/PVD/doppler
+ dielectric-led recipe (metalness 0.35 / clearcoat 0.60 / envMapIntensity 0.70) so a saturated
+ coloured coat keeps its hue instead of the environment stealing it; chrome-specular stays
+ `gem-metal`, bright-clean stays `gemstone`. Plus a `paletteHueRisk` hue-survival annotation.
+- **CIEDE2000 colour math** — `_shared/color_metrics.py`: sRGB→CIELAB + full ΔE00, verified against
+ the canonical Sharma test pairs.
+- **Colour-aware Divine Eye signals (report-only)** — `hue_zone_parity` (per-band CIEDE2000 along the
+ axis; catches "purple rendered blue" that luma/structure signals miss) and `specular_wash`
+ (saturation-decay + hue-drift-toward-cyan detector). Both ship report-only (no ensemble weight)
+ until calibrated, so they never silently move a verdict.
+- **InstancedMesh emission** — repetition systems now emit one `THREE.InstancedMesh` (single
+ draw-call) instead of a per-instance `Mesh` clone loop; the `instanced-cluster` primitive resolves
+ to its base geometry instead of failing.
+- **`ground-blade` UV fix** — blade UVs now span the geometry's actual Y bounds instead of a
+ hardcoded range, so an off-origin blade no longer clamps every face to the bright spine-rim row
+ (the flat "one colour" / white-tip bug); the length gradient reads correctly.
+- **Dep-free cutouts** — `extrude` supports `THREE.Shape.holes` + an `ovalLoop` helper (e.g. a
+ wire-cutter oval hole) with no CSG dependency.
+
+### Notes
+- Pure Python 3.10+ stdlib in `forge/` (no pip installs). 20/20 forge test suites green.
+- Grimoire lessons updated: shading realism (hue-survival under tone-mapping; reference beats prose),
+ geometry patterns, self-correction.
+
## [1.2.0] - 2026-07-21
**Theme: Humanoid character generator.** Characters and hybrid subjects become
diff --git a/SKILL.md b/SKILL.md
index bd5c349..08788aa 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -2,7 +2,7 @@
name: img2threejs
description: Turn an object or character reference image into a quality-gated, animation-ready procedural Three.js model built in code. Use for image-to-3D reconstruction, detail-accurate object rebuilds, stylized/likeness-maximized human characters, sculpt specs, and staged code generation.
license: MIT
-version: 1.2.0
+version: 1.3.0
---
# img2threejs — Image to procedural Three.js
@@ -66,9 +66,20 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i
Replace generic starter `featureReviewTargets` with the object's real identity-defining
systems (≤5 critical, ≤3 important per pass); for characters add `anatomy-proportion`,
`face-landmark-placement`, `pose-silhouette`, `outfit-and-palette`. Use 3D-graphics terms only
- (`grimoire/glossary/3d_vocabulary.md`), never "nice/smooth/shiny".
-4. When material fidelity matters and a source image exists, extract reference PBR evidence per crop:
- `forge/stage1_intake/extract_pbr_evidence.py <crop> --out-dir <dir> --material-id <id> --target-threshold 0.7`.
+ (`grimoire/glossary/3d_vocabulary.md`), never "nice/smooth/shiny". Classify every component's
+ `topologyClass`/`topologyRationale` per `grimoire/intake/surface_topology.md` before picking a
+ `primitive` — this is what prevents a continuous organic form from being picked as a box.
+4. When material fidelity matters and a source image exists, analyze each material's **finish** then
+ extract reference PBR evidence, both per crop (crop the correct region — verify the crop is on the
+ part you think it is):
+ - `forge/stage1_intake/analyze_texture.py <crop> --spec spec.json --material-id <id> --in-place`
+ classifies the finish (`gem-metal | gemstone | painted-metal | worn-composite | brushed-steel |
+ plastic`), extracts the gradient palette, and writes doc-grounded MeshPhysicalMaterial scalars
+ (metalness/roughness/clearcoat/transmission/ior/anisotropy/envMapIntensity) onto the material.
+ Recipes + Three.js texture/PBR rules (colorSpace, CanvasTexture/DataTexture, height→normal) live
+ in `grimoire/build/threejs_texture_reference.md`. Rule of thumb: **solid albedo for flat paint,
+ real reference crop for patterned finishes** (doppler/quartz/hydro-dip/camo).
+ - `forge/stage1_intake/extract_pbr_evidence.py <crop> --out-dir <dir> --material-id <id> --target-threshold 0.7`.
Confidence < 0.7 is a stop/refine-input signal, not a pass. It is inference, not inverse rendering.
5. Validate, then strict-validate before generating code:
`forge/stage2_spec/validate_sculpt_spec.py object-sculpt-spec.json` then `--strict-quality`.
@@ -89,7 +100,26 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that i
## Gates (do not skip)
-- **Suitability**: pass / conditional / reject before any planning. `grimoire/intake/validation_rubric.md`.
+- **Suitability + reference integrity**: pass / conditional / reject before any planning
+ (`grimoire/intake/validation_rubric.md`), AND every reference admitted via
+ `forge/stage1_intake/check_reference_admission.py` (rejects empty/fragmented/tiny/duplicate/
+ undecodable refs with a reason). Intake understanding cross-checked by
+ `forge/stage1_intake/check_intake_correctness.py` (halts on a confident class contradiction).
+- **Divine Eye (the harness heart) — deterministic-first, model-last**: the render evaluator is
+ `forge/stage4_review/divine_eye.py` — a zero-token multi-signal ensemble (IoU/scale HARD gates;
+ proportion/symmetry-parity/pHash/SSIM/edge/blowout/flat/tonal-parity soft) with self-uncertainty
+ (`probe` on signal disagreement) and deterministic routing (`continue`/`refine-spec`/`refine-code`/
+ `probe`). The VLM (`forge/stage4_review/vlm_gate.py`) is a gated, calibrated, cross-checked
+ last layer: **never consulted on a hard-gate failure**, multi-sample-voted, and can rescue a
+ soft near-threshold reject but never grant past a hard geometric failure.
+- **Multi-angle or it didn't happen**: a non-planar form must hold from ≥2 camera angles.
+ `forge/stage4_review/diagnose_render_multi_angle.py` flags `degenerate-view` when an orbited
+ silhouette collapses (a flat plane faking a volume). Orbit angles use reference-free
+ self-consistency — never scored against a reference angle the photo doesn't cover.
+- **Bounded correction loop (token-burn safety)**: `forge/stage4_review/correction_loop.py`
+ guarantees termination (success/repeated-defect/oscillation/plateau/hard-ceiling), escalating to
+ `request-input` — never a silent infinite burn.
+- **Tier 1 (legacy, still valid)**: "Tier 2 (AI-vision) never runs against a render that has not passed Tier 1." Run `forge/stage4_review/diagnose_render.py` (silhouette IoU/proportion/symmetry/per-part color) and record it (`--spec ... --in-place`) before requesting a comparison sheet; `orchestrate_passes.py check` refuses otherwise.
- **Pre-spec / strict-quality**: blocks code gen until the spec is deep enough for its contract.
- **Screenshot feedback**: `continue` is allowed only with a render + comparison sheet + global
AI-vision score ≥ threshold (default 0.7) AND every critical feature ≥ its own threshold.
diff --git a/forge/_shared/artifact_cache.py b/forge/_shared/artifact_cache.py
new file mode 100644
index 0000000..760d660
--- /dev/null
+++ b/forge/_shared/artifact_cache.py
@@ -0,0 +1,54 @@
+"""Lightweight hash-based artifact cache (Plan 1.3 Workstream E).
+
+Cache key = crop file content hash + the extracting script's OWN source-file
+hash, both computed automatically at every run — no manually-maintained
+version string exists to forget bumping (closes Risk R3: a cache keyed on a
+human-maintained version constant will eventually serve stale results after
+someone edits the algorithm without remembering to bump it).
+
+This is NOT full module/spec-hash reuse (no dependency graph, no partial-
+object hashing) — just "don't redo expensive-ish work on unchanged inputs."
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from pathlib import Path
+from typing import Any
+
+
+def file_sha256(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+def cache_key(crop_path: Path, script_path: Path) -> str:
+ return f"{file_sha256(crop_path)}:{file_sha256(script_path)[:12]}"
+
+
+def manifest_path_for(directory: Path, name: str) -> Path:
+ return directory / ".cache" / name
+
+
+def load_manifest(path: Path) -> dict[str, Any]:
+ if not path.exists():
+ return {}
+ try:
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def save_manifest(path: Path, manifest: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+
+
+def get_cached(manifest_path: Path, key: str) -> dict[str, Any] | None:
+ return load_manifest(manifest_path).get(key)
+
+
+def put_cached(manifest_path: Path, key: str, value: dict[str, Any]) -> None:
+ manifest = load_manifest(manifest_path)
+ manifest[key] = value
+ save_manifest(manifest_path, manifest)
diff --git a/forge/_shared/color_metrics.py b/forge/_shared/color_metrics.py
new file mode 100644
index 0000000..a13dd18
--- /dev/null
+++ b/forge/_shared/color_metrics.py
@@ -0,0 +1,107 @@
+#!/usr/bin/env python3
+"""Perceptual colour math for the harness — pure stdlib (sRGB→CIELAB + CIEDE2000).
+
+Canonical sRGB→CIELAB and the full CIEDE2000 (ΔE00) difference, used by the Divine Eye
+hue-zone signal and any per-region colour check. CIEDE2000 corrects CIELAB's non-uniformity
+(the ~275° blue region especially — exactly where the M9 violet→blue failure lives) via the
+R_T hue-rotation term, so it is the right metric for "is this the same hue zone?".
+
+Verified against Sharma et al.'s published CIEDE2000 test pairs (see test_color_metrics.py).
+"""
+from __future__ import annotations
+
+import math
+
+# D65 reference white (2° observer)
+_XN, _YN, _ZN = 95.047, 100.0, 108.883
+
+
+def _lin(c: float) -> float:
+ c /= 255.0
+ return c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4
+
+
+def srgb_to_lab(rgb: tuple[int, int, int]) -> tuple[float, float, float]:
+ r, g, b = _lin(rgb[0]), _lin(rgb[1]), _lin(rgb[2])
+ # linear sRGB → XYZ (D65)
+ x = (r * 0.4124 + g * 0.3576 + b * 0.1805) * 100.0
+ y = (r * 0.2126 + g * 0.7152 + b * 0.0722) * 100.0
+ z = (r * 0.0193 + g * 0.1192 + b * 0.9505) * 100.0
+
+ def f(t: float) -> float:
+ return t ** (1.0 / 3.0) if t > 0.008856 else (7.787 * t + 16.0 / 116.0)
+
+ fx, fy, fz = f(x / _XN), f(y / _YN), f(z / _ZN)
+ return (116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz))
+
+
+def ciede2000(lab1: tuple[float, float, float], lab2: tuple[float, float, float]) -> float:
+ """Full CIEDE2000 colour difference (kL=kC=kH=1). Returns ΔE00."""
+ l1, a1, b1 = lab1
+ l2, a2, b2 = lab2
+ c1 = math.hypot(a1, b1)
+ c2 = math.hypot(a2, b2)
+ c_bar = (c1 + c2) / 2.0
+ g = 0.5 * (1.0 - math.sqrt(c_bar ** 7 / (c_bar ** 7 + 25.0 ** 7))) if c_bar > 0 else 0.0
+ a1p = (1.0 + g) * a1
+ a2p = (1.0 + g) * a2
+ c1p = math.hypot(a1p, b1)
+ c2p = math.hypot(a2p, b2)
+
+ def hp(ap: float, bp: float) -> float:
+ if ap == 0.0 and bp == 0.0:
+ return 0.0
+ deg = math.degrees(math.atan2(bp, ap))
+ return deg + 360.0 if deg < 0 else deg
+
+ h1p = hp(a1p, b1)
+ h2p = hp(a2p, b2)
+
+ dLp = l2 - l1
+ dCp = c2p - c1p
+ if c1p * c2p == 0.0:
+ dhp = 0.0
+ elif abs(h2p - h1p) <= 180.0:
+ dhp = h2p - h1p
+ elif h2p - h1p > 180.0:
+ dhp = h2p - h1p - 360.0
+ else:
+ dhp = h2p - h1p + 360.0
+ dHp = 2.0 * math.sqrt(c1p * c2p) * math.sin(math.radians(dhp) / 2.0)
+
+ Lp_bar = (l1 + l2) / 2.0
+ Cp_bar = (c1p + c2p) / 2.0
+ if c1p * c2p == 0.0:
+ hp_bar = h1p + h2p
+ elif abs(h1p - h2p) <= 180.0:
+ hp_bar = (h1p + h2p) / 2.0
+ elif h1p + h2p < 360.0:
+ hp_bar = (h1p + h2p + 360.0) / 2.0
+ else:
+ hp_bar = (h1p + h2p - 360.0) / 2.0
+
+ t = (
+ 1.0
+ - 0.17 * math.cos(math.radians(hp_bar - 30.0))
+ + 0.24 * math.cos(math.radians(2.0 * hp_bar))
+ + 0.32 * math.cos(math.radians(3.0 * hp_bar + 6.0))
+ - 0.20 * math.cos(math.radians(4.0 * hp_bar - 63.0))
+ )
+ d_theta = 30.0 * math.exp(-(((hp_bar - 275.0) / 25.0) ** 2))
+ rc = 2.0 * math.sqrt(Cp_bar ** 7 / (Cp_bar ** 7 + 25.0 ** 7)) if Cp_bar > 0 else 0.0
+ sl = 1.0 + (0.015 * (Lp_bar - 50.0) ** 2) / math.sqrt(20.0 + (Lp_bar - 50.0) ** 2)
+ sc = 1.0 + 0.045 * Cp_bar
+ sh = 1.0 + 0.015 * Cp_bar * t
+ rt = -math.sin(math.radians(2.0 * d_theta)) * rc
+
+ return math.sqrt(
+ (dLp / sl) ** 2
+ + (dCp / sc) ** 2
+ + (dHp / sh) ** 2
+ + rt * (dCp / sc) * (dHp / sh)
+ )
+
+
+def delta_e_rgb(rgb1: tuple[int, int, int], rgb2: tuple[int, int, int]) -> float:
+ """Convenience: CIEDE2000 between two sRGB colours."""
+ return ciede2000(srgb_to_lab(rgb1), srgb_to_lab(rgb2))
diff --git a/forge/_shared/image_hash.py b/forge/_shared/image_hash.py
new file mode 100644
index 0000000..92684f3
--- /dev/null
+++ b/forge/_shared/image_hash.py
@@ -0,0 +1,112 @@
+"""Perceptual image hashing (DCT-based pHash), pure Python stdlib.
+
+Plan 1.3. Shared by:
+ - reference-admission duplicate detection (stage1_intake/check_reference_admission.py, §4.5.2)
+ - the Divine Eye's coarse "same-thing?" pre-gate signal (stage4_review/divine_eye.py, §3.1)
+
+Classic pHash: grayscale -> downsample to N×N (default 32) -> 2D DCT-II -> keep the
+top-left low-frequency K×K block (default 8, excluding the DC term for robustness to
+overall brightness) -> hash bit = coefficient > median. Produces a 64-bit integer whose
+Hamming distance approximates perceptual similarity and is invariant to scale, small
+blur, and uniform brightness shifts — exactly the invariances a duplicate/near-duplicate
+check wants. No PIL/numpy.
+"""
+
+from __future__ import annotations
+
+import math
+
+_DCT_CACHE: dict[int, list[list[float]]] = {}
+
+
+def _dct_matrix(n: int) -> list[list[float]]:
+ """Cached DCT-II basis matrix M where out = M @ in."""
+ cached = _DCT_CACHE.get(n)
+ if cached is not None:
+ return cached
+ matrix: list[list[float]] = []
+ factor = math.pi / (2.0 * n)
+ for k in range(n):
+ scale = math.sqrt(1.0 / n) if k == 0 else math.sqrt(2.0 / n)
+ row = [scale * math.cos((2 * i + 1) * k * factor) for i in range(n)]
+ matrix.append(row)
+ _DCT_CACHE[n] = matrix
+ return matrix
+
+
+def _dct_2d(block: list[list[float]]) -> list[list[float]]:
+ """Separable 2D DCT-II of a square matrix."""
+ n = len(block)
+ m = _dct_matrix(n)
+ # rows: temp = M @ block
+ temp = [[sum(m[k][i] * block[i][j] for i in range(n)) for j in range(n)] for k in range(n)]
+ # cols: out = temp @ M^T
+ out = [[sum(temp[k][j] * m[l][j] for j in range(n)) for l in range(n)] for k in range(n)]
+ return out
+
+
+def to_grayscale_downsampled(
+ width: int,
+ height: int,
+ pixels: list[tuple[int, int, int, int]],
+ size: int = 32,
+) -> list[list[float]]:
+ """Box-average downsample of the luminance channel to size×size (Rec.709 luma)."""
+ if width <= 0 or height <= 0 or not pixels:
+ return [[0.0] * size for _ in range(size)]
+ out = [[0.0] * size for _ in range(size)]
+ counts = [[0] * size for _ in range(size)]
+ for idx, (r, g, b, _a) in enumerate(pixels):
+ x = idx % width
+ y = idx // width
+ if y >= height:
+ break
+ sx = min(size - 1, x * size // width)
+ sy = min(size - 1, y * size // height)
+ out[sy][sx] += 0.2126 * r + 0.7152 * g + 0.0722 * b
+ counts[sy][sx] += 1
+ for sy in range(size):
+ for sx in range(size):
+ c = counts[sy][sx]
+ if c:
+ out[sy][sx] /= c
+ return out
+
+
+def phash(gray: list[list[float]], hash_size: int = 8) -> int:
+ """64-bit pHash (for hash_size=8) from a square grayscale matrix (side ≥ hash_size)."""
+ n = len(gray)
+ if n < hash_size:
+ raise ValueError(f"grayscale side {n} smaller than hash_size {hash_size}")
+ coeffs = _dct_2d(gray)
+ low = [coeffs[k][l] for k in range(hash_size) for l in range(hash_size)]
+ # Exclude the DC term (index 0) from the median so overall brightness doesn't dominate.
+ ac = low[1:]
+ ordered = sorted(ac)
+ mid = len(ordered) // 2
+ median = ordered[mid] if len(ordered) % 2 else 0.5 * (ordered[mid - 1] + ordered[mid])
+ bits = 0
+ for i, value in enumerate(low):
+ bits <<= 1
+ if value > median:
+ bits |= 1
+ return bits
+
+
+def phash_from_image(
+ width: int,
+ height: int,
+ pixels: list[tuple[int, int, int, int]],
+ hash_size: int = 8,
+ img_size: int = 32,
+) -> int:
+ return phash(to_grayscale_downsampled(width, height, pixels, img_size), hash_size)
+
+
+def hamming(a: int, b: int) -> int:
+ return bin(a ^ b).count("1")
+
+
+def normalized_similarity(a: int, b: int, bits: int = 64) -> float:
+ """1.0 = identical hash, 0.0 = maximally different. Used as a [0,1] agreement score."""
+ return 1.0 - hamming(a, b) / bits
diff --git a/forge/stage1_intake/analyze_texture.py b/forge/stage1_intake/analyze_texture.py
new file mode 100644
index 0000000..2e04fbc
--- /dev/null
+++ b/forge/stage1_intake/analyze_texture.py
@@ -0,0 +1,250 @@
+#!/usr/bin/env python3
+"""Reference texture analysis → finishClass + PBR recipe (Plan 1.3 texture upgrade).
+
+Pure stdlib. Classifies a reference crop's *finish* from image statistics and emits a
+material recipe (MeshPhysicalMaterial scalars + palette + procedural hints) that
+`generate_threejs_factory.py`'s procedural texture generator consumes. This replaces the
+per-object hand-crafting of albedo/roughness maps with a repeatable analysis→recipe step.
+
+finishClass ∈ { gem-metal, gemstone, painted-metal, worn-composite, brushed-steel, plastic }
+Recipe scalars grounded in grimoire/build/threejs_texture_reference.md (notebooklm/three.js docs).
+
+CLI: analyze_texture.py <crop.png> [--json]
+API: analyze(path) -> dict
+"""
+from __future__ import annotations
+
+import argparse
+import colorsys
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
+
+# MeshPhysicalMaterial scalar presets per finish (see grimoire threejs_texture_reference.md)
+RECIPES: dict[str, dict[str, Any]] = {
+ "gem-metal": {"metalness": 0.75, "roughness": 0.14, "clearcoat": 0.60, "clearcoatRoughness": 0.06, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 1.3, "anisotropy": 0.0, "procedural": "gradient-smoke"},
+ # candy-coat: anodized / PVD / pigment-dominant doppler coat. Dielectric-led (low metalness) +
+ # clearcoat + trimmed envMapIntensity so the environment reflection can't steal the hue — the
+ # exact counter-recipe that fixed the M9 Doppler blue-wash (grimoire/feedback/shading_realism.md).
+ "candy-coat": {"metalness": 0.35, "roughness": 0.18, "clearcoat": 0.60, "clearcoatRoughness": 0.15, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 0.7, "anisotropy": 0.0, "procedural": "gradient-smoke"},
+ "gemstone": {"metalness": 0.0, "roughness": 0.05, "clearcoat": 1.00, "clearcoatRoughness": 0.0, "transmission": 0.9, "ior": 1.54, "envMapIntensity": 1.0, "anisotropy": 0.0, "procedural": "gradient-smoke"},
+ "painted-metal": {"metalness": 0.0, "roughness": 0.5, "clearcoat": 1.00, "clearcoatRoughness": 0.05, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 1.0, "anisotropy": 0.0, "procedural": "flat-clearcoat"},
+ "worn-composite": {"metalness": 0.0, "roughness": 0.9, "clearcoat": 0.0, "clearcoatRoughness": 0.0, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 0.5, "anisotropy": 0.0, "procedural": "mottle"},
+ "brushed-steel": {"metalness": 1.0, "roughness": 0.35, "clearcoat": 0.0, "clearcoatRoughness": 0.0, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 1.0, "anisotropy": 1.0, "procedural": "brushed"},
+ "plastic": {"metalness": 0.05, "roughness": 0.6, "clearcoat": 0.2, "clearcoatRoughness": 0.3, "transmission": 0.0, "ior": 1.5, "envMapIntensity": 0.7, "anisotropy": 0.0, "procedural": "flat-clearcoat"},
+}
+
+N = 64 # downsample grid for stats
+
+
+def _sample(pixels, w, h, mask):
+ minx = miny = 1 << 30
+ maxx = maxy = -1
+ for y in range(h):
+ r = y * w
+ for x in range(w):
+ if mask[r + x]:
+ minx = min(minx, x); maxx = max(maxx, x)
+ miny = min(miny, y); maxy = max(maxy, y)
+ if maxx < 0:
+ minx, miny, maxx, maxy = 0, 0, w - 1, h - 1
+ bw = max(1, maxx - minx + 1); bh = max(1, maxy - miny + 1)
+ grid = []
+ for j in range(N):
+ sy = min(h - 1, miny + j * bh // N)
+ for i in range(N):
+ sx = min(w - 1, minx + i * bw // N)
+ p = pixels[sy * w + sx]
+ grid.append((p[0], p[1], p[2]))
+ return grid
+
+
+def _lum(p):
+ return (p[0] * 30 + p[1] * 59 + p[2] * 11) / 100.0
+
+
+def analyze(path: str | Path) -> dict[str, Any]:
+ w, h, pixels, _ = load_image(Path(path))
+ mask, _diag, _warn = build_foreground_mask(w, h, pixels)
+ g = _sample(pixels, w, h, mask)
+ n = len(g)
+ lums = [_lum(p) for p in g]
+ mean_lum = sum(lums) / n
+
+ # saturation + hue (HSV) — chromatic vs neutral, and hue SPREAD (gem shifts hue, paint doesn't)
+ hsv = [colorsys.rgb_to_hsv(p[0] / 255, p[1] / 255, p[2] / 255) for p in g]
+ sats = [s for _h, s, _v in hsv]
+ mean_sat = sum(sats) / n
+ # circular hue spread (robust to wraparound + outliers): 1 - mean resultant length,
+ # saturation-weighted. ~0 for a single paint hue, larger for a blue→purple gem shift.
+ import math as _m
+ sc = ss = wsum = 0.0
+ for _h, s, _v in hsv:
+ if s > 0.2:
+ sc += s * _m.cos(2 * _m.pi * _h)
+ ss += s * _m.sin(2 * _m.pi * _h)
+ wsum += s
+ hue_spread = (1.0 - _m.hypot(sc, ss) / wsum) if wsum > 2.0 else 0.0
+
+ # luminance gradient along rows vs cols (a strong axis gradient = doppler-like finish)
+ row_means = [sum(lums[j * N:(j + 1) * N]) / N for j in range(N)]
+ col_means = [sum(lums[i + j * N] for j in range(N)) / N for i in range(N)]
+ horiz_grad = (max(col_means) - min(col_means)) / 255.0
+ vert_grad = (max(row_means) - min(row_means)) / 255.0
+ gradient_strength = max(horiz_grad, vert_grad)
+ gradient_axis = "horizontal" if horiz_grad >= vert_grad else "vertical"
+
+ # local mottle: mean abs difference to 4-neighbours (worn/patchy surfaces are high)
+ diffs = 0.0
+ cnt = 0
+ for j in range(1, N - 1):
+ for i in range(1, N - 1):
+ c = lums[j * N + i]
+ diffs += abs(c - lums[j * N + i - 1]) + abs(c - lums[j * N + i + 1])
+ cnt += 2
+ mottle = (diffs / cnt) / 255.0 if cnt else 0.0
+
+ # directional streaks: horizontal high-freq >> vertical high-freq ⇒ brushed metal
+ hf_h = sum(abs(lums[j * N + i] - lums[j * N + i - 1]) for j in range(N) for i in range(1, N)) / (N * (N - 1))
+ hf_v = sum(abs(lums[j * N + i] - lums[(j - 1) * N + i]) for j in range(1, N) for i in range(N)) / (N * (N - 1))
+ streak_ratio = hf_h / (hf_v + 1e-6)
+ anisotropy = max(streak_ratio, 1.0 / (streak_ratio + 1e-6)) # directional either axis
+
+ # specular fraction → metalness proxy
+ spec_frac = sum(1 for lv in lums if lv > 235) / n
+
+ # ---- classify ----
+ if mean_sat < 0.18: # near-neutral / grey → metal or worn
+ if anisotropy > 1.9 and (mean_lum > 95 or spec_frac > 0.03): # bright directional = brushed metal
+ finish = "brushed-steel"
+ elif spec_frac > 0.05 and mean_lum > 140: # bright smooth specular = polished steel
+ finish = "brushed-steel"
+ elif mottle > 0.02 or mean_lum < 120: # dark / textured neutral = worn composite/rubber grip
+ finish = "worn-composite"
+ else: # mid-bright smooth neutral = plastic
+ finish = "plastic"
+ else: # chromatic
+ # gem/candy/doppler family = a chromatic surface with a strong gradient AND smoky internal
+ # variance (the swirl); flat paint has the gradient from lighting only, so low mottle.
+ if gradient_strength > 0.18 and mottle > 0.038:
+ if spec_frac > 0.05:
+ # bright chrome-like specular hotspots → genuinely metallic doppler (high metalness)
+ finish = "gem-metal"
+ elif mean_lum > 150 and spec_frac < 0.005:
+ # bright + clean, no specular blowout → transmissive gemstone (quartz/glass)
+ finish = "gemstone"
+ else:
+ # saturated PIGMENT-DOMINANT coat (colour survives into mid-tones, little chrome)
+ # → anodized/PVD/doppler candy-coat, rendered as a dielectric so the env can't
+ # steal the hue. This is the M9-Doppler case (was mis-classed high-metalness).
+ finish = "candy-coat"
+ else:
+ finish = "painted-metal"
+
+ # ---- palette stops along the dominant gradient axis (ordered low→high lum) ----
+ stops = []
+ for k in range(5):
+ idx = int(k / 4 * (N - 1))
+ if gradient_axis == "horizontal":
+ col = [g[j * N + idx] for j in range(N)]
+ else:
+ col = g[idx * N:(idx + 1) * N]
+ r = sum(c[0] for c in col) // len(col)
+ gg = sum(c[1] for c in col) // len(col)
+ b = sum(c[2] for c in col) // len(col)
+ stops.append(f"#{r:02X}{gg:02X}{b:02X}")
+
+ # Hue-survival annotation: flag any saturated blue-leaning violet/blue
+ # palette stop (B > R) that would collapse to flat blue under ACES/Reinhard tone-mapping, and
+ # suggest a magenta-lean correction (R >= B + a little green). Same rule as extract_gradient_stops.
+ palette_risk = []
+ for hexs in stops:
+ r_ = int(hexs[1:3], 16)
+ g_ = int(hexs[3:5], 16)
+ b_ = int(hexs[5:7], 16)
+ hh, ss, _vv = colorsys.rgb_to_hsv(r_ / 255, g_ / 255, b_ / 255)
+ if b_ > r_ and ss > 0.15 and 0.54 <= hh <= 0.83: # violet/blue hue band on the HSV circle
+ palette_risk.append({
+ "stop": hexs,
+ "hueRisk": "blue-collapse",
+ "suggestedRgb": [min(255, b_), max(g_, int(b_ * 0.25)), r_],
+ })
+
+ recipe = dict(RECIPES[finish])
+ return {
+ "finishClass": finish,
+ "recipe": recipe,
+ "palette": stops,
+ "paletteHueRisk": palette_risk,
+ "gradientAxis": gradient_axis,
+ "stats": {
+ "meanLum": round(mean_lum, 1),
+ "meanSaturation": round(mean_sat, 3),
+ "gradientStrength": round(gradient_strength, 3),
+ "mottle": round(mottle, 3),
+ "streakRatio": round(streak_ratio, 2),
+ "hueSpread": round(hue_spread, 3),
+ "specularFraction": round(spec_frac, 3),
+ },
+ }
+
+
+def apply_to_material(material: dict[str, Any], result: dict[str, Any]) -> dict[str, Any]:
+ """Write the analysed recipe onto a spec material (doc-grounded MeshPhysicalMaterial scalars).
+ Layer-shaped fields ({'base': v}) are preserved so validators stay happy."""
+ r = result["recipe"]
+ material["finishClass"] = result["finishClass"]
+ material["texturePalette"] = result["palette"]
+ material["proceduralTexture"] = r["procedural"]
+ for key in ("metalness", "roughness", "clearcoat", "clearcoatRoughness", "transmission"):
+ existing = material.get(key)
+ if isinstance(existing, dict):
+ existing["base"] = r[key]
+ else:
+ material[key] = {"base": r[key], "variation": 0.0}
+ material["ior"] = {"base": r["ior"], "value": r["ior"]}
+ material["envMapIntensity"] = r["envMapIntensity"]
+ if r["anisotropy"] > 0:
+ material["anisotropy"] = {"base": r["anisotropy"]}
+ return material
+
+
+def main(argv=None) -> int:
+ ap = argparse.ArgumentParser(description="Analyze a reference crop → finishClass + PBR recipe")
+ ap.add_argument("image")
+ ap.add_argument("--json", action="store_true")
+ ap.add_argument("--spec", type=Path, help="ObjectSculptSpec to patch a material in")
+ ap.add_argument("--material-id", help="material id to apply the recipe to (with --spec)")
+ ap.add_argument("--in-place", action="store_true", help="write the spec back")
+ args = ap.parse_args(argv)
+ result = analyze(args.image)
+
+ if args.spec and args.material_id:
+ spec = json.loads(args.spec.read_text())
+ mats = [m for m in spec.get("materials", []) if m.get("id") == args.material_id]
+ if not mats:
+ print(f"material {args.material_id!r} not found in spec", file=sys.stderr)
+ return 2
+ apply_to_material(mats[0], result)
+ if args.in_place:
+ args.spec.write_text(json.dumps(spec, indent=2))
+ print(f"applied {result['finishClass']} recipe to material {args.material_id!r} in {args.spec.name}")
+ else:
+ print(json.dumps(mats[0], indent=2))
+ return 0
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ print(f"finishClass: {result['finishClass']}")
+ print(f"palette: {result['palette']}")
+ print(f"stats: {result['stats']}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/forge/stage1_intake/bind_detail_properties.py b/forge/stage1_intake/bind_detail_properties.py
new file mode 100644
index 0000000..31380cc
--- /dev/null
+++ b/forge/stage1_intake/bind_detail_properties.py
@@ -0,0 +1,99 @@
+#!/usr/bin/env python3
+"""Detail → PBR/geometry property auto-binding (Plan 1.3 Workstream J).
+
+Standardized intake: turn a plain-language detail/material observation into concrete
+Three.js material properties + geometry/primitive hints, so a vague one-line prompt
+still produces a rigorous quality contract instead of "make it shiny". Deterministic
+keyword mapping — no model, no token. The bound properties are exactly the ones the
+full property surface (Workstream H) can emit.
+
+Usage:
+ bind("glossy jade blade with internal smoke") ->
+ {materialProperties, primitiveHint, note}
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import sys
+from typing import Any
+
+# Each rule: (name, keyword-regex, material-properties dict, primitive hint or None, note).
+# Ordered most-specific first; all matching rules contribute (union of properties).
+_RULES: list[tuple[str, str, dict[str, Any], str | None, str]] = [
+ ("gemstone/glass", r"jade|gem|glass|crystal|translucent|transparent|amber|resin",
+ {"transmission": 0.6, "ior": 1.6, "thickness": 0.5, "roughness": 0.1, "requiresEnvMap": True},
+ None, "translucent → transmission+ior+thickness; needs an environment map to read correctly"),
+ ("brushed-metal", r"brushed|anisotropic|satin metal|machined",
+ {"metalness": 1.0, "roughness": 0.35, "anisotropy": 0.6, "anisotropyRotation": 0.0, "requiresEnvMap": True},
+ None, "brushed metal → anisotropy for the directional highlight streak"),
+ ("metal", r"metal|steel|chrome|gold|silver|brass|copper|iron|alumin",
+ {"metalness": 1.0, "roughness": 0.3, "requiresEnvMap": True},
+ None, "metal → metalness 1 + low roughness + env map"),
+ ("glossy-coat", r"gloss|glossy|lacquer|wet look|polished paint|clear ?coat|enamel|varnish",
+ {"clearcoat": 1.0, "clearcoatRoughness": 0.1, "requiresEnvMap": True},
+ None, "glossy paint → clearcoat 1.0 + low clearcoatRoughness"),
+ ("iridescent", r"iridescen|oil ?slick|soap|pearlescent|nacre|holograph",
+ {"iridescence": 1.0, "iridescenceIOR": 1.3, "requiresEnvMap": True},
+ None, "iridescent → iridescence + iridescenceIOR"),
+ ("fabric", r"fabric|cloth|velvet|suede|felt|textile|woven|denim|cotton",
+ {"sheen": 1.0, "sheenColor": "#ffffff", "sheenRoughness": 0.5, "metalness": 0.0, "roughness": 0.85},
+ None, "fabric → sheen for the soft grazing-angle retroreflection"),
+ ("emissive", r"emissive|glow|glowing|led|neon|luminous|backlit|screen|display",
+ {"emissive": "#ffffff", "emissiveIntensity": 1.0},
+ None, "emissive/glowing → emissive + emissiveIntensity"),
+ ("rubber/matte", r"rubber|matte plastic|matte|grip|polymer|abs plastic",
+ {"metalness": 0.0, "roughness": 0.8},
+ None, "matte polymer → high roughness, non-metal"),
+ ("fastener", r"screw|rivet|bolt|stud|fastener|nut|nail|grommet|eyelet",
+ {},
+ "instanced-cluster", "repeated fasteners → instancing (InstancedMesh), not N meshes"),
+ ("decal", r"logo|emblem|stamp|decal|marking|engrav|wordmark|serial|inscription|label",
+ {},
+ "decal", "flat marking → DecalGeometry stamped onto the surface"),
+]
+
+
+def bind(description: str) -> dict[str, Any]:
+ """Bind a free-text detail description to concrete properties + a primitive hint."""
+ text = (description or "").lower()
+ props: dict[str, Any] = {}
+ notes: list[str] = []
+ primitive_hint: str | None = None
+ matched: list[str] = []
+ for name, pattern, rule_props, hint, note in _RULES:
+ if re.search(pattern, text):
+ matched.append(name)
+ for k, v in rule_props.items():
+ props.setdefault(k, v) # first (most-specific) rule wins on conflict
+ if hint and primitive_hint is None:
+ primitive_hint = hint
+ notes.append(note)
+ return {
+ "matchedRules": matched,
+ "materialProperties": props,
+ "primitiveHint": primitive_hint,
+ "notes": notes,
+ "bound": bool(matched),
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("description", help="free-text detail/material description")
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ result = bind(args.description)
+ if args.json:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ else:
+ print(f"matched: {', '.join(result['matchedRules']) or '(none)'}")
+ print(f"properties: {result['materialProperties']}")
+ print(f"primitiveHint: {result['primitiveHint']}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage1_intake/check_intake_correctness.py b/forge/stage1_intake/check_intake_correctness.py
new file mode 100644
index 0000000..371c79b
--- /dev/null
+++ b/forge/stage1_intake/check_intake_correctness.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env python3
+"""Intake-correctness cross-check (Plan 1.3 §4.6) — no semantic garbage-in.
+
+Reference admission (§4.5) proves the image is a valid target; this proves the
+intake actually UNDERSTOOD it. A vague prompt can make intake confidently
+mis-classify (a knife specced as a "spoon"); if that wrong guess drives spec
+authoring, everything downstream is wrong. So before spec authoring proceeds, the
+intake's object-class/material guess is (a) exposed as `assumptionsExposed`, and
+(b) cross-checked against an objectness verdict. A contradiction HALTS to
+request-input rather than building a wrong spec.
+
+Scaffold note (§4.6 + build order §8.5): the objectness verdict ideally comes from
+OSIM (Phase 3, deterministic, zero-token) or, failing that, one cheap VLM objectness
+call. This module owns the DECISION/control-flow now; the objectness source is
+pluggable and wired in Phase 3. With no verdict available, it proceeds but records
+that confirmation is deferred — never silently claims confirmation it didn't get.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+# A contradiction only halts when the objectness signal is confident enough to be trusted.
+CONTRADICTION_CONFIDENCE_MIN = 0.6
+
+
+def expose_assumptions(assessment: dict[str, Any]) -> dict[str, Any]:
+ """Extract the intake's confident guesses so a wrong default is visible, not buried."""
+ psa = assessment.get("preSpecAssessment", assessment)
+ obj = psa.get("objectClass", {}) if isinstance(psa.get("objectClass"), dict) else {}
+ return {
+ "primaryType": obj.get("primaryType"),
+ "primaryDomain": obj.get("primaryDomain"),
+ "materialFamilies": obj.get("materialFamilies", []),
+ }
+
+
+def decide(
+ assessment: dict[str, Any],
+ objectness_verdict: dict[str, Any] | None,
+) -> dict[str, Any]:
+ """Decide whether spec authoring may proceed.
+
+ objectness_verdict (pluggable; from OSIM in Phase 3 or a VLM objectness call):
+ {"matchesDeclaredClass": bool, "confidence": float, "detectedClass": str}
+ or None when no objectness source is available yet.
+
+ Returns {action: 'proceed'|'halt', confirmed: bool, assumptionsExposed, reason}.
+ """
+ assumptions = expose_assumptions(assessment)
+
+ if objectness_verdict is None:
+ return {
+ "action": "proceed",
+ "confirmed": False,
+ "assumptionsExposed": assumptions,
+ "reason": (
+ "no objectness source available yet — confirmation DEFERRED to Phase 3 (OSIM). "
+ "Proceeding on exposed assumptions; they remain falsifiable at Divine-Eye review."
+ ),
+ }
+
+ matches = bool(objectness_verdict.get("matchesDeclaredClass"))
+ confidence = float(objectness_verdict.get("confidence", 0.0))
+ detected = objectness_verdict.get("detectedClass")
+
+ if not matches and confidence >= CONTRADICTION_CONFIDENCE_MIN:
+ return {
+ "action": "halt",
+ "confirmed": False,
+ "assumptionsExposed": assumptions,
+ "reason": (
+ f"intake declared object class {assumptions.get('primaryType')!r} but the objectness "
+ f"check detected {detected!r} (confidence {confidence:.2f} ≥ {CONTRADICTION_CONFIDENCE_MIN}). "
+ "Halting to request-input rather than building a wrong spec (§4.6)."
+ ),
+ }
+
+ return {
+ "action": "proceed",
+ "confirmed": matches,
+ "assumptionsExposed": assumptions,
+ "reason": (
+ f"objectness check {'confirms' if matches else 'does not contradict'} the declared class "
+ f"(confidence {confidence:.2f})."
+ ),
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("assessment", type=Path, help="assessment/spec JSON with preSpecAssessment.objectClass")
+ parser.add_argument("--objectness", type=Path, help="optional objectness verdict JSON (matchesDeclaredClass/confidence/detectedClass)")
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+
+ assessment = json.loads(args.assessment.read_text(encoding="utf-8"))
+ verdict = json.loads(args.objectness.read_text(encoding="utf-8")) if args.objectness else None
+ result = decide(assessment, verdict)
+
+ if args.json:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ else:
+ print(f"action: {result['action'].upper()} confirmed={result['confirmed']}")
+ print(f" assumptions: {result['assumptionsExposed']}")
+ print(f" reason: {result['reason']}")
+ # Exit 1 on halt so a pipeline runner can gate on it; 0 on proceed.
+ return 1 if result["action"] == "halt" else 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage1_intake/check_reference_admission.py b/forge/stage1_intake/check_reference_admission.py
new file mode 100644
index 0000000..947dfe7
--- /dev/null
+++ b/forge/stage1_intake/check_reference_admission.py
@@ -0,0 +1,203 @@
+#!/usr/bin/env python3
+"""Reference-admission gate (Plan 1.3 §4.5.2) — no meaningless references.
+
+Before an image/crop is admitted as ground truth for a component or the whole
+object, it must pass deterministic checks so the Divine Eye never compares a
+render against junk (empty mask, fragmented subject, too-small crop, a duplicate
+angle that adds no information). A reference that fails is rejected WITH A REASON
+at intake, before any tokens are spent — never silently used.
+
+Pure Python stdlib (reuses extract_pbr_evidence's mask primitives + the shared
+pHash). No PIL/numpy.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from image_hash import hamming, phash_from_image # noqa: E402
+
+
+# Thresholds (calibratable in Plan 1.3 §5; conservative defaults here).
+MIN_FOREGROUND_COVERAGE = 0.05
+MAX_FOREGROUND_COVERAGE = 0.97
+MIN_SHORT_SIDE_PX = 64
+MIN_LARGEST_COMPONENT_FRACTION = 0.60 # largest blob must be ≥60% of all foreground
+DUPLICATE_HAMMING_THRESHOLD = 6 # pHash distance ≤ this vs an admitted ref ⇒ duplicate
+COHERENCE_GRID = 96 # downsample mask to this side for connected-component analysis
+
+
+def largest_component_fraction(
+ mask: list[bool], width: int, height: int, grid: int = COHERENCE_GRID
+) -> float:
+ """Fraction of foreground occupied by its single largest 4-connected blob,
+ computed on a downsampled grid. ~1.0 = one coherent subject; low = scattered
+ fragments (a meaningless silhouette for IoU/DCD)."""
+ if width <= 0 or height <= 0 or not mask:
+ return 0.0
+ g = min(grid, max(1, width), max(1, height))
+ cell = [[False] * g for _ in range(g)]
+ for idx, on in enumerate(mask):
+ if not on:
+ continue
+ x = idx % width
+ y = idx // width
+ if y >= height:
+ break
+ cell[min(g - 1, y * g // height)][min(g - 1, x * g // width)] = True
+ total = sum(1 for row in cell for c in row if c)
+ if total == 0:
+ return 0.0
+ seen = [[False] * g for _ in range(g)]
+ best = 0
+ for sy in range(g):
+ for sx in range(g):
+ if not cell[sy][sx] or seen[sy][sx]:
+ continue
+ size = 0
+ stack = [(sy, sx)]
+ seen[sy][sx] = True
+ while stack:
+ cy, cx = stack.pop()
+ size += 1
+ for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)):
+ ny, nx = cy + dy, cx + dx
+ if 0 <= ny < g and 0 <= nx < g and cell[ny][nx] and not seen[ny][nx]:
+ seen[ny][nx] = True
+ stack.append((ny, nx))
+ best = max(best, size)
+ return best / total
+
+
+def check_admission(
+ crop_path: Path,
+ viewpoint: str = "reference",
+ against_hashes: list[int] | None = None,
+) -> dict[str, Any]:
+ """Return an admission verdict dict with reasons + a provenance tag.
+
+ `against_hashes` are pHashes of already-admitted references; a near-duplicate
+ (Hamming ≤ threshold) is rejected as adding no information."""
+ reasons: list[str] = []
+ try:
+ width, height, pixels, _load_warnings = load_image(crop_path)
+ except Exception as exc: # noqa: BLE001
+ # A reference that cannot even be decoded is a clean rejection, not a crash —
+ # an undecodable image is the most meaningless "reference" of all.
+ return {
+ "admitted": False,
+ "reasons": [f"cannot decode image as a usable reference: {type(exc).__name__}: {exc}"],
+ "provenance": {
+ "viewpoint": viewpoint,
+ "sourcePath": str(crop_path.resolve()),
+ "width": 0,
+ "height": 0,
+ "foregroundCoverage": 0.0,
+ "largestComponentFraction": 0.0,
+ "pHash": None,
+ "duplicateOfHash": None,
+ },
+ }
+
+ short_side = min(width, height)
+ if short_side < MIN_SHORT_SIDE_PX:
+ reasons.append(
+ f"resolution floor: short side {short_side}px < {MIN_SHORT_SIDE_PX}px "
+ "(too few pixels to derive geometry/color reliably)"
+ )
+
+ mask, diag, _mask_warnings = build_foreground_mask(width, height, pixels)
+ coverage = float(diag.get("foregroundCoverage", 0.0))
+ if coverage < MIN_FOREGROUND_COVERAGE:
+ reasons.append(
+ f"foreground coverage {coverage:.3f} < {MIN_FOREGROUND_COVERAGE} "
+ "(empty/near-empty — meaningless silhouette)"
+ )
+ elif coverage > MAX_FOREGROUND_COVERAGE:
+ reasons.append(
+ f"foreground coverage {coverage:.3f} > {MAX_FOREGROUND_COVERAGE} "
+ "(no background to segment against — silhouette not isolable)"
+ )
+
+ coherence = largest_component_fraction(mask, width, height)
+ if coverage >= MIN_FOREGROUND_COVERAGE and coherence < MIN_LARGEST_COMPONENT_FRACTION:
+ reasons.append(
+ f"mask coherence: largest connected blob is {coherence:.2f} of foreground "
+ f"< {MIN_LARGEST_COMPONENT_FRACTION} (fragmented/scattered subject — ambiguous)"
+ )
+
+ ref_hash = phash_from_image(width, height, pixels)
+ duplicate_of: int | None = None
+ for other in against_hashes or []:
+ if hamming(ref_hash, other) <= DUPLICATE_HAMMING_THRESHOLD:
+ duplicate_of = other
+ reasons.append(
+ f"duplicate/near-duplicate: pHash within {DUPLICATE_HAMMING_THRESHOLD} of an "
+ "already-admitted reference (adds no information)"
+ )
+ break
+
+ admitted = not reasons
+ return {
+ "admitted": admitted,
+ "reasons": reasons,
+ "provenance": {
+ "viewpoint": viewpoint,
+ "sourcePath": str(crop_path.resolve()),
+ "width": width,
+ "height": height,
+ "foregroundCoverage": round(coverage, 4),
+ "largestComponentFraction": round(coherence, 4),
+ "pHash": ref_hash,
+ "duplicateOfHash": duplicate_of,
+ },
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("image", type=Path)
+ parser.add_argument("--viewpoint", default="reference", help="viewpoint tag this ref is ground truth for")
+ parser.add_argument(
+ "--against",
+ default="",
+ help="comma-separated pHashes (ints) of already-admitted references, for duplicate detection",
+ )
+ parser.add_argument("--json", action="store_true", help="emit the verdict as JSON")
+ args = parser.parse_args(argv)
+
+ against: list[int] = []
+ for token in args.against.split(","):
+ token = token.strip()
+ if token:
+ try:
+ against.append(int(token))
+ except ValueError:
+ print(f"warning: ignoring non-integer --against token {token!r}", file=sys.stderr)
+
+ try:
+ verdict = check_admission(args.image.expanduser().resolve(), args.viewpoint, against)
+ except Exception as exc: # noqa: BLE001
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+ if args.json:
+ print(json.dumps(verdict, indent=2, ensure_ascii=False))
+ else:
+ status = "ADMITTED" if verdict["admitted"] else "REJECTED"
+ print(f"{status} ({verdict['provenance']['viewpoint']}) pHash={verdict['provenance']['pHash']}")
+ for reason in verdict["reasons"]:
+ print(f" - {reason}")
+ return 0 if verdict["admitted"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage1_intake/detect_reference_effects.py b/forge/stage1_intake/detect_reference_effects.py
new file mode 100644
index 0000000..8d7a5d9
--- /dev/null
+++ b/forge/stage1_intake/detect_reference_effects.py
@@ -0,0 +1,275 @@
+#!/usr/bin/env python3
+"""Reference-effect detectors for the img2threejs presentation stage.
+
+Post-processing (depth-of-field, bloom) is authorized on the PRESENTATION render
+ONLY, and ONLY when the REFERENCE photo actually exhibits that characteristic.
+These detectors look at the reference image and decide whether each effect is
+warranted so that effects serve photographic fidelity, not decoration. They are
+NEVER applied to the Eye's evaluation render.
+
+Pure Python 3.10+ stdlib only. Reuses the stage1 loader (import, do NOT edit).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
+from extract_pbr_evidence import load_image, build_foreground_mask # noqa: E402
+
+
+# --------------------------------------------------------------------------- #
+# Helpers
+# --------------------------------------------------------------------------- #
+def luma(r: int, g: int, b: int) -> float:
+ """Rec.709 luma normalized to 0..1."""
+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255.0
+
+
+def _luma_grid(
+ width: int,
+ height: int,
+ pixels: list[tuple[int, int, int, int]],
+ step: int,
+) -> tuple[list[float], int, int]:
+ """Downsample the image to a manageable grid of luma values.
+
+ Samples every ``step`` pixels. Returns (grid, grid_width, grid_height) where
+ grid is row-major of length grid_width * grid_height.
+ """
+ grid: list[float] = []
+ gw = 0
+ gh = 0
+ for y in range(0, height, step):
+ gh += 1
+ row_count = 0
+ for x in range(0, width, step):
+ r, g, b, _a = pixels[y * width + x]
+ grid.append(luma(r, g, b))
+ row_count += 1
+ gw = row_count
+ return grid, gw, gh
+
+
+def _mask_grid(
+ width: int,
+ height: int,
+ mask: list[bool],
+ step: int,
+) -> list[bool]:
+ """Downsample the foreground mask on the same sampling lattice as _luma_grid."""
+ out: list[bool] = []
+ for y in range(0, height, step):
+ for x in range(0, width, step):
+ out.append(mask[y * width + x])
+ return out
+
+
+def _grid_step(width: int, height: int, target: int = 160) -> int:
+ """Pick a sampling step so the longer side is ~<= target cells."""
+ return max(1, max(width, height) // target)
+
+
+def local_gradient_energy(
+ grid: list[float],
+ gw: int,
+ gh: int,
+ keep: list[bool] | None,
+) -> float:
+ """Mean of |L(x,y)-L(x-1,y)| + |L(x,y)-L(x,y-1)| over the selected region.
+
+ ``keep`` selects which grid cells to include (True = include). When None,
+ every cell with x>=1 and y>=1 is included.
+ """
+ total = 0.0
+ count = 0
+ for y in range(1, gh):
+ for x in range(1, gw):
+ idx = y * gw + x
+ if keep is not None and not keep[idx]:
+ continue
+ here = grid[idx]
+ dxe = abs(here - grid[idx - 1])
+ dye = abs(here - grid[idx - gw])
+ total += dxe + dye
+ count += 1
+ return total / count if count else 0.0
+
+
+# --------------------------------------------------------------------------- #
+# Detectors
+# --------------------------------------------------------------------------- #
+def detect_background_blur(png_path: Path) -> dict[str, Any]:
+ """Detect shallow depth-of-field: background much blurrier than the subject."""
+ width, height, pixels, _warnings = load_image(png_path)
+ mask, diag, _mask_warnings = build_foreground_mask(width, height, pixels)
+ coverage = float(diag.get("foregroundCoverage", 0.0))
+
+ step = _grid_step(width, height)
+ grid, gw, gh = _luma_grid(width, height, pixels, step)
+ mgrid = _mask_grid(width, height, mask, step)
+
+ subject_keep = mgrid
+ background_keep = [not value for value in mgrid]
+
+ subject_energy = local_gradient_energy(grid, gw, gh, subject_keep)
+ background_energy = local_gradient_energy(grid, gw, gh, background_keep)
+ ratio = background_energy / subject_energy if subject_energy > 0 else 1.0
+
+ has_background = 0.05 < coverage < 0.95
+ blurred = has_background and ratio < 0.5
+
+ if not has_background:
+ reason = (
+ f"no separable background (foreground coverage {coverage:.3f} outside "
+ f"0.05..0.95); depth-of-field not applicable"
+ )
+ elif blurred:
+ reason = (
+ f"background detail ({background_energy:.5f}) is under half the subject "
+ f"detail ({subject_energy:.5f}); ratio {ratio:.3f} < 0.5 indicates shallow "
+ f"depth-of-field"
+ )
+ else:
+ reason = (
+ f"background detail ({background_energy:.5f}) is comparable to subject "
+ f"detail ({subject_energy:.5f}); ratio {ratio:.3f} >= 0.5, scene reads sharp"
+ )
+
+ return {
+ "blurred": blurred,
+ "backgroundEnergy": round(background_energy, 6),
+ "subjectEnergy": round(subject_energy, 6),
+ "ratio": round(ratio, 4),
+ "reason": reason,
+ }
+
+
+def detect_highlight_glow(png_path: Path) -> dict[str, Any]:
+ """Detect bloom: clipped highlights surrounded by a gradual bright halo."""
+ width, height, pixels, _warnings = load_image(png_path)
+ total = max(1, width * height)
+
+ lumas = [luma(r, g, b) for r, g, b, _a in pixels]
+ hot_indices = [i for i, value in enumerate(lumas) if value > 0.92]
+ hot_fraction = len(hot_indices) / total
+
+ if not hot_indices:
+ return {
+ "glow": False,
+ "hotFraction": round(hot_fraction, 6),
+ "haloFraction": 0.0,
+ "reason": "no near-white highlights (luma > 0.92); nothing to bloom",
+ }
+
+ # Sample the hot pixels so large clipped regions stay fast.
+ sample_limit = 200
+ if len(hot_indices) > sample_limit:
+ stride = len(hot_indices) // sample_limit
+ sampled = hot_indices[::stride][:sample_limit]
+ else:
+ sampled = hot_indices
+
+ # Ring of neighbors just outside the hot core (2-3px out, 8 compass dirs).
+ ring_offsets = [
+ (dx, dy)
+ for radius in (2, 3)
+ for dx, dy in (
+ (-radius, 0),
+ (radius, 0),
+ (0, -radius),
+ (0, radius),
+ (-radius, -radius),
+ (radius, -radius),
+ (-radius, radius),
+ (radius, radius),
+ )
+ ]
+
+ haloed = 0
+ for idx in sampled:
+ x = idx % width
+ y = idx // width
+ elevated_neighbor = False
+ for dx, dy in ring_offsets:
+ nx = x + dx
+ ny = y + dy
+ if 0 <= nx < width and 0 <= ny < height:
+ neighbor = lumas[ny * width + nx]
+ if 0.6 <= neighbor <= 0.92:
+ elevated_neighbor = True
+ break
+ if elevated_neighbor:
+ haloed += 1
+
+ halo_fraction = haloed / len(sampled)
+ glow = hot_fraction > 0.005 and halo_fraction > 0.5
+
+ if glow:
+ reason = (
+ f"highlights present (hotFraction {hot_fraction:.4f} > 0.005) and "
+ f"{halo_fraction:.2%} of them fade through an elevated halo (0.6..0.92); "
+ f"bloom is warranted"
+ )
+ elif hot_fraction <= 0.005:
+ reason = (
+ f"highlights are negligible (hotFraction {hot_fraction:.4f} <= 0.005); "
+ f"no bloom"
+ )
+ else:
+ reason = (
+ f"highlights present but only {halo_fraction:.2%} bloom outward "
+ f"(<= 50%); hard edges, no gradual halo, so no bloom"
+ )
+
+ return {
+ "glow": glow,
+ "hotFraction": round(hot_fraction, 6),
+ "haloFraction": round(halo_fraction, 4),
+ "reason": reason,
+ }
+
+
+def recommend_effects(png_path: Path) -> dict[str, Any]:
+ """Run both detectors and recommend which post-fx the reference warrants."""
+ blur = detect_background_blur(png_path)
+ glow = detect_highlight_glow(png_path)
+ return {
+ "dof": blur["blurred"],
+ "bloom": glow["glow"],
+ "blur": blur,
+ "glow": glow,
+ "note": (
+ "post-fx authorized only for effects the reference actually exhibits; "
+ "applied on the presentation render only, never the Eye's evaluation render"
+ ),
+ }
+
+
+# --------------------------------------------------------------------------- #
+# CLI
+# --------------------------------------------------------------------------- #
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("image", type=Path)
+ parser.add_argument("--json", action="store_true", help="Print compact JSON")
+ args = parser.parse_args(argv)
+
+ try:
+ result = recommend_effects(args.image.expanduser().resolve())
+ if args.json:
+ print(json.dumps(result, ensure_ascii=False))
+ else:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0
+ except Exception as exc: # noqa: BLE001
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage1_intake/extract_gradient_stops.py b/forge/stage1_intake/extract_gradient_stops.py
new file mode 100644
index 0000000..bd0eaf4
--- /dev/null
+++ b/forge/stage1_intake/extract_gradient_stops.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+"""Reference-grounded gradient-stop extractor. Pure stdlib.
+
+Samples the TRUE colour gradient of a material along a structural axis directly from the
+reference crop, so procedural texture STOPS are grounded in the photo instead of hand-guessed
+(the root cause of the M9 Doppler "purple guessed → rendered blue" 4-iteration failure).
+
+Method (Context Part 2.1): foreground-masked PER-BAND MEDIAN sampling — split the object into N
+bands along the axis, take the median RGB per band (median resists specular outliers far better
+than mean), convert to HSV, assign a deterministic hue name, and flag any violet/purple stop that
+is blue-leaning (B > R) as `hueRisk: blue-collapse` (Context Part 2.3 — such a hue collapses to
+blue under ACES/Reinhard tone-mapping; fix = magenta-lean R>=B + green crosstalk).
+
+CLI: extract_gradient_stops.py <crop.png> [--axis u|v] [--stops N] [--json]
+API: extract_gradient_stops(path, axis="u", stops=6) -> dict
+"""
+from __future__ import annotations
+
+import argparse
+import colorsys
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
+
+# Deterministic hue-name lookup over the HSV hue circle (degrees).
+_HUE_NAMES = [
+ (15, "red"), (45, "orange"), (70, "yellow"), (165, "green"),
+ (195, "cyan"), (255, "blue"), (290, "violet"), (345, "magenta"), (360, "red"),
+]
+
+
+def hue_name(h_deg: float) -> str:
+ for upper, name in _HUE_NAMES:
+ if h_deg < upper:
+ return name
+ return "red"
+
+
+def _median(values: list[int]) -> int:
+ if not values:
+ return 0
+ s = sorted(values)
+ return s[len(s) // 2]
+
+
+def sample_banded_stops(
+ width: int,
+ height: int,
+ pixels: list[tuple[int, int, int, int]],
+ mask: list[bool],
+ axis: str,
+ stops: int,
+) -> list[dict[str, Any]]:
+ """Median RGB per band along the axis. axis 'u' = length/x, 'v' = height/y."""
+ span = width if axis == "u" else height
+ band = max(1, span // stops)
+ out: list[dict[str, Any]] = []
+ for b in range(stops):
+ lo = b * band
+ hi = span if b == stops - 1 else (b + 1) * band
+ rs: list[int] = []
+ gs: list[int] = []
+ bs: list[int] = []
+ for y in range(height):
+ for x in range(width):
+ coord = x if axis == "u" else y
+ if coord < lo or coord >= hi:
+ continue
+ idx = y * width + x
+ if idx >= len(mask) or not mask[idx]:
+ continue
+ r, g, bl, _a = pixels[idx]
+ rs.append(r)
+ gs.append(g)
+ bs.append(bl)
+ if not rs:
+ continue # empty band (no foreground) — skip, don't fabricate a colour
+ r, g, bl = _median(rs), _median(gs), _median(bs)
+ h, s, v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, bl / 255.0)
+ h_deg = h * 360.0
+ name = hue_name(h_deg)
+ stop: dict[str, Any] = {
+ "t": round((b + 0.5) / stops, 4),
+ "rgb": [r, g, bl],
+ "hsv": [round(h_deg, 1), round(s, 3), round(v, 3)],
+ "hueName": name,
+ }
+ # Hue-survival flag: a blue-leaning violet/purple (B > R) collapses to blue under
+ # tone-mapping. Suggest a magenta-lean correction (raise R above B + a little green).
+ if name in ("violet", "magenta", "blue") and bl > r and s > 0.15:
+ stop["hueRisk"] = "blue-collapse"
+ stop["suggestedRgb"] = [min(255, bl), max(g, int(bl * 0.25)), r]
+ out.append(stop)
+ return out
+
+
+def extract_gradient_stops(path: Path, axis: str = "u", stops: int = 6) -> dict[str, Any]:
+ width, height, pixels, warnings = load_image(path)
+ mask, _meta, mask_warnings = build_foreground_mask(width, height, pixels)
+ warnings.extend(mask_warnings)
+ band_stops = sample_banded_stops(width, height, pixels, mask, axis, stops)
+ # Collapse consecutive same-hue bands into named hue zones.
+ zones: list[dict[str, Any]] = []
+ for st in band_stops:
+ if zones and zones[-1]["hueName"] == st["hueName"]:
+ zones[-1]["tEnd"] = st["t"]
+ else:
+ zones.append({"hueName": st["hueName"], "tStart": st["t"], "tEnd": st["t"]})
+ return {
+ "axis": axis,
+ "requestedStops": stops,
+ "stops": band_stops,
+ "hueZones": zones,
+ "riskFlags": [s for s in band_stops if s.get("hueRisk")],
+ "warnings": warnings,
+ "reference": str(path.resolve()),
+ "note": "band-median stops grounded in the reference; feed to the texture painter instead "
+ "of hand-guessed STOPS. hueRisk=blue-collapse stops need a magenta-lean correction.",
+ }
+
+
+def main(argv: list[str]) -> int:
+ ap = argparse.ArgumentParser(description="Extract reference-grounded gradient stops (stdlib).")
+ ap.add_argument("crop", type=Path)
+ ap.add_argument("--axis", choices=["u", "v"], default="u")
+ ap.add_argument("--stops", type=int, default=6)
+ ap.add_argument("--json", action="store_true")
+ args = ap.parse_args(argv)
+ if not args.crop.exists():
+ print(f"error: {args.crop} not found", file=sys.stderr)
+ return 2
+ result = extract_gradient_stops(args.crop, axis=args.axis, stops=max(2, args.stops))
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ print(f"axis={result['axis']} stops={len(result['stops'])}")
+ for s in result["stops"]:
+ risk = f" ⚠ {s['hueRisk']} → try rgb {s.get('suggestedRgb')}" if s.get("hueRisk") else ""
+ print(f" t={s['t']:<5} rgb={s['rgb']} {s['hueName']:<8} hsv={s['hsv']}{risk}")
+ print("hue zones:", " → ".join(z["hueName"] for z in result["hueZones"]))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage1_intake/extract_part_color_recipe.py b/forge/stage1_intake/extract_part_color_recipe.py
new file mode 100644
index 0000000..419c57c
--- /dev/null
+++ b/forge/stage1_intake/extract_part_color_recipe.py
@@ -0,0 +1,496 @@
+#!/usr/bin/env python3
+"""Extract a structured per-component color/material recipe from a crop.
+
+Plan 1.3 Workstream C. Extends extract_pbr_evidence.py's pixel-evidence approach
+with CIE L*a*b* clustering (not RGB), Bradford chromatic adaptation, specular-
+hotspot-based roughness estimation, and optional smooth color-gradient detection.
+Colors are emitted as "rgba(r, g, b, a)" strings, matching the Canvas 2D
+addColorStop(offset, color) signature the codegen already consumes, so no
+format conversion is needed between extraction and generate_threejs_factory.py.
+
+Pure Python 3.10+ standard library only — no PIL/numpy, matching the rest of forge/.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from extract_pbr_evidence import ( # noqa: E402
+ build_foreground_mask,
+ clamp,
+ clamp01,
+ load_image,
+ mask_bbox,
+ representative_samples,
+ resample_crop,
+ slugify,
+)
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from artifact_cache import cache_key, get_cached, manifest_path_for, put_cached # noqa: E402
+
+
+# ---------- CIE L*a*b* conversion (sRGB, D65 reference white) ----------
+
+_D65 = (0.95047, 1.0, 1.08883)
+
+# sRGB (linear) -> XYZ, D65
+_RGB_TO_XYZ = (
+ (0.4124564, 0.3575761, 0.1804375),
+ (0.2126729, 0.7151522, 0.0721750),
+ (0.0193339, 0.1191920, 0.9503041),
+)
+_XYZ_TO_RGB = (
+ (3.2404542, -1.5371385, -0.4985314),
+ (-0.9692660, 1.8760108, 0.0415560),
+ (0.0556434, -0.2040259, 1.0572252),
+)
+
+# Bradford cone-response matrix, used for chromatic adaptation.
+_BRADFORD = (
+ (0.8951, 0.2664, -0.1614),
+ (-0.7502, 1.7135, 0.0367),
+ (0.0389, -0.0685, 1.0296),
+)
+_BRADFORD_INV = (
+ (0.9869929, -0.1470543, 0.1599627),
+ (0.4323053, 0.5183603, 0.0492912),
+ (-0.0085287, 0.0400428, 0.9684867),
+)
+
+
+def _matmul3(matrix: tuple[tuple[float, float, float], ...], vector: tuple[float, float, float]) -> tuple[float, float, float]:
+ return tuple(
+ sum(matrix[row][col] * vector[col] for col in range(3)) for row in range(3)
+ ) # type: ignore[return-value]
+
+
+def _srgb_to_linear(channel: float) -> float:
+ c = channel / 255.0
+ if c <= 0.04045:
+ return c / 12.92
+ return ((c + 0.055) / 1.055) ** 2.4
+
+
+def _linear_to_srgb(channel: float) -> float:
+ c = clamp01(channel)
+ if c <= 0.0031308:
+ srgb = c * 12.92
+ else:
+ srgb = 1.055 * (c ** (1.0 / 2.4)) - 0.055
+ return clamp(srgb * 255.0, 0.0, 255.0)
+
+
+def _lab_f(t: float) -> float:
+ delta = 6.0 / 29.0
+ if t > delta ** 3:
+ return t ** (1.0 / 3.0)
+ return t / (3.0 * delta * delta) + 4.0 / 29.0
+
+
+def _lab_f_inv(t: float) -> float:
+ delta = 6.0 / 29.0
+ if t > delta:
+ return t ** 3
+ return 3.0 * delta * delta * (t - 4.0 / 29.0)
+
+
+def rgb_to_xyz(rgb: tuple[int, int, int]) -> tuple[float, float, float]:
+ linear = tuple(_srgb_to_linear(channel) for channel in rgb)
+ return _matmul3(_RGB_TO_XYZ, linear) # type: ignore[arg-type]
+
+
+def xyz_to_rgb(xyz: tuple[float, float, float]) -> tuple[int, int, int]:
+ linear = _matmul3(_XYZ_TO_RGB, xyz)
+ return tuple(round(_linear_to_srgb(channel)) for channel in linear) # type: ignore[return-value]
+
+
+def xyz_to_lab(xyz: tuple[float, float, float], white: tuple[float, float, float] = _D65) -> tuple[float, float, float]:
+ xr, yr, zr = (xyz[i] / white[i] for i in range(3))
+ fx, fy, fz = _lab_f(xr), _lab_f(yr), _lab_f(zr)
+ l_star = 116.0 * fy - 16.0
+ a_star = 500.0 * (fx - fy)
+ b_star = 200.0 * (fy - fz)
+ return (l_star, a_star, b_star)
+
+
+def lab_to_xyz(lab: tuple[float, float, float], white: tuple[float, float, float] = _D65) -> tuple[float, float, float]:
+ l_star, a_star, b_star = lab
+ fy = (l_star + 16.0) / 116.0
+ fx = fy + a_star / 500.0
+ fz = fy - b_star / 200.0
+ return (white[0] * _lab_f_inv(fx), white[1] * _lab_f_inv(fy), white[2] * _lab_f_inv(fz))
+
+
+def srgb_to_lab(rgb: tuple[int, int, int]) -> tuple[float, float, float]:
+ return xyz_to_lab(rgb_to_xyz(rgb))
+
+
+def lab_to_rgb(lab: tuple[float, float, float]) -> tuple[int, int, int]:
+ return xyz_to_rgb(lab_to_xyz(lab))
+
+
+def lab_to_rgba(lab: tuple[float, float, float], alpha: float = 1.0) -> str:
+ r, g, b = lab_to_rgb(lab)
+ return f"rgba({r}, {g}, {b}, {round(clamp01(alpha), 3)})"
+
+
+def lab_distance(a: tuple[float, float, float], b: tuple[float, float, float]) -> float:
+ """CIE76 (Euclidean Lab) distance — sufficient for this project's thresholds."""
+ return math.sqrt(sum((a[i] - b[i]) ** 2 for i in range(3)))
+
+
+def bradford_adapt(
+ lab: tuple[float, float, float],
+ source_white: tuple[float, float, float],
+ target_white: tuple[float, float, float] = _D65,
+) -> tuple[float, float, float]:
+ """Chromatic-adapt a Lab color from an estimated source illuminant to target_white
+ (D65 by default) via the Bradford cone-response transform, approximating a neutral
+ white-balance so warm/cool ambient light doesn't skew the extracted albedo."""
+ xyz = lab_to_xyz(lab, white=source_white)
+ src_cone = _matmul3(_BRADFORD, source_white)
+ dst_cone = _matmul3(_BRADFORD, target_white)
+ cone = _matmul3(_BRADFORD, xyz)
+ adapted_cone = tuple(
+ cone[i] * (dst_cone[i] / src_cone[i] if src_cone[i] else 1.0) for i in range(3)
+ )
+ adapted_xyz = _matmul3(_BRADFORD_INV, adapted_cone) # type: ignore[arg-type]
+ return xyz_to_lab(adapted_xyz, white=target_white)
+
+
+# ---------- Lab-space k-means palette ----------
+
+def lab_kmeans_palette(samples: list[tuple[float, float, float]], k: int) -> list[dict[str, Any]]:
+ if not samples:
+ return []
+ k = max(1, min(k, len(samples)))
+ ordered = sorted(samples, key=lambda lab: lab[0])
+ centers = [ordered[int((index + 0.5) * (len(ordered) - 1) / k)] for index in range(k)]
+ groups: list[list[tuple[float, float, float]]] = [[] for _ in centers]
+ for _ in range(8):
+ groups = [[] for _ in centers]
+ for sample in samples:
+ nearest = min(range(len(centers)), key=lambda idx: lab_distance(sample, centers[idx]))
+ groups[nearest].append(sample)
+ new_centers = []
+ for group, center in zip(groups, centers):
+ if not group:
+ new_centers.append(center)
+ continue
+ new_centers.append(tuple(sum(s[c] for s in group) / len(group) for c in range(3)))
+ centers = new_centers # type: ignore[assignment]
+ total = len(samples)
+ result = [
+ {"center": centers[index], "share_pct": len(group) / total}
+ for index, group in enumerate(groups)
+ if group
+ ]
+ result.sort(key=lambda entry: entry["share_pct"], reverse=True)
+ return result
+
+
+# ---------- Hotspot-based roughness (Cook-Torrance half-angle proxy) ----------
+
+def estimate_roughness_from_hotspot(
+ lumas: list[float],
+ mask: list[bool],
+) -> tuple[float, str]:
+ """Sharp/tight hotspot -> low roughness; wide/diffuse hotspot -> high roughness.
+ This is a proxy measurement (spatial spread of the brightest foreground pixels),
+ not a true BRDF fit, but it is a real measurement off the pixels rather than a
+ heuristic default."""
+ foreground_lumas = [luma for luma, keep in zip(lumas, mask) if keep]
+ if not foreground_lumas:
+ return 0.7, "no foreground pixels; default mid-roughness"
+ peak = max(foreground_lumas)
+ # Measure what fraction of the surface reads as "near the actual peak
+ # brightness" (within 0.1 luma of it), not "above a fixed percentile" — a
+ # percentile-based cutoff breaks down when the highlight covers only a tiny
+ # fraction of pixels, since the percentile value itself then falls back into
+ # the dark background range and every pixel spuriously satisfies ">= cutoff".
+ near_peak_threshold = max(0.0, peak - 0.1)
+ hotspot_fraction = sum(1 for luma in foreground_lumas if luma >= near_peak_threshold) / len(foreground_lumas)
+ # A tight/sharp specular hotspot occupies a small fraction of the surface near
+ # peak brightness; a broad/diffuse highlight covers much more of the surface.
+ spread = clamp01(hotspot_fraction * 2.0)
+ roughness = clamp(0.12 + spread * 0.75, 0.05, 0.95)
+ if spread < 0.3:
+ evidence = "sharp, tight specular hotspot — supports low roughness/high specularity"
+ elif spread > 0.7:
+ evidence = "broad, gradually-fading highlight — supports high roughness/diffuse response"
+ else:
+ evidence = "moderate hotspot spread — mid-range roughness"
+ return round(roughness, 3), evidence
+
+
+# ---------- Material classification (rule-based, evidence-cited) ----------
+
+def classify_material(
+ dominant_lab: tuple[float, float, float],
+ saturation: float,
+ hotspot_roughness: float,
+) -> tuple[str, float]:
+ lightness = dominant_lab[0]
+ chroma = math.sqrt(dominant_lab[1] ** 2 + dominant_lab[2] ** 2)
+ if saturation < 0.12 and hotspot_roughness < 0.3:
+ return "metal", round(clamp(0.55 + (0.3 - hotspot_roughness) * 0.8, 0.4, 0.85), 3)
+ if saturation < 0.15 and lightness > 70 and hotspot_roughness < 0.45:
+ return "glass", round(clamp(0.45 + (70 - abs(lightness - 85)) * 0.005, 0.35, 0.75), 3)
+ if chroma > 25 and hotspot_roughness > 0.55:
+ return "fabric", round(clamp(0.4 + (hotspot_roughness - 0.55) * 0.6, 0.35, 0.7), 3)
+ if chroma > 15 and hotspot_roughness < 0.5:
+ return "plastic", round(clamp(0.4 + (0.5 - hotspot_roughness) * 0.5, 0.35, 0.7), 3)
+ if lightness < 45 and chroma < 20:
+ return "stone", round(0.45, 3)
+ return "unknown", round(0.3, 3)
+
+
+# ---------- Color-gradient detection ----------
+
+_GRADIENT_MIN_DELTA_E = 8.0
+_GRADIENT_MIN_MONOTONIC_FRACTION = 0.8
+_GRADIENT_STOP_OFFSETS = (0.0, 0.55, 1.0)
+
+
+def _sample_axis(
+ size: int,
+ lab_grid: list[tuple[float, float, float]],
+ mask_grid: list[bool],
+ start: tuple[float, float],
+ end: tuple[float, float],
+ steps: int = 9,
+) -> list[tuple[float, float, float]] | None:
+ samples: list[tuple[float, float, float]] = []
+ for step in range(steps):
+ t = step / (steps - 1)
+ x = start[0] + (end[0] - start[0]) * t
+ y = start[1] + (end[1] - start[1]) * t
+ sx = min(size - 1, max(0, int(round(x))))
+ sy = min(size - 1, max(0, int(round(y))))
+ index = sy * size + sx
+ if not mask_grid[index]:
+ return None
+ samples.append(lab_grid[index])
+ return samples
+
+
+def _is_monotonic(values: list[float]) -> bool:
+ """Strictly-equal consecutive samples count as neutral (support neither direction),
+ not as evidence for both — otherwise an aliased flat/oscillating signal (e.g. nearest-
+ pixel sampling across a checkerboard) can spuriously look monotonic when ties inflate
+ whichever real direction happens to have a one-sample edge."""
+ if len(values) < 2:
+ return True
+ increasing = sum(1 for i in range(1, len(values)) if values[i] > values[i - 1])
+ decreasing = sum(1 for i in range(1, len(values)) if values[i] < values[i - 1])
+ fraction = max(increasing, decreasing) / (len(values) - 1)
+ return fraction >= _GRADIENT_MIN_MONOTONIC_FRACTION
+
+
+def detect_color_gradient(
+ size: int,
+ lab_grid: list[tuple[float, float, float]],
+ mask_grid: list[bool],
+) -> dict[str, Any] | None:
+ """Tests 4 linear axes + 1 radial-from-centroid axis; returns the strongest
+ candidate that clears BOTH the magnitude (ΔE >= 8.0) and monotonicity (>=80%
+ consistent-direction sample pairs) gates, or None if nothing qualifies. Both
+ gates are required — magnitude alone would accept textured/patterned regions
+ with real-but-non-directional color variance (see Risk R8)."""
+ foreground_indices = [i for i, keep in enumerate(mask_grid) if keep]
+ if len(foreground_indices) < 9:
+ return None
+ xs = [i % size for i in foreground_indices]
+ ys = [i // size for i in foreground_indices]
+ x0, x1 = min(xs), max(xs)
+ y0, y1 = min(ys), max(ys)
+ cx, cy = sum(xs) / len(xs), sum(ys) / len(ys)
+ candidates: list[tuple[str, tuple[float, float], tuple[float, float], tuple[float, float]]] = [
+ ("linear", (x0, cy), (x1, cy), (1.0, 0.0)),
+ ("linear", (cx, y0), (cx, y1), (0.0, 1.0)),
+ ("linear", (x0, y0), (x1, y1), (0.7071, 0.7071)),
+ ("linear", (x0, y1), (x1, y0), (0.7071, -0.7071)),
+ ("radial", (cx, cy), (x1, cy), (1.0, 0.0)),
+ ]
+ best: dict[str, Any] | None = None
+ best_delta_e = 0.0
+ for kind, start, end, axis in candidates:
+ samples = _sample_axis(size, lab_grid, mask_grid, start, end)
+ if samples is None:
+ continue
+ delta_e = lab_distance(samples[0], samples[-1])
+ if delta_e < _GRADIENT_MIN_DELTA_E:
+ continue
+ if not all(_is_monotonic([s[channel] for s in samples]) for channel in range(3)):
+ continue
+ if delta_e > best_delta_e:
+ best_delta_e = delta_e
+ stops = []
+ for offset in _GRADIENT_STOP_OFFSETS:
+ idx = min(len(samples) - 1, max(0, round(offset * (len(samples) - 1))))
+ stops.append({"offset": offset, "color": lab_to_rgba(samples[idx])})
+ axis_field = list(axis) if kind == "linear" else [cx / size, cy / size]
+ best = {
+ "type": kind,
+ "axis": axis_field,
+ "stops": stops,
+ "confidence": round(clamp01(delta_e / 30.0), 3),
+ }
+ return best
+
+
+# ---------- Top-level recipe assembly ----------
+
+def build_recipe(
+ component_id: str,
+ crop_path: Path,
+ target_threshold: float = 0.7,
+ material_class_hint: str | None = None,
+ size: int = 96,
+) -> dict[str, Any]:
+ width, height, pixels, _load_warnings = load_image(crop_path)
+ rgba_pixels = pixels
+ rgb_pixels = [(r, g, b) for r, g, b, _a in rgba_pixels]
+ mask, _mask_diag, _mask_warnings = build_foreground_mask(width, height, rgba_pixels)
+ bbox = mask_bbox(width, height, mask)
+ sampled_pixels, sampled_mask = resample_crop(width, height, rgba_pixels, mask, bbox, size)
+
+ lab_grid = [srgb_to_lab(pixel) for pixel in sampled_pixels]
+ lumas = [0.2126 * p[0] / 255.0 + 0.7152 * p[1] / 255.0 + 0.0722 * p[2] / 255.0 for p in sampled_pixels]
+
+ foreground_lab = [lab for lab, keep in zip(lab_grid, sampled_mask) if keep]
+ samples_for_kmeans = representative_samples(foreground_lab, [True] * len(foreground_lab), limit=4000) if foreground_lab else []
+ clusters = lab_kmeans_palette(samples_for_kmeans, k=3)
+
+ if not clusters:
+ raise ValueError(f"no foreground pixels found in crop for component {component_id!r}")
+
+ dominant_lab = clusters[0]["center"]
+ secondary_lab = clusters[1]["center"] if len(clusters) > 1 else dominant_lab
+
+ background_white = _D65 # neutral D65 assumption; refine with a metered gray card in future work
+ dominant_adapted = bradford_adapt(dominant_lab, source_white=background_white)
+ secondary_adapted = bradford_adapt(secondary_lab, source_white=background_white)
+
+ roughness, hotspot_evidence = estimate_roughness_from_hotspot(lumas, sampled_mask)
+
+ dominant_rgb = lab_to_rgb(dominant_adapted)
+ saturation = 0.0 if max(dominant_rgb) == 0 else (max(dominant_rgb) - min(dominant_rgb)) / max(dominant_rgb)
+ material_class, material_confidence = classify_material(dominant_adapted, saturation, roughness)
+ if material_class_hint:
+ material_class = material_class_hint
+ material_confidence = max(material_confidence, 0.6)
+
+ metalness = 1.0 if material_class == "metal" else 0.0
+
+ gradient = detect_color_gradient(size, lab_grid, sampled_mask)
+
+ recipe: dict[str, Any] = {
+ "componentId": component_id,
+ "dominantAlbedo": lab_to_rgba(dominant_adapted),
+ "secondaryAlbedo": lab_to_rgba(secondary_adapted),
+ "materialClass": material_class,
+ "materialClassConfidence": material_confidence,
+ "roughnessEstimate": roughness,
+ "metalnessEstimate": metalness,
+ "highlightEvidence": hotspot_evidence,
+ "sourceCropPath": str(crop_path.resolve()),
+ "labClusterMeta": {
+ "clusterCount": len(clusters),
+ "dominantClusterSharePct": round(clusters[0]["share_pct"], 3),
+ },
+ }
+ if gradient is not None:
+ recipe["colorGradient"] = gradient
+ return recipe
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("crop", type=Path)
+ parser.add_argument("--component-id", required=True)
+ parser.add_argument("--material-class-hint")
+ parser.add_argument("--target-threshold", type=float, default=0.7)
+ parser.add_argument("--spec", type=Path, help="ObjectSculptSpec JSON to patch")
+ parser.add_argument("--in-place", action="store_true", help="Patch --spec in place when confidence passes")
+ parser.add_argument("--out-spec", type=Path, help="Write patched spec to this path")
+ parser.add_argument("--allow-low-confidence", action="store_true")
+ parser.add_argument("--no-cache", action="store_true", help="Skip the hash-based extraction cache")
+ args = parser.parse_args(argv)
+
+ try:
+ crop_path = args.crop.expanduser().resolve()
+ cache_dir = (args.spec.expanduser().resolve().parent if args.spec else crop_path.parent)
+ manifest_path = manifest_path_for(cache_dir, "color_recipe_cache.json")
+ key = cache_key(crop_path, Path(__file__).resolve())
+ cached = None if args.no_cache else get_cached(manifest_path, key)
+ if cached is not None:
+ # The cache key is crop+script content only (no component-id), since the
+ # pixel-derived data is identical regardless of which component reuses this
+ # exact crop — but componentId is a contextual label, not derived from
+ # pixels, so it must be re-stamped to the CURRENT invocation's value.
+ recipe = dict(cached)
+ recipe["componentId"] = args.component_id
+ recipe["cacheHit"] = True
+ else:
+ recipe = build_recipe(
+ args.component_id,
+ crop_path,
+ target_threshold=args.target_threshold,
+ material_class_hint=args.material_class_hint,
+ )
+ recipe["cacheHit"] = False
+ if not args.no_cache:
+ put_cached(manifest_path, key, {k: v for k, v in recipe.items() if k != "cacheHit"})
+ ok = recipe["materialClassConfidence"] >= args.target_threshold
+ if args.spec:
+ if not ok and not args.allow_low_confidence:
+ raise ValueError(
+ f"materialClassConfidence {recipe['materialClassConfidence']} is below target "
+ f"{args.target_threshold}; spec was not patched (use --allow-low-confidence to override)"
+ )
+ spec_path = args.spec.expanduser().resolve()
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
+ components = spec.get("componentTree", [])
+ target = next((c for c in components if isinstance(c, dict) and c.get("id") == args.component_id), None)
+ if target is None:
+ raise ValueError(f"component {args.component_id!r} not found in spec componentTree")
+ # cacheHit is a runtime diagnostic for this invocation, not evidence data —
+ # don't persist it into the spec's colorMaterialRecipe.
+ target["colorMaterialRecipe"] = {k: v for k, v in recipe.items() if k != "cacheHit"}
+ # colorMaterialRecipe lives on the component (evidence/audit trail: which crop,
+ # what confidence). But generate_threejs_factory.py's texture codegen reads
+ # colorGradient off the shared MATERIAL entry (materials[] is the actual
+ # rendering unit, referenced by id from possibly-multiple components) — so a
+ # detected gradient must also be mirrored onto that material to actually render.
+ if "colorGradient" in recipe:
+ material_id = target.get("material")
+ material = next(
+ (m for m in spec.get("materials", []) if isinstance(m, dict) and m.get("id") == material_id),
+ None,
+ )
+ if material is not None:
+ material["colorGradient"] = recipe["colorGradient"]
+ output = spec_path if args.in_place else (args.out_spec.expanduser().resolve() if args.out_spec else None)
+ if output:
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps(recipe, indent=2, ensure_ascii=False))
+ # Low confidence without --spec is informational only (nothing was patched,
+ # so there's nothing to "fail"); the --spec low-confidence case already
+ # raised above and was caught by the except clause below.
+ return 0
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage2_spec/derive_geometry.py b/forge/stage2_spec/derive_geometry.py
new file mode 100644
index 0000000..fefa1e9
--- /dev/null
+++ b/forge/stage2_spec/derive_geometry.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+"""Deterministic geometry derivation from a reference mask (Plan 1.3 §4, Phase 2).
+
+Blum-Medial-Axis-style lathe-profile derivation: instead of hand-guessing a
+LatheGeometry profile, COMPUTE it from the object's silhouette. For a roughly
+axisymmetric subject (vase, bottle, handle, hilt), sweeping the local inscribed
+half-width along the major axis yields a revolve profile that matches the
+reference — stopping the "eyeballed profile" failure mode.
+
+Pure Python stdlib (reuses extract_pbr_evidence's mask primitives). No PIL/numpy.
+
+Output profile is a list of [radius, axisPos] pairs in object-relative units
+(axisPos in [-0.5, 0.5], radius normalized by the object's long dimension),
+directly consumable as LatheGeometry points (x = radius ≥ 0, revolved around Y).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
+from extract_pbr_evidence import build_foreground_mask, load_image, mask_bbox # noqa: E402
+
+
+def _row_span(mask: list[bool], width: int, y: int, x0: int, x1: int) -> tuple[int, int] | None:
+ left = right = None
+ for x in range(x0, x1 + 1):
+ if mask[y * width + x]:
+ if left is None:
+ left = x
+ right = x
+ if left is None:
+ return None
+ return (left, right)
+
+
+def _col_span(mask: list[bool], width: int, height: int, x: int, y0: int, y1: int) -> tuple[int, int] | None:
+ top = bottom = None
+ for y in range(y0, y1 + 1):
+ if mask[y * width + x]:
+ if top is None:
+ top = y
+ bottom = y
+ if top is None:
+ return None
+ return (top, bottom)
+
+
+def derive_lathe_profile(
+ mask: list[bool],
+ width: int,
+ height: int,
+ samples: int = 24,
+) -> dict[str, Any]:
+ """Derive a revolve profile from the mask by sweeping inscribed half-width along
+ the object's major axis. Returns {axis, points:[[radius, axisPos],...], samples}."""
+ x0, y0, bw, bh = mask_bbox(width, height, mask)
+ x1, y1 = x0 + bw - 1, y0 + bh - 1
+ vertical = bh >= bw # revolve around the LONGER dimension's axis
+ long_len = bh if vertical else bw
+ if long_len <= 1:
+ return {"axis": "vertical" if vertical else "horizontal", "points": [], "samples": 0}
+
+ raw: list[tuple[float, float]] = [] # (axisPos_pixels_from_start, radius_pixels)
+ for i in range(samples):
+ t = i / (samples - 1)
+ if vertical:
+ y = int(round(y0 + t * (y1 - y0)))
+ span = _row_span(mask, width, y, x0, x1)
+ pos = y - y0
+ else:
+ x = int(round(x0 + t * (x1 - x0)))
+ span = _col_span(mask, width, height, x, y0, y1)
+ pos = x - x0
+ radius = 0.0 if span is None else (span[1] - span[0]) / 2.0
+ raw.append((float(pos), radius))
+
+ # Normalize: axisPos to [-0.5, 0.5] over the long dimension, radius by long dimension.
+ norm = float(long_len)
+ points = [[round(r / norm, 4), round(pos / norm - 0.5, 4)] for pos, r in raw]
+ return {
+ "axis": "vertical" if vertical else "horizontal",
+ "points": points,
+ "samples": samples,
+ "note": "Blum-medial-axis-derived revolve profile (radius along major axis); LatheGeometry-ready.",
+ }
+
+
+def derive_from_image(crop_path: Path, samples: int = 24) -> dict[str, Any]:
+ width, height, pixels, _warn = load_image(crop_path)
+ mask, _diag, _mw = build_foreground_mask(width, height, pixels)
+ result = derive_lathe_profile(mask, width, height, samples)
+ result["sourcePath"] = str(crop_path.resolve())
+ return result
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("image", type=Path)
+ parser.add_argument("--samples", type=int, default=24)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ result = derive_from_image(args.image.expanduser().resolve(), args.samples)
+ except Exception as exc: # noqa: BLE001
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ print(json.dumps(result, indent=2, ensure_ascii=False) if args.json else
+ f"axis={result['axis']} points={len(result['points'])}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage2_spec/new_sculpt_spec.py b/forge/stage2_spec/new_sculpt_spec.py
index a9aa19c..1609ef6 100755
--- a/forge/stage2_spec/new_sculpt_spec.py
+++ b/forge/stage2_spec/new_sculpt_spec.py
@@ -219,11 +219,19 @@ def load_assessment(path: Path | None) -> dict | None:
def _cnode(cid, name, primitive, parent, position, scale,
material="skin", role="body", level="meso", rotation=(0, 0, 0),
importance=0.7, sockets=None, local_features=None, anim_role="static",
- pivot_mode="center", evidence=None):
+ pivot_mode="center", evidence=None, topology_class="assembled-solid",
+ topology_rationale=None):
"""Build a full schema-valid componentTree node with humanoid-friendly defaults."""
+ if topology_rationale is None:
+ topology_rationale = (
+ f"{name} is a discrete primitive body part assembled onto the humanoid rig, "
+ f"not a continuous sculpt or shell."
+ )
return {
"id": cid, "name": name, "level": level, "role": role,
"importance": importance, "confidence": 0.8, "primitive": primitive,
+ "topologyClass": topology_class,
+ "topologyRationale": topology_rationale,
"geometryDescriptor": {
"topologyIntent": "stylized character part",
"edgeTreatment": {"type": "none", "bevelRadius": 0.0, "segments": 1},
@@ -425,7 +433,7 @@ def make_spec(target_name: str, image: str | None, assessment_payload: dict | No
return {
"targetName": target_name,
"targetId": target_id,
- "schemaVersion": "2.0",
+ "schemaVersion": "2.1",
"terminologyProfile": {
"domain": "real-time procedural Three.js asset",
"geometryTerms": [
@@ -774,6 +782,11 @@ def make_spec(target_name: str, image: str | None, assessment_payload: dict | No
"importance": 1.0,
"confidence": 0.5,
"primitive": "box",
+ "topologyClass": "assembled-solid",
+ "topologyRationale": (
+ "Placeholder root blockout; reclassify per Workstream A's decision tree "
+ "(grimoire/intake/surface_topology.md) once real geometry is authored."
+ ),
"geometryDescriptor": {
"topologyIntent": "low-poly blockout with bevel-ready edges",
"edgeTreatment": {
diff --git a/forge/stage2_spec/validate_sculpt_spec.py b/forge/stage2_spec/validate_sculpt_spec.py
index 85a2ce5..61c4e9e 100755
--- a/forge/stage2_spec/validate_sculpt_spec.py
+++ b/forge/stage2_spec/validate_sculpt_spec.py
@@ -35,6 +35,7 @@ VALID_PRIMITIVES = {
"tube",
"lathe",
"extrude",
+ "ground-blade",
"curve-sweep",
"plane-card",
"instanced-cluster",
@@ -43,6 +44,88 @@ VALID_COMPONENT_LEVELS = {"macro", "meso", "micro"}
VALID_COMPLEXITY_TIERS = {"unassessed", "simple", "moderate", "complex", "ultra-complex"}
TERMINOLOGY_LIST_FIELDS = {"geometryTerms", "materialTerms", "lightingTerms"}
VALID_REVIEW_ACTIONS = {"continue", "refine-spec", "refine-code", "request-input", "stop"}
+VALID_TOPOLOGY_CLASSES = {
+ "continuous-sculpt",
+ "assembled-solid",
+ "conforming-shell",
+ "surface-relief",
+ "fiber-strand",
+ "material-only",
+}
+# Plan 1.3 Workstream A: primitives that are structurally wrong for a given topology class.
+# Prevents "Flat-Projection Bias" (e.g. a continuous organic bulge picked as a box-stack).
+DISALLOWED_TOPOLOGY_PRIMITIVE_PAIRS: dict[str, set[str]] = {
+ "continuous-sculpt": {"box", "cylinder", "cone"},
+ "fiber-strand": {"box", "plane-card"},
+}
+TOPOLOGY_ALLOWED_HINT = {
+ "continuous-sculpt": "lathe, extrude, or curve-sweep",
+ "fiber-strand": "tube or instanced-cluster",
+}
+
+
+# Plan 1.3 G.1 — spec-level flatness gate (the karambit-blade defect signature).
+# The robust discriminator is SEMANTIC, not a fragile geometric curvature estimate:
+# `continuous-sculpt` asserts "a continuous volumetric 3D form", so pairing it with a
+# THIN straight extrude (a flat slab) is a contradiction that will read as a flat plane
+# from non-reference angles. A legitimately flat object is tagged surface-relief /
+# conforming-shell / material-only, NOT continuous-sculpt, so it never reaches this gate.
+FLATNESS_DEPTH_RATIO_MAX = 0.15 # depth/diagonal below this ⇒ thin slab
+
+
+def _bbox_diagonal(points: list) -> float:
+ xs = [p[0] for p in points if isinstance(p, (list, tuple)) and len(p) >= 2]
+ ys = [p[1] for p in points if isinstance(p, (list, tuple)) and len(p) >= 2]
+ if not xs or not ys:
+ return 0.0
+ return ((max(xs) - min(xs)) ** 2 + (max(ys) - min(ys)) ** 2) ** 0.5
+
+
+def flatness_risk(component_id: str, component: dict[str, Any]) -> tuple[str, str]:
+ """Return ('HIGH'|'OK', message). HIGH when a component the spec declares to be a
+ continuous 3D form (`continuous-sculpt`, gated at the call site) is built as a THIN
+ straight extrude — a flat slab that only reads correctly from the reference angle.
+ The fix is `curve-sweep` (sweep a thin cross-section along a 3D spine)."""
+ descriptor = component.get("geometryDescriptor") if isinstance(component.get("geometryDescriptor"), dict) else {}
+ profile = descriptor.get("profile2D") if isinstance(descriptor.get("profile2D"), dict) else None
+ if not profile:
+ return ("OK", "")
+ points = profile.get("points")
+ depth = profile.get("depth")
+ if not isinstance(points, list) or not is_number(depth):
+ return ("OK", "")
+ diagonal = _bbox_diagonal(points)
+ if diagonal <= 0:
+ return ("OK", "")
+ depth_ratio = float(depth) / diagonal
+ if depth_ratio < FLATNESS_DEPTH_RATIO_MAX:
+ return (
+ "HIGH",
+ f"quality: component {component_id!r} flatness risk — declared continuous-sculpt (a "
+ f"continuous 3D form) but built as a thin straight extrude "
+ f"(depth/diagonal={depth_ratio:.3f} < {FLATNESS_DEPTH_RATIO_MAX}); it will read as a flat "
+ f"plane bent into a curve from non-reference angles. Use primitive 'curve-sweep' (sweep a "
+ f"thin cross-section along a 3D spine), or re-classify the topology if it really is flat.",
+ )
+ return ("OK", "")
+
+
+def schema_version_tuple(spec: dict[str, Any]) -> tuple[int, int]:
+ raw = spec.get("schemaVersion")
+ if not isinstance(raw, str):
+ return (0, 0)
+ parts = raw.split(".")
+ try:
+ return (int(parts[0]), int(parts[1]) if len(parts) > 1 else 0)
+ except ValueError:
+ return (0, 0)
+
+
+def requires_topology_classification(spec: dict[str, Any]) -> bool:
+ # Plan 1.3 Risk R2: only specs authored under schema 2.1+ are held to the new
+ # topologyClass/topologyRationale requirement, so pre-1.3 specs are not silently
+ # broken by a field they were never told to fill in.
+ return schema_version_tuple(spec) >= (2, 1)
VISUAL_PASS_IDS = {
"blockout",
"structural-pass",
@@ -617,6 +700,65 @@ def validate_string_array(value: Any, label: str, errors: list[str]) -> None:
errors.append(f"{label} must be an array of strings")
+VALID_MATERIAL_CLASSES = {
+ "metal", "plastic", "wood", "fabric", "skin", "glass", "ceramic", "rubber", "stone", "unknown",
+}
+# Alpha accepts "0", "1", "0.xxx", "1.xxx", or ".xxx" — must match what lab_to_rgba() in
+# extract_part_color_recipe.py actually emits (round(alpha, 3) renders full opacity as "1.0",
+# not bare "1"), or every extracted recipe fails this check on its own real output.
+RGBA_PATTERN = re.compile(r"^rgba\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*(?:(?:0|1)(?:\.\d+)?|\.\d+)\s*\)$")
+
+
+def is_rgba_string(value: Any) -> bool:
+ return isinstance(value, str) and bool(RGBA_PATTERN.match(value.strip()))
+
+
+def validate_color_material_recipe(component_id: str, recipe: Any, warnings: list[str]) -> None:
+ """Plan 1.3 Workstream C: every non-material-only component needs a structured,
+ evidence-linked colorMaterialRecipe instead of bare-word colors. Fires as a
+ 'quality:' warning so --strict-quality (not normal validation) enforces it,
+ matching the topologyClass gating above."""
+ if not isinstance(recipe, dict):
+ warnings.append(f"quality: component {component_id!r} is missing colorMaterialRecipe")
+ return
+ for field in ("dominantAlbedo", "secondaryAlbedo"):
+ if not is_rgba_string(recipe.get(field)):
+ warnings.append(
+ f"quality: component {component_id!r} colorMaterialRecipe.{field} must be an "
+ f"'rgba(r, g, b, a)' string"
+ )
+ material_class = recipe.get("materialClass")
+ if material_class not in VALID_MATERIAL_CLASSES:
+ warnings.append(
+ f"quality: component {component_id!r} colorMaterialRecipe.materialClass must be one "
+ f"of: {', '.join(sorted(VALID_MATERIAL_CLASSES))}"
+ )
+ confidence = recipe.get("materialClassConfidence")
+ if not is_number(confidence) or not (0.0 <= float(confidence) <= 1.0):
+ warnings.append(
+ f"quality: component {component_id!r} colorMaterialRecipe.materialClassConfidence "
+ f"must be a number between 0.0 and 1.0"
+ )
+ gradient = recipe.get("colorGradient")
+ if gradient is not None:
+ if not isinstance(gradient, dict) or gradient.get("type") not in {"linear", "radial"}:
+ warnings.append(
+ f"quality: component {component_id!r} colorMaterialRecipe.colorGradient.type "
+ f"must be 'linear' or 'radial'"
+ )
+ stops = gradient.get("stops") if isinstance(gradient, dict) else None
+ if not isinstance(stops, list) or len(stops) < 2:
+ warnings.append(
+ f"quality: component {component_id!r} colorMaterialRecipe.colorGradient.stops "
+ f"must have at least 2 entries"
+ )
+ elif any(not is_rgba_string(stop.get("color")) for stop in stops if isinstance(stop, dict)):
+ warnings.append(
+ f"quality: component {component_id!r} colorMaterialRecipe.colorGradient.stops[].color "
+ f"must be 'rgba(r, g, b, a)' strings"
+ )
+
+
def validate_components(
spec: dict[str, Any],
material_ids: set[str],
@@ -643,6 +785,46 @@ def validate_components(
errors.append(
f"component {component_id!r} primitive must be one of: {', '.join(sorted(VALID_PRIMITIVES))}"
)
+ if requires_topology_classification(spec):
+ topology_class = component.get("topologyClass")
+ topology_rationale = component.get("topologyRationale")
+ if topology_class not in VALID_TOPOLOGY_CLASSES:
+ warnings.append(
+ f"quality: component {component_id!r} missing or invalid topologyClass "
+ f"(must be one of: {', '.join(sorted(VALID_TOPOLOGY_CLASSES))})"
+ )
+ else:
+ if not isinstance(topology_rationale, str) or not topology_rationale.strip():
+ warnings.append(
+ f"quality: component {component_id!r} topologyRationale is required alongside topologyClass"
+ )
+ else:
+ normalized_rationale = re.sub(r"[\s_-]+", "", topology_rationale.strip().lower())
+ normalized_class = re.sub(r"[\s_-]+", "", topology_class.lower())
+ if normalized_rationale == normalized_class:
+ warnings.append(
+ f"quality: component {component_id!r} topologyRationale restates the enum "
+ f"value instead of citing visible evidence"
+ )
+ disallowed = DISALLOWED_TOPOLOGY_PRIMITIVE_PAIRS.get(topology_class, set())
+ if primitive in disallowed:
+ hint = TOPOLOGY_ALLOWED_HINT.get(topology_class, "an allowed primitive")
+ warnings.append(
+ f"quality: component {component_id!r} pairs topologyClass={topology_class!r} "
+ f"with disallowed primitive {primitive!r} (use {hint} instead)"
+ )
+ # Plan 1.3 Workstream C: gated on topologyClass (already required above),
+ # not colorMaterialRecipe.materialClass — that field only exists once the
+ # recipe is present, so using it as its own gate would be circular.
+ if topology_class != "material-only":
+ validate_color_material_recipe(component_id, component.get("colorMaterialRecipe"), warnings)
+ # Plan 1.3 G.1: flatness pre-check — catch a flat extrude faking a curved
+ # 3D form BEFORE any render (the karambit-blade defect: a thin extrude of a
+ # curved silhouette only looks right from the reference camera angle).
+ if primitive == "extrude" and topology_class == "continuous-sculpt":
+ severity, message = flatness_risk(component_id, component)
+ if severity == "HIGH":
+ warnings.append(message)
level = component.get("level")
if level is not None and level not in VALID_COMPONENT_LEVELS:
errors.append(f"component {component_id!r} level must be macro, meso, or micro")
diff --git a/forge/stage3_build/generate_threejs_factory.py b/forge/stage3_build/generate_threejs_factory.py
index 7eef01f..233da26 100755
--- a/forge/stage3_build/generate_threejs_factory.py
+++ b/forge/stage3_build/generate_threejs_factory.py
@@ -24,6 +24,7 @@ VALID_PRIMITIVES = {
"tube",
"lathe",
"extrude",
+ "ground-blade",
"curve-sweep",
"plane-card",
"instanced-cluster",
@@ -221,7 +222,39 @@ def scale_vector(component: dict[str, Any], transform: dict[str, Any]) -> str:
return vector(None, [1, 1, 1])
-def geometry_for(primitive: str) -> str:
+class GeometryNotImplementedError(Exception):
+ """A component's primitive is a valid VALID_PRIMITIVES member but geometry_for()
+ has no codegen branch for it yet. Never silently substitute a box for this case —
+ that produced structurally-wrong renders (e.g. blade/knife primitives collapsing to
+ a generic box) with no signal that anything was wrong. See Plan 1.3 Workstream F."""
+
+
+_DEFAULT_EXTRUDE_PROFILE = {"points": [[-0.3, -0.3], [0.3, -0.3], [0.3, 0.3], [-0.3, 0.3]], "depth": 0.1}
+# Plan 1.3 — ground blade: a real knife solid with a PRIMARY BEVEL (lower body grinds from
+# full thickness at a mid grind-line down to a sharp cutting edge) and a SWEDGE / false edge
+# (near the tip the spine also grinds to a false edge). Lofted from stations [x, spineY, edgeY].
+_DEFAULT_BLADE_SPEC = {
+ "stations": [
+ [0.00, 0.080, -0.090], [0.12, 0.086, -0.100], [0.30, 0.086, -0.110],
+ [0.50, 0.084, -0.108], [0.63, 0.078, -0.095], [0.74, 0.055, -0.055],
+ [0.82, 0.028, -0.020], [0.88, 0.000, 0.000],
+ ],
+ "thickness": 0.05, "grindFrac": 0.55, "swedgeFromTipFrac": 0.34, "spineFlat": 0.30,
+}
+_DEFAULT_LATHE_PROFILE = {"points": [[0.3, -0.5], [0.15, 0.0], [0.3, 0.5]], "segments": 24}
+_DEFAULT_TUBE_PATH = {"points": [[0.0, -0.5, 0.0], [0.0, 0.5, 0.0]], "radius": 0.05, "closed": False}
+# Plan 1.3 F.6 — curve-sweep: a thin 2D cross-section swept along a measured 3D spine.
+# The FIX for curved forms (hooked blades, handles) that a flat extrude only renders
+# correctly from the reference camera angle. Default is a gentle S-curve so a missing
+# spine still produces a real swept solid, not a straight bar.
+_DEFAULT_CURVE_SWEEP = {
+ "spine": [[-0.5, -0.4, 0.0], [-0.1, 0.1, 0.0], [0.3, 0.2, 0.0], [0.6, -0.1, 0.0]],
+ "crossSection": {"points": [[-0.04, -0.02], [0.04, -0.02], [0.04, 0.02], [-0.04, 0.02]]},
+ "closed": False,
+}
+
+
+def geometry_for(primitive: str, component: dict[str, Any] | None = None) -> str:
if primitive == "box":
return "new THREE.BoxGeometry(1, 1, 1, 12, 12, 12)"
if primitive in {"sphere", "ellipsoid"}:
@@ -233,10 +266,39 @@ def geometry_for(primitive: str) -> str:
if primitive == "capsule":
return "new THREE.CapsuleGeometry(0.35, 0.7, 16, 32)"
if primitive == "torus":
- return "new THREE.TorusGeometry(0.45, 0.08, 24, 96)"
+ # Tube thickness is ring-relative (fraction of the 0.45 base radius) so a
+ # component can be a slim bike tyre or a fat donut without changing scale.
+ desc = component.get("geometryDescriptor") if isinstance(component, dict) and isinstance(component.get("geometryDescriptor"), dict) else {}
+ tube_ratio = desc.get("torusTubeRatio")
+ tube = 0.45 * float(tube_ratio) if isinstance(tube_ratio, (int, float)) and tube_ratio > 0 else 0.08
+ return f"new THREE.TorusGeometry(0.45, {round(tube, 4)}, 24, 96)"
if primitive == "plane-card":
return "new THREE.PlaneGeometry(1, 1, 24, 24)"
- return "new THREE.BoxGeometry(1, 1, 1, 8, 8, 8)"
+ descriptor = component.get("geometryDescriptor") if isinstance(component, dict) and isinstance(component.get("geometryDescriptor"), dict) else {}
+ if primitive == "extrude":
+ profile = descriptor.get("profile2D") if isinstance(descriptor.get("profile2D"), dict) else _DEFAULT_EXTRUDE_PROFILE
+ return f"buildExtrudeGeometry({json_literal(profile)})"
+ if primitive == "ground-blade":
+ spec = descriptor.get("bladeSpec") if isinstance(descriptor.get("bladeSpec"), dict) else _DEFAULT_BLADE_SPEC
+ return f"buildGroundBladeGeometry({json_literal(spec)})"
+ if primitive == "lathe":
+ profile = descriptor.get("latheProfile") if isinstance(descriptor.get("latheProfile"), dict) else _DEFAULT_LATHE_PROFILE
+ return f"buildLatheGeometry({json_literal(profile)})"
+ if primitive == "tube":
+ path = descriptor.get("tubePath") if isinstance(descriptor.get("tubePath"), dict) else _DEFAULT_TUBE_PATH
+ return f"buildTubeGeometry({json_literal(path)})"
+ if primitive == "curve-sweep":
+ sweep = descriptor.get("curveSweep") if isinstance(descriptor.get("curveSweep"), dict) else _DEFAULT_CURVE_SWEEP
+ return f"buildCurveSweepGeometry({json_literal(sweep)})"
+ if primitive == "instanced-cluster":
+ # An instanced cluster's *geometry* is its base shape; the instancing itself is applied
+ # by the repetition-system emitter (THREE.InstancedMesh). Resolve the base primitive from
+ # the descriptor (default box); guard against self-reference so we never recurse.
+ base = descriptor.get("baseGeometry") if isinstance(descriptor.get("baseGeometry"), str) else "box"
+ if base in ("instanced-cluster", "") or base not in VALID_PRIMITIVES:
+ base = "box"
+ return geometry_for(base, component)
+ raise GeometryNotImplementedError(primitive)
def generate(spec: dict[str, Any], pass_id: str) -> str:
@@ -253,6 +315,11 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
lines: list[str] = [
"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';",
"",
"export type ProceduralModelOptions = {",
" wireframe?: boolean;",
@@ -273,6 +340,178 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
"",
"type SculptMaterialSpec = Record<string, any>;",
"",
+ ]
+
+ # Plan 1.3 Workstream F.5: real geometry for the primitives that previously fell
+ # through to a silent BoxGeometry fallback. Only emit the helper functions a
+ # primitive that's actually used in THIS pass's components needs — TypeScript
+ # projects commonly build with noUnusedLocals, and an always-emitted
+ # buildLatheGeometry/buildTubeGeometry fails that build the moment a spec (or a
+ # pass, since blockout only includes macro components) doesn't use them.
+ used_primitives = {str(component.get("primitive")) for component in components}
+ if "extrude" in used_primitives:
+ lines.extend(
+ [
+ "// bevelEnabled defaults to true on THREE.ExtrudeGeometry and rounds every",
+ "// corner — sharp/pointed profiles (blades, fork tines, spikes) need",
+ "// bevelEnabled: false plus lineTo()-only path segments near the tip, since a",
+ "// curve command cannot produce a true converging point.",
+ "function buildExtrudeShape(points: [number, number][], holes?: [number, number][][]): THREE.Shape {",
+ " const shape = new THREE.Shape();",
+ " if (points.length > 0) {",
+ " shape.moveTo(points[0][0], points[0][1]);",
+ " for (let i = 1; i < points.length; i += 1) {",
+ " shape.lineTo(points[i][0], points[i][1]);",
+ " }",
+ " }",
+ " // Cutouts (e.g. an oval wire-cutter hole) as THREE.Path added to shape.holes —",
+ " // dep-free boolean subtraction via the tessellator, no CSG library needed.",
+ " for (const loop of holes ?? []) {",
+ " if (loop.length < 3) continue;",
+ " const path = new THREE.Path();",
+ " path.moveTo(loop[0][0], loop[0][1]);",
+ " for (let i = 1; i < loop.length; i += 1) path.lineTo(loop[i][0], loop[i][1]);",
+ " path.closePath();",
+ " shape.holes.push(path);",
+ " }",
+ " return shape;",
+ "}",
+ "",
+ "// Build an N-gon oval loop (for hole authoring from a compact {cx,cy,rx,ry} descriptor).",
+ "function ovalLoop(cx: number, cy: number, rx: number, ry: number, seg = 24): [number, number][] {",
+ " const loop: [number, number][] = [];",
+ " for (let i = 0; i < seg; i += 1) {",
+ " const a = (i / seg) * Math.PI * 2;",
+ " loop.push([cx + Math.cos(a) * rx, cy + Math.sin(a) * ry]);",
+ " }",
+ " return loop;",
+ "}",
+ "",
+ "function buildExtrudeGeometry(profile: { points: [number, number][]; depth: number; holes?: [number, number][][]; ovalHoles?: { cx: number; cy: number; rx: number; ry: number }[] }): THREE.ExtrudeGeometry {",
+ " const holes = [...(profile.holes ?? []), ...((profile.ovalHoles ?? []).map((o) => ovalLoop(o.cx, o.cy, o.rx, o.ry)))];",
+ " const shape = buildExtrudeShape(profile.points, holes);",
+ " return new THREE.ExtrudeGeometry(shape, {",
+ " depth: profile.depth,",
+ " bevelEnabled: false,",
+ " steps: 1,",
+ " });",
+ "}",
+ "",
+ ]
+ )
+ if "ground-blade" in used_primitives:
+ lines.extend(
+ [
+ "// Ground blade: lofts a beveled cross-section along [x, spineY, edgeY] stations.",
+ "// Per station the section is: sharp cutting EDGE (z=0) → PRIMARY BEVEL up to the",
+ "// grind line (±T) → flat/saber body → SWEDGE near the tip (spine grinds to a false",
+ "// edge, z=0) or a squared spine elsewhere. Non-indexed → flat-shaded facets. UVs map",
+ "// the doppler gradient along length (u) and height (v).",
+ "function buildGroundBladeGeometry(spec: { stations: [number, number, number][]; thickness?: number; grindFrac?: number; swedgeFromTipFrac?: number }): THREE.BufferGeometry {",
+ " const st = spec.stations;",
+ " const T = (spec.thickness ?? 0.05) / 2;",
+ " const grindFrac = spec.grindFrac ?? 0.55;",
+ " const swedgeFrac = spec.swedgeFromTipFrac ?? 0.34;",
+ " const xG = st[0][0];",
+ " const xT = st[st.length - 1][0];",
+ " const len = (xT - xG) || 1;",
+ " // Actual blade Y bounds (stations are [x, topY, botY]) — v must span THESE, not a",
+ " // hardcoded ±0.12: a blade positioned off-origin would otherwise clamp v→1 and make",
+ " // every face sample the bright spine-rim row (the white-tip/washed-facet bug).",
+ " let yMin = Infinity, yMax = -Infinity;",
+ " for (const s of st) { yMin = Math.min(yMin, s[2]); yMax = Math.max(yMax, s[1]); }",
+ " const yH = (yMax - yMin) || 1;",
+ " const ring = (s: [number, number, number]): [number, number, number][] => {",
+ " const [x, topY, botY] = s;",
+ " const h = Math.max(1e-4, topY - botY);",
+ " const grindY = botY + grindFrac * h;",
+ " const swedgeY = topY - 0.42 * h;",
+ " const sz = ((xT - x) / len < swedgeFrac) ? 0 : T; // swedge → sharp false edge near tip",
+ " return [",
+ " [x, botY, 0], [x, grindY, T], [x, swedgeY, T], [x, topY, sz],",
+ " [x, topY, -sz], [x, swedgeY, -T], [x, grindY, -T],",
+ " ];",
+ " };",
+ " const pos: number[] = [];",
+ " const tri = (a: number[], b: number[], c: number[]) => { pos.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]); };",
+ " let A = ring(st[0]);",
+ " // guard-end cap (fan) so the base is closed where it meets the guard",
+ " for (let k = 1; k < 6; k++) tri(A[0], A[k], A[k + 1]);",
+ " for (let i = 1; i < st.length; i++) {",
+ " const B = ring(st[i]);",
+ " for (let k = 0; k < 7; k++) {",
+ " const k2 = (k + 1) % 7;",
+ " tri(A[k], A[k2], B[k2]);",
+ " tri(A[k], B[k2], B[k]);",
+ " }",
+ " A = B;",
+ " }",
+ " const g = new THREE.BufferGeometry();",
+ " g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));",
+ " g.computeVertexNormals();",
+ " const uv: number[] = [];",
+ " for (let t = 0; t < pos.length; t += 3) uv.push((pos[t] - xG) / len, (pos[t + 1] - yMin) / yH);",
+ " g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));",
+ " return g;",
+ "}",
+ "",
+ ]
+ )
+ if "lathe" in used_primitives:
+ lines.extend(
+ [
+ "function buildLatheGeometry(profile: { points: [number, number][]; segments?: number }): THREE.LatheGeometry {",
+ " const points = profile.points.map(([x, y]) => new THREE.Vector2(Math.max(0.0001, x), y));",
+ " return new THREE.LatheGeometry(points, profile.segments ?? 24);",
+ "}",
+ "",
+ ]
+ )
+ if "tube" in used_primitives:
+ lines.extend(
+ [
+ "function buildTubeGeometry(",
+ " path: { points: [number, number, number][]; radius?: number; radialSegments?: number; closed?: boolean },",
+ "): THREE.TubeGeometry {",
+ " const vectors = path.points.map(([x, y, z]) => new THREE.Vector3(x, y, z));",
+ " const curve = new THREE.CatmullRomCurve3(vectors, path.closed ?? false);",
+ " const tubularSegments = Math.max(8, path.points.length * 6);",
+ " return new THREE.TubeGeometry(curve, tubularSegments, path.radius ?? 0.05, path.radialSegments ?? 8, path.closed ?? false);",
+ "}",
+ "",
+ ]
+ )
+ if "curve-sweep" in used_primitives:
+ lines.extend(
+ [
+ "// Plan 1.3 F.6 — sweep a thin 2D cross-section along a 3D spine so a curved",
+ "// form (hooked blade, handle) reads correctly from EVERY camera angle, not just",
+ "// the reference angle a flat extrude happens to match. Uses ExtrudeGeometry's",
+ "// native extrudePath; bevelEnabled: false keeps sharp tips (same rule as F.5).",
+ "function buildCurveSweepGeometry(",
+ " sweep: { spine: [number, number, number][]; crossSection: { points: [number, number][] }; closed?: boolean },",
+ "): THREE.ExtrudeGeometry {",
+ " const shape = new THREE.Shape();",
+ " const cs = sweep.crossSection.points;",
+ " if (cs.length > 0) {",
+ " shape.moveTo(cs[0][0], cs[0][1]);",
+ " for (let i = 1; i < cs.length; i += 1) shape.lineTo(cs[i][0], cs[i][1]);",
+ " shape.closePath();",
+ " }",
+ " const spine = sweep.spine.map(([x, y, z]) => new THREE.Vector3(x, y, z));",
+ " const path = new THREE.CatmullRomCurve3(spine, sweep.closed ?? false);",
+ " return new THREE.ExtrudeGeometry(shape, {",
+ " extrudePath: path,",
+ " steps: Math.max(24, spine.length * 8),",
+ " bevelEnabled: false,",
+ " });",
+ "}",
+ "",
+ ]
+ )
+
+ lines.extend(
+ [
"function hashString(value: string): number {",
" let hash = 2166136261;",
" for (let index = 0; index < value.length; index += 1) {",
@@ -401,6 +640,51 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" ];",
"}",
"",
+ "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 [Number(match[1]), Number(match[2]), 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)));",
@@ -546,6 +830,7 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" 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) {",
@@ -556,10 +841,17 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" const colorNoise = sampleSurface(u, v, bands, seed + 15013);",
" heightField[index] = height;",
" roughnessField[index] = clamp01(baseRoughness + (roughNoise - 0.5) * roughnessVariation * 2);",
- " const paletteValue = clamp01(",
- " 0.5 + (colorNoise - 0.5) * colorAmplitude * 2 + (height - 0.5) * heightCorrelation",
- " );",
- " const color = mixPalette(colors, paletteValue);",
+ " 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]);",
" }",
" }",
@@ -623,6 +915,21 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" 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: Math.max(1, 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: Math.max(1, readLayerNumber(spec.iridescenceIOR, ['base', 'value'], 1.3)),",
+ " anisotropy: clamp01(readLayerNumber(spec.anisotropy, ['base', 'amount'], 0)),",
+ " anisotropyRotation: readLayerNumber(spec.anisotropy, ['rotation'], 0),",
+ " specularIntensity: clamp01(readLayerNumber(spec.specularIntensity, ['base'], 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)),",
@@ -708,7 +1015,8 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
f" root.name = {json.dumps(target)};",
"",
" const materialMap: Record<string, THREE.Material> = {};",
- ]
+ ]
+ )
for material_id, material in materials.items():
lines.extend(
[
@@ -770,7 +1078,7 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
f" nodes[{json.dumps(component_id)}] = {node_var};",
f" const {component_var}Geometry = {endpoint_var}",
f" ? new THREE.CylinderGeometry({endpoint_var}.endRadius, {endpoint_var}.baseRadius, {endpoint_var}.length, 32, 12)",
- f" : {geometry_for(primitive)};",
+ f" : {geometry_for(primitive, component)};",
f" const {component_var} = new THREE.Mesh(",
f" {component_var}Geometry,",
f" materialMap[{json.dumps(material_id)}] ?? new THREE.MeshStandardMaterial({{ color: 0x888888 }})",
@@ -814,10 +1122,72 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
f" sockets[{json.dumps(socket_key)}] = {socket_var};",
]
)
- if primitive in {"tube", "lathe", "extrude", "curve-sweep", "instanced-cluster"}:
- lines.append(
- f" // TODO: replace {component_id!r} box fallback with {primitive} procedural geometry."
- )
+
+ # Repetition systems (spokes, fasteners, teeth, slats): the spec models these
+ # as a count + placement + instanceScale rather than N hand-authored components.
+ # They are emitted here, parented to the referenced node, and pass-gated by the
+ # same macro/meso/micro levels as componentTree so blockout stays clay-macro.
+ allowed_levels = PASS_LEVELS.get(pass_id, {"macro"})
+ known_ids = {str(c.get("id")) for c in all_components if isinstance(c, dict)}
+ for rep_index, system in enumerate(spec.get("repetitionSystems", [])):
+ if not isinstance(system, dict):
+ continue
+ level = str(system.get("level") or "meso")
+ if level not in allowed_levels:
+ continue
+ parent_id = str(system.get("parent") or "root")
+ if parent_id not in known_ids and parent_id != "root":
+ parent_id = "root"
+ placement = system.get("placement", {}) if isinstance(system.get("placement"), dict) else {}
+ count = int(system.get("count") or 0)
+ if count <= 0:
+ continue
+ primitive = str(system.get("primitive") or "box")
+ if primitive not in VALID_PRIMITIVES:
+ primitive = "box"
+ rep_material = str(system.get("material") or next(iter(materials.keys()), "base"))
+ scale = system.get("instanceScale", [0.1, 0.1, 0.1])
+ axis = placement.get("axis", [0, 0, 1])
+ radius = placement.get("radius", 0.0)
+ start_deg = placement.get("startAngleDeg", 0)
+ mode = str(placement.get("mode") or "radial")
+ rep_var = f"rep_{rep_index}"
+ lines.extend(
+ [
+ "",
+ f" // repetition system: {system.get('id') or rep_var} (InstancedMesh, {mode}, count={count}, level={level})",
+ " {",
+ f" const parent = nodes[{json.dumps(parent_id)}] ?? root;",
+ f" const geo = {geometry_for(primitive, {})};",
+ f" const mat = materialMap[{json.dumps(rep_material)}] ?? new THREE.MeshStandardMaterial({{ color: 0x888888 }});",
+ f" const scl = [{vector(scale, [0.1, 0.1, 0.1])}];",
+ f" const axis = new THREE.Vector3({vector(axis, [0, 0, 1])}).normalize();",
+ f" const radius = {float(radius) if isinstance(radius, (int, float)) else 0.0};",
+ " const seed = Math.abs(axis.z) < 0.9 ? new THREE.Vector3(0, 0, 1) : new THREE.Vector3(1, 0, 0);",
+ " const perp = new THREE.Vector3().crossVectors(axis, seed).normalize();",
+ " // One InstancedMesh = one draw call for all repeated parts (teeth/fasteners/spokes),",
+ " // replacing the former per-instance Mesh clone loop (real-time perf principle).",
+ f" const cluster = new THREE.InstancedMesh(geo, mat, {count});",
+ " const _m = new THREE.Matrix4();",
+ " const _p = new THREE.Vector3();",
+ " const _q = new THREE.Quaternion();",
+ " const _s = new THREE.Vector3(scl[0], scl[1], scl[2]);",
+ f" for (let i = 0; i < {count}; i++) {{",
+ f" const ang = (({float(start_deg) if isinstance(start_deg,(int,float)) else 0.0}) + (i * 360) / {count}) * Math.PI / 180;",
+ " const dir = perp.clone().applyQuaternion(new THREE.Quaternion().setFromAxisAngle(axis, ang));",
+ " _p.copy(radius > 0 ? dir.clone().multiplyScalar(radius * 0.5) : new THREE.Vector3());",
+ " _q.setFromUnitVectors(new THREE.Vector3(1, 0, 0), dir);",
+ " _m.compose(_p, _q, _s);",
+ " cluster.setMatrixAt(i, _m);",
+ " }",
+ " cluster.instanceMatrix.needsUpdate = true;",
+ " cluster.castShadow = options.castShadow ?? true;",
+ " cluster.receiveShadow = options.receiveShadow ?? true;",
+ f" cluster.name = {json.dumps(str(system.get('id') or rep_var))};",
+ " parent.add(cluster);",
+ " }",
+ ]
+ )
look_dev_targets = spec.get("lookDevTargets", {})
lighting_from_photo = spec.get("lightingFromPhoto", [])
@@ -854,6 +1224,15 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" 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);",
@@ -867,6 +1246,78 @@ def generate(spec: dict[str, Any], pass_id: str) -> str:
" 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.",
+ f"export function create{type_name}Environment(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).",
+ f"export function frame{type_name}Camera(",
+ " 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).",
+ f"export function create{type_name}PresentationComposer(",
+ " 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;",
+ "}",
+ "",
]
)
return "\n".join(lines)
@@ -896,7 +1347,15 @@ def main(argv: list[str]) -> int:
if output.exists() and not args.force:
parser.error(f"{output} already exists; use --force to overwrite")
output.parent.mkdir(parents=True, exist_ok=True)
- output.write_text(generate(spec, pass_id), encoding="utf-8")
+ try:
+ rendered = generate(spec, pass_id)
+ except GeometryNotImplementedError as exc:
+ parser.error(
+ f"primitive {str(exc)!r} is accepted by validation but has no codegen "
+ f"implementation yet in geometry_for() — refine-spec to a supported primitive "
+ f"or implement it before generating this component"
+ )
+ output.write_text(rendered, encoding="utf-8")
print(output)
return 0
diff --git a/forge/stage3_build/module_cache.py b/forge/stage3_build/module_cache.py
new file mode 100644
index 0000000..578ea91
--- /dev/null
+++ b/forge/stage3_build/module_cache.py
@@ -0,0 +1,155 @@
+"""Per-module code cache for the img2threejs factory generator (Plan 1.3
+Phase 6, Workstream I).
+
+img2threejs decomposes an object into risk-ranked semantic MODULES. Regenerating
+the whole factory on every fix is wasteful and regresses already-approved parts.
+This module caches generated factory code PER MODULE, keyed on BOTH the module's
+spec fragment AND the generator's own source, so editing one module regenerates
+only that module (and its neighbors) rather than the whole object.
+
+It builds on the shared hash-based cache (`_shared/artifact_cache.py`) and adds:
+ - a canonical (key-order-independent) hash of a module spec, and
+ - §3.7 neighbor re-validation: when a module changes, cached modules ATTACHED
+ to it are invalidated, because a neighbor change can introduce interaction
+ defects the dependent's already-cached code no longer accounts for.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from artifact_cache import ( # noqa: E402
+ file_sha256,
+ get_cached,
+ load_manifest,
+ manifest_path_for, # noqa: F401 (re-exported for callers)
+ put_cached,
+ save_manifest,
+)
+
+
+def canonical_module_hash(module_spec: dict) -> str:
+ """sha256 of the module spec serialized deterministically (sorted keys).
+
+ Two specs with the same content but different key insertion order hash
+ identically, so cache hits don't depend on dict ordering.
+ """
+ blob = json.dumps(
+ module_spec, sort_keys=True, ensure_ascii=False, separators=(",", ":")
+ ).encode("utf-8")
+ return hashlib.sha256(blob).hexdigest()
+
+
+def module_cache_key(module_spec: dict, generator_source: Path) -> str:
+ """Key changes if EITHER the module's spec OR the generator source changes.
+
+ Mirrors artifact_cache.cache_key: pairing the spec hash with the generator's
+ own source hash closes the stale-cache risk (edit the generator, forget to
+ bump a version -> serve stale code).
+ """
+ return f"{canonical_module_hash(module_spec)}:{file_sha256(generator_source)[:12]}"
+
+
+def get_module(
+ manifest_path: Path, module_spec: dict, generator_source: Path
+) -> str | None:
+ """Return the cached generated code for this module, or None on a miss."""
+ entry = get_cached(manifest_path, module_cache_key(module_spec, generator_source))
+ if entry is None:
+ return None
+ return entry.get("code")
+
+
+def put_module(
+ manifest_path: Path, module_spec: dict, generator_source: Path, code: str
+) -> None:
+ """Store generated code for this module under its (spec+generator) key."""
+ put_cached(
+ manifest_path,
+ module_cache_key(module_spec, generator_source),
+ {"code": code, "moduleId": module_spec.get("id")},
+ )
+
+
+def _dependents_of(changed_module_id: str, components: list[dict]) -> set[str]:
+ """Ids of components attached to `changed_module_id` (parent or attachment).
+
+ The changed module itself is never included — only its dependents.
+ """
+ dependents: set[str] = set()
+ for comp in components:
+ comp_id = comp.get("id")
+ if comp_id == changed_module_id:
+ continue
+ parent_id = comp.get("parent")
+ attachment = comp.get("attachment") or {}
+ attach_parent = attachment.get("parentId")
+ if parent_id == changed_module_id or attach_parent == changed_module_id:
+ if comp_id is not None:
+ dependents.add(comp_id)
+ return dependents
+
+
+def invalidate_attached(
+ manifest_path: Path, changed_module_id: str, components: list[dict]
+) -> list[str]:
+ """§3.7 neighbor re-validation.
+
+ Find every component attached to `changed_module_id` (its parent, or its
+ attachment.parentId, points at the changed module) and drop ALL cached
+ entries whose stored moduleId equals that dependent's id. The changed module
+ itself is NOT invalidated here — only its dependents, whose cached code may
+ now be wrong because a neighbor moved.
+
+ Returns the sorted list of dependent module ids that were invalidated.
+ """
+ dependents = _dependents_of(changed_module_id, components)
+ if not dependents:
+ return []
+
+ manifest = load_manifest(manifest_path)
+ removed: set[str] = set()
+ for key in list(manifest.keys()):
+ entry = manifest[key]
+ module_id = entry.get("moduleId") if isinstance(entry, dict) else None
+ if module_id in dependents:
+ del manifest[key]
+ removed.add(module_id)
+ save_manifest(manifest_path, manifest)
+ return sorted(removed)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description="img2threejs per-module code cache")
+ parser.add_argument("--manifest", required=True, help="path to cache manifest")
+ parser.add_argument("--action", choices=["stats"], default="stats")
+ parser.add_argument("--json", action="store_true", help="emit JSON")
+ args = parser.parse_args(argv)
+
+ try:
+ manifest = load_manifest(Path(args.manifest))
+ module_ids = sorted(
+ {
+ entry.get("moduleId")
+ for entry in manifest.values()
+ if isinstance(entry, dict) and entry.get("moduleId") is not None
+ }
+ )
+ result = {"entries": len(manifest), "moduleIds": module_ids}
+ if args.json:
+ print(json.dumps(result, ensure_ascii=False))
+ else:
+ print(result)
+ except Exception as exc: # noqa: BLE001
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage3_build/orchestrate_passes.py b/forge/stage3_build/orchestrate_passes.py
index 7b0e842..25febbd 100755
--- a/forge/stage3_build/orchestrate_passes.py
+++ b/forge/stage3_build/orchestrate_passes.py
@@ -443,6 +443,19 @@ def sync_pipeline(spec: dict[str, Any]) -> dict[str, Any]:
return pipeline
+def has_passing_tier1_result(spec: dict[str, Any], pass_id: str) -> bool:
+ """Plan 1.3 Workstream D: Tier 2 (AI-vision) must never run against a render
+ that has not passed Tier 1. Checked here rather than in append_review.py so
+ the refusal happens before any expensive review step is even attempted."""
+ results = spec.get("tier1Results", [])
+ if not isinstance(results, list):
+ return False
+ return any(
+ isinstance(entry, dict) and entry.get("passId") == pass_id and entry.get("passed") is True
+ for entry in results
+ )
+
+
def check_pass(spec: dict[str, Any], requested_pass: str) -> tuple[bool, str, dict[str, Any]]:
pipeline = sync_pipeline(spec)
ids = list(pipeline["passOrder"])
@@ -459,6 +472,12 @@ def check_pass(spec: dict[str, Any], requested_pass: str) -> tuple[bool, str, di
gaps = pass_specific_gaps(spec, requested_pass)
if gaps:
return False, f"pass {requested_pass!r} needs spec refinement: {'; '.join(gaps)}", pipeline
+ if requested_pass in VISUAL_PASS_IDS and not has_passing_tier1_result(spec, requested_pass):
+ return (
+ False,
+ f"Tier 1 diagnostics have not passed for this render — run diagnose_render.py first",
+ pipeline,
+ )
return True, f"pass {requested_pass!r} is the current unlocked pass", pipeline
previous_index = ids.index(requested_pass) - 1
previous = ids[previous_index] if previous_index >= 0 else ""
diff --git a/forge/stage4_review/calibrate_eye.py b/forge/stage4_review/calibrate_eye.py
new file mode 100644
index 0000000..9b46f92
--- /dev/null
+++ b/forge/stage4_review/calibrate_eye.py
@@ -0,0 +1,131 @@
+#!/usr/bin/env python3
+"""Divine Eye calibration harness (Plan 1.3 §5) — fit/validate the Eye on a labeled corpus.
+
+Before the Eye is allowed to HARD-GATE anything, it runs in report-only mode over a
+corpus of labeled (reference, render) pairs — known-good (the render should pass) and
+known-bad (it must be rejected). This harness runs divine_eye.evaluate on each pair,
+tabulates every signal per label class, and checks that the fidelity score cleanly
+SEPARATES good from bad. A corpus needs BOTH classes or it only measures false-rejects.
+
+Acceptance (absolute, on the corpus): every known-good pair passes AND every known-bad
+pair is rejected. Only then may report-only be flipped to hard-gate. Percentage targets
+(Q1/Q4/Q5) apply to a rolling window of ≥20 real builds, not this small corpus.
+
+Note: producing real RENDERS of the showcase demos needs a browser (deferred to the
+end-to-end infra). This harness is the deterministic, render-agnostic scaffold: give it
+whatever (reference, render) PNG pairs exist and it reports the separation + suggests a
+threshold. Pure stdlib + reuses divine_eye. Zero token.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from divine_eye import evaluate # noqa: E402
+
+
+def run_corpus(pairs: list[dict]) -> dict[str, Any]:
+ """pairs: [{"reference": path, "render": path, "label": "good"|"bad"}, ...].
+ Runs the Eye on each and aggregates per-signal stats per label class."""
+ rows: list[dict[str, Any]] = []
+ for pair in pairs:
+ result = evaluate(Path(pair["reference"]), Path(pair["render"]))
+ rows.append({
+ "label": pair.get("label", "unlabeled"),
+ "fidelity": result["fidelity"],
+ "verdict": result["verdict"],
+ "hardGateFailures": result["hardGateFailures"],
+ "signals": result["signals"],
+ "reference": pair["reference"],
+ "render": pair["render"],
+ })
+ return {"rows": rows, "signalStats": _signal_stats(rows)}
+
+
+def _signal_stats(rows: list[dict]) -> dict[str, Any]:
+ stats: dict[str, Any] = {}
+ for label in ("good", "bad"):
+ labelled = [r for r in rows if r["label"] == label]
+ if not labelled:
+ continue
+ fids = [r["fidelity"] for r in labelled]
+ stats[label] = {
+ "count": len(labelled),
+ "fidelityMin": round(min(fids), 4),
+ "fidelityMax": round(max(fids), 4),
+ "fidelityMean": round(sum(fids) / len(fids), 4),
+ }
+ return stats
+
+
+def separation(rows: list[dict]) -> dict[str, Any]:
+ """Does fidelity cleanly separate good from bad? A clean split exists when the
+ worst good fidelity is strictly above the best bad fidelity; the suggested
+ threshold sits between them."""
+ good = [r["fidelity"] for r in rows if r["label"] == "good"]
+ bad = [r["fidelity"] for r in rows if r["label"] == "bad"]
+ result: dict[str, Any] = {
+ "hasGood": bool(good),
+ "hasBad": bool(bad),
+ "minGoodFidelity": round(min(good), 4) if good else None,
+ "maxBadFidelity": round(max(bad), 4) if bad else None,
+ }
+ if good and bad:
+ min_good, max_bad = min(good), max(bad)
+ clean = min_good > max_bad
+ result["cleanSeparation"] = clean
+ result["suggestedThreshold"] = round((min_good + max_bad) / 2, 4) if clean else None
+ # absolute acceptance: every good passes at the current target, every bad rejected
+ result["allGoodPass"] = all(
+ r["verdict"] == "pass" for r in rows if r["label"] == "good"
+ )
+ result["allBadRejected"] = all(
+ r["verdict"] != "pass" for r in rows if r["label"] == "bad"
+ )
+ result["corpusAcceptable"] = result["allGoodPass"] and result["allBadRejected"]
+ else:
+ result["cleanSeparation"] = None
+ result["corpusAcceptable"] = False
+ result["warning"] = "corpus needs BOTH good and bad pairs (else it only measures false-rejects)"
+ return result
+
+
+def calibrate(pairs: list[dict]) -> dict[str, Any]:
+ corpus = run_corpus(pairs)
+ corpus["separation"] = separation(corpus["rows"])
+ corpus["reportOnly"] = True
+ corpus["note"] = ("report-only — flip to hard-gate ONLY when corpusAcceptable is true "
+ "(all good pass, all bad rejected)")
+ return corpus
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--corpus", required=True, type=Path,
+ help="JSON list of {reference, render, label} pairs")
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ pairs = json.loads(args.corpus.read_text(encoding="utf-8"))
+ result = calibrate(pairs)
+ except Exception as exc: # noqa: BLE001
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ if args.json:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ else:
+ sep = result["separation"]
+ print(f"corpus: {result['signalStats']}")
+ print(f"separation: clean={sep.get('cleanSeparation')} acceptable={sep.get('corpusAcceptable')} "
+ f"suggestedThreshold={sep.get('suggestedThreshold')}")
+ # exit 0 only when the corpus cleanly validates the Eye
+ return 0 if result["separation"].get("corpusAcceptable") else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/correction_loop.py b/forge/stage4_review/correction_loop.py
new file mode 100644
index 0000000..4428496
--- /dev/null
+++ b/forge/stage4_review/correction_loop.py
@@ -0,0 +1,170 @@
+#!/usr/bin/env python3
+"""Bounded stop-policy state machine for the Eye-driven correction loop.
+
+Plan 1.3 Phase 4, §3.6 — bounded correction-loop stop policy.
+
+This is a PURE-LOGIC module: no images, no repo imports, stdlib only. It decides,
+after each iteration of an expensive VLM-driven correction loop, whether to stop
+and what action the caller should take next.
+
+TERMINATION GUARANTEE
+---------------------
+A caller that loops::
+
+ while not decide(history)["stop"]:
+ history.append(one_more_iteration())
+
+can NEVER run more than ``max_iter`` iterations. The HARD_CEILING condition
+(priority 6) fires purely on ``len(history) >= max_iter`` and cannot be bypassed
+by any other state — not even a monotonically-improving-but-never-reaching-target
+loop. This is the single most important property of this module; do not weaken it.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+
+
+def decide(history, target_fidelity=0.85, max_iter=6, min_delta=0.02):
+ """Decide whether to stop the correction loop and what to do next.
+
+ Args:
+ history: list of per-iteration dicts in chronological order, each
+ ``{"fidelity": float in [0,1], "defectTags": list[str], "reverted": bool}``.
+ ``reverted`` means that iteration's correction lowered the score and
+ was auto-reverted.
+ target_fidelity: fidelity at/above which the model is considered good enough.
+ max_iter: non-bypassable ceiling on iterations — guarantees termination.
+ min_delta: minimum per-iteration fidelity gain below which progress has
+ plateaued.
+
+ Returns:
+ dict ``{"stop": bool, "action": str, "reason": str}``.
+
+ Stop conditions are evaluated in strict priority order; the first match wins.
+ """
+ # 1. EMPTY — nothing has happened yet.
+ if not history:
+ return {
+ "stop": False,
+ "action": "continue-iterating",
+ "reason": "no iterations yet",
+ }
+
+ last = history[-1]
+ prev = history[-2] if len(history) >= 2 else None
+
+ # 2. SUCCESS — target met and no open defects.
+ if last["fidelity"] >= target_fidelity and not last["defectTags"]:
+ return {
+ "stop": True,
+ "action": "continue",
+ "reason": "fidelity target met, no open defects",
+ }
+
+ # 3. REPEATED_DEFECT — a defect tag survived two consecutive iterations.
+ if prev is not None:
+ shared = set(last["defectTags"]) & set(prev["defectTags"])
+ if shared:
+ tag = sorted(shared)[0]
+ return {
+ "stop": True,
+ "action": "refine-spec",
+ "reason": f"same defect survived 2 consecutive fixes: {tag}",
+ }
+
+ # 4. OSCILLATION — repeated reverts, or a direction flip over the last 3 scores.
+ reverts = sum(1 for h in history if h.get("reverted"))
+ oscillating = reverts >= 2
+ if not oscillating and len(history) >= 3:
+ f0, f1, f2 = (h["fidelity"] for h in history[-3:])
+ d1 = f1 - f0
+ d2 = f2 - f1
+ # strictly down-then-up or up-then-down (both deltas non-zero, opposite signs)
+ if (d1 < 0 and d2 > 0) or (d1 > 0 and d2 < 0):
+ oscillating = True
+ if oscillating:
+ return {
+ "stop": True,
+ "action": "refine-spec",
+ "reason": "oscillating/thrashing",
+ }
+
+ # 5. PLATEAU — progress stalled below target.
+ if (
+ prev is not None
+ and (last["fidelity"] - prev["fidelity"]) < min_delta
+ and last["fidelity"] < target_fidelity
+ ):
+ return {
+ "stop": True,
+ "action": "request-input",
+ "reason": "progress plateaued below target (Δ<min_delta)",
+ }
+
+ # 6. HARD_CEILING — non-bypassable termination guarantee.
+ if len(history) >= max_iter:
+ return {
+ "stop": True,
+ "action": "request-input",
+ "reason": "hit MAX_ITER ceiling",
+ }
+
+ # 7. Otherwise — keep going.
+ return {
+ "stop": False,
+ "action": "continue-iterating",
+ "reason": "still improving toward target",
+ }
+
+
+def budget_exceeded(spent_tokens, budget):
+ """§3.6 budget circuit-breaker.
+
+ Returns True when the token budget is spent. The caller uses this to
+ HALT-and-ask-the-user; it never silently continues.
+ """
+ return spent_tokens >= budget
+
+
+def main(argv):
+ parser = argparse.ArgumentParser(
+ description="Bounded correction-loop stop policy (§3.6)."
+ )
+ parser.add_argument("--history", required=True, help="path to JSON list of iterations")
+ parser.add_argument("--target", type=float, default=0.85, help="target fidelity")
+ parser.add_argument("--max-iter", type=int, default=6, help="hard iteration ceiling")
+ parser.add_argument("--min-delta", type=float, default=0.02, help="plateau threshold")
+ parser.add_argument("--json", action="store_true", help="emit decision as JSON")
+
+ try:
+ args = parser.parse_args(argv)
+ with open(args.history, "r", encoding="utf-8") as fh:
+ history = json.load(fh)
+ if not isinstance(history, list):
+ raise ValueError("history JSON must be a list")
+
+ decision = decide(
+ history,
+ target_fidelity=args.target,
+ max_iter=args.max_iter,
+ min_delta=args.min_delta,
+ )
+
+ if args.json:
+ print(json.dumps(decision))
+ else:
+ print(
+ f"stop={decision['stop']} action={decision['action']} "
+ f"reason={decision['reason']}"
+ )
+ return 0 if not decision["stop"] else 1
+ except Exception as exc: # noqa: BLE001 - CLI boundary, surface any failure
+ print(f"error: {exc}")
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/diagnose_render.py b/forge/stage4_review/diagnose_render.py
new file mode 100644
index 0000000..4c70a2b
--- /dev/null
+++ b/forge/stage4_review/diagnose_render.py
@@ -0,0 +1,261 @@
+#!/usr/bin/env python3
+"""Tier-1 cheap, deterministic diagnostics — run BEFORE any expensive AI-vision
+comparison-sheet review (Plan 1.3 Workstream B). Pure Python 3.10+ standard
+library only, no PIL/numpy, matching the rest of forge/.
+
+Output is a machine-checked pass/fail plus numbers — no visual judgment, no
+AI-vision call. `orchestrate_passes.py` refuses to unlock the comparison-sheet
+step until a passing tier1Result exists for the current render's hash
+(Workstream D).
+
+Known scope limitation: per_part_color_delta compares the render's OVERALL
+dominant color clusters against each component's colorMaterialRecipe, not a
+true per-component cropped region (that would need per-component render-crop
+coordinates, which the pipeline does not yet track). This is a coarser signal
+than the plan's ideal, but per Risk R7, Tier 1 only needs to be discriminative
+enough to catch gross mismatches, not pixel-perfect — documented here rather
+than silently overclaimed.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
+from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
+from extract_part_color_recipe import lab_distance, lab_kmeans_palette, srgb_to_lab # noqa: E402
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage3_build"))
+from orchestrate_passes import DEFAULT_PASS_ORDER, load_spec # noqa: E402
+
+
+def color_is_gated(pass_id: str | None) -> bool:
+ """Per-part color fidelity is a hard criterion only from `material-pass` onward.
+
+ Blockout / structural / form-refinement passes render the model with clay
+ (materials deliberately stripped) so the silhouette can be judged on shape
+ alone — comparing their per-part color against a colored reference always
+ fails and says nothing about those passes' goals. Before material-pass (or
+ when the pass is unknown) the color delta is recorded as informational, never
+ a failure. This mirrors the skill doctrine: "blockout: silhouette reads
+ correctly WITHOUT materials".
+ """
+ if pass_id is None:
+ return False
+ try:
+ return DEFAULT_PASS_ORDER.index(pass_id) >= DEFAULT_PASS_ORDER.index("material-pass")
+ except ValueError:
+ return False
+
+
+SILHOUETTE_IOU_THRESHOLD = 0.85
+ASPECT_RATIO_DELTA_THRESHOLD = 0.05
+SCALE_DELTA_THRESHOLD = 0.08
+SYMMETRY_ERROR_THRESHOLD = 0.10
+COLOR_DELTA_E_THRESHOLD = 20.0 # generous vs. the JND (~2-3) to tolerate render/photo lighting gaps
+MASK_GRID_SIZE = 224
+
+
+def load_mask(png_path: Path, size: int = MASK_GRID_SIZE) -> list[bool]:
+ """Returns a flat row-major boolean grid of length size*size (foreground=True)."""
+ width, height, pixels, _warnings = load_image(png_path)
+ mask, _diag, _warn = build_foreground_mask(width, height, pixels)
+ resized: list[bool] = []
+ for y in range(size):
+ sy = min(height - 1, int(y * height / size))
+ for x in range(size):
+ sx = min(width - 1, int(x * width / size))
+ resized.append(mask[sy * width + sx])
+ return resized
+
+
+def silhouette_iou(reference_mask: list[bool], render_mask: list[bool]) -> float:
+ intersection = 0
+ union = 0
+ for ref, render in zip(reference_mask, render_mask):
+ if ref or render:
+ union += 1
+ if ref and render:
+ intersection += 1
+ return intersection / union if union else 1.0
+
+
+def bbox_of(mask: list[bool], size: int = MASK_GRID_SIZE) -> tuple[int, int, int, int]:
+ xs: list[int] = []
+ ys: list[int] = []
+ for index, value in enumerate(mask):
+ if value:
+ xs.append(index % size)
+ ys.append(index // size)
+ if not xs:
+ return (0, 0, 0, 0)
+ x0, x1 = min(xs), max(xs)
+ y0, y1 = min(ys), max(ys)
+ return (x0, y0, x1 - x0 + 1, y1 - y0 + 1)
+
+
+def proportion_delta(
+ reference_bbox: tuple[int, int, int, int],
+ render_bbox: tuple[int, int, int, int],
+) -> dict[str, float]:
+ _rx, _ry, rw, rh = reference_bbox
+ _dx, _dy, dw, dh = render_bbox
+ ref_ar = rw / rh if rh else 0.0
+ render_ar = dw / dh if dh else 0.0
+ aspect_ratio_delta = abs(ref_ar - render_ar) / ref_ar if ref_ar else (0.0 if render_ar == 0 else 1.0)
+ ref_area = rw * rh
+ render_area = dw * dh
+ scale_delta = abs(ref_area - render_area) / ref_area if ref_area else (0.0 if render_area == 0 else 1.0)
+ return {"aspect_ratio_delta": round(aspect_ratio_delta, 4), "scale_delta": round(scale_delta, 4)}
+
+
+def bilateral_symmetry_error(mask: list[bool], size: int = MASK_GRID_SIZE) -> float:
+ total = 0
+ mismatches = 0
+ for y in range(size):
+ row_offset = y * size
+ for x in range(size):
+ mirrored_x = size - 1 - x
+ total += 1
+ if mask[row_offset + x] != mask[row_offset + mirrored_x]:
+ mismatches += 1
+ return mismatches / total if total else 0.0
+
+
+def per_part_color_delta(recipes: list[dict[str, Any]], render_path: Path) -> dict[str, Any]:
+ """Compares each component's colorMaterialRecipe against the render's overall
+ dominant Lab-space color clusters (see module docstring for the per-component-
+ region scope limitation). Returns per-recipe delta-E and a pass/fail summary."""
+ if not recipes:
+ return {"checked": 0, "maxDeltaE": 0.0, "perComponent": []}
+ width, height, pixels, _warnings = load_image(render_path)
+ mask, _diag, _warn = build_foreground_mask(width, height, pixels)
+ foreground_lab = [srgb_to_lab((r, g, b)) for (r, g, b, _a), keep in zip(pixels, mask) if keep]
+ clusters = lab_kmeans_palette(foreground_lab, k=min(5, max(1, len(recipes))))
+ results = []
+ for recipe in recipes:
+ dominant = recipe.get("dominantAlbedo")
+ if not isinstance(dominant, str):
+ continue
+ try:
+ rgb_text = dominant[dominant.index("(") + 1 : dominant.index(")")]
+ r, g, b = (int(float(part.strip())) for part in rgb_text.split(",")[:3])
+ except (ValueError, IndexError):
+ continue
+ expected_lab = srgb_to_lab((r, g, b))
+ best_delta = min((lab_distance(expected_lab, c["center"]) for c in clusters), default=999.0)
+ results.append({"componentId": recipe.get("componentId"), "deltaE": round(best_delta, 2)})
+ max_delta = max((entry["deltaE"] for entry in results), default=0.0)
+ return {"checked": len(results), "maxDeltaE": round(max_delta, 2), "perComponent": results}
+
+
+def render_hash(render_path: Path) -> str:
+ return hashlib.sha256(render_path.read_bytes()).hexdigest()[:16]
+
+
+def run_tier1(
+ reference_path: Path,
+ render_path: Path,
+ spec_path: Path | None = None,
+ pass_id: str | None = None,
+) -> dict[str, Any]:
+ reference_mask = load_mask(reference_path)
+ render_mask = load_mask(render_path)
+
+ iou = silhouette_iou(reference_mask, render_mask)
+ reference_bbox = bbox_of(reference_mask)
+ render_bbox = bbox_of(render_mask)
+ proportions = proportion_delta(reference_bbox, render_bbox)
+ symmetry = bilateral_symmetry_error(render_mask)
+
+ checks: dict[str, Any] = {
+ "silhouetteIoU": round(iou, 4),
+ "aspectRatioDelta": proportions["aspect_ratio_delta"],
+ "scaleDelta": proportions["scale_delta"],
+ "bilateralSymmetryError": round(symmetry, 4),
+ }
+ failures: list[str] = []
+ if iou < SILHOUETTE_IOU_THRESHOLD:
+ failures.append(f"silhouette IoU {iou:.3f} is below threshold {SILHOUETTE_IOU_THRESHOLD}")
+ if proportions["aspect_ratio_delta"] > ASPECT_RATIO_DELTA_THRESHOLD:
+ failures.append(
+ f"aspect-ratio delta {proportions['aspect_ratio_delta']:.3f} exceeds "
+ f"threshold {ASPECT_RATIO_DELTA_THRESHOLD}"
+ )
+ if proportions["scale_delta"] > SCALE_DELTA_THRESHOLD:
+ failures.append(f"scale delta {proportions['scale_delta']:.3f} exceeds threshold {SCALE_DELTA_THRESHOLD}")
+
+ if spec_path is not None:
+ spec = load_spec(spec_path)
+ recipes = [
+ component["colorMaterialRecipe"]
+ for component in spec.get("componentTree", [])
+ if isinstance(component, dict) and isinstance(component.get("colorMaterialRecipe"), dict)
+ ]
+ color_report = per_part_color_delta(recipes, render_path)
+ gated = color_is_gated(pass_id)
+ color_report["gated"] = gated
+ checks["colorDelta"] = color_report
+ if gated and color_report["maxDeltaE"] > COLOR_DELTA_E_THRESHOLD:
+ failures.append(
+ f"max per-part color delta-E {color_report['maxDeltaE']} exceeds "
+ f"threshold {COLOR_DELTA_E_THRESHOLD}"
+ )
+
+ return {
+ "passed": not failures,
+ "checks": checks,
+ "failures": failures,
+ "renderHash": render_hash(render_path),
+ "passId": pass_id,
+ }
+
+
+def record_tier1_result(spec: dict[str, Any], result: dict[str, Any]) -> None:
+ """Appends to spec['tier1Results'] so orchestrate_passes.py (Workstream D) can
+ refuse to unlock the Tier-2 comparison-sheet step until a passing entry exists
+ for the current pass/render hash."""
+ results = spec.setdefault("tier1Results", [])
+ if isinstance(results, list):
+ results.append(result)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--reference", type=Path, required=True)
+ parser.add_argument("--render", type=Path, required=True)
+ parser.add_argument("--spec", type=Path, help="ObjectSculptSpec JSON (for per-part color delta + recording the result)")
+ parser.add_argument("--pass-id")
+ parser.add_argument("--in-place", action="store_true", help="Record the result into --spec")
+ parser.add_argument("--out-spec", type=Path, help="Write the spec with the recorded result to this path")
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+
+ try:
+ spec_path = args.spec.expanduser().resolve() if args.spec else None
+ result = run_tier1(
+ args.reference.expanduser().resolve(),
+ args.render.expanduser().resolve(),
+ spec_path,
+ args.pass_id,
+ )
+ if spec_path and (args.in_place or args.out_spec):
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
+ record_tier1_result(spec, result)
+ output = spec_path if args.in_place else args.out_spec.expanduser().resolve()
+ output.parent.mkdir(parents=True, exist_ok=True)
+ output.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ return 0 if result["passed"] else 1
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/diagnose_render_multi_angle.py b/forge/stage4_review/diagnose_render_multi_angle.py
new file mode 100644
index 0000000..1efb4ab
--- /dev/null
+++ b/forge/stage4_review/diagnose_render_multi_angle.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""Deterministic Phase-3 §3.2 multi-angle "degenerate-view" check.
+
+A flat plane faking a 3D volume looks convincing from the single reference
+camera angle, but its silhouette AREA collapses when the camera orbits: a
+billboard seen edge-on nearly vanishes. This module exploits that. Given a set
+of already-rendered PNGs of the SAME object from different camera angles, it
+measures each frame's foreground silhouette area (as a fraction of the frame)
+and flags "degenerate-view" when a non-reference angle's area collapses far
+below the reference angle's area.
+
+This check is deterministic and costs zero tokens: it is pure pixel arithmetic
+over foreground masks, reusing the stage1 intake loader/segmenter.
+
+Scope: this module only ANALYZES already-captured PNGs. Driving an actual
+browser / renderer to PRODUCE the orbit PNGs is a separate concern handled
+elsewhere in the pipeline.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
+from extract_pbr_evidence import load_image, build_foreground_mask, mask_bbox # noqa: E402
+
+
+def silhouette_area_fraction(png_path: Path) -> float:
+ """Return the fraction of the frame occupied by the object's silhouette.
+
+ Loads the image, segments the foreground from the background, and returns
+ (foreground pixel count / total pixels). ``mask_bbox`` is imported and kept
+ available for callers/tests that want the tight silhouette box, but the area
+ fraction itself is computed from the full mask so a small-but-wide sliver
+ is scored purely by how much of the frame it actually fills.
+ """
+ path = Path(png_path)
+ width, height, pixels, _warnings = load_image(path)
+ mask, _diag, mask_warnings = build_foreground_mask(width, height, pixels)
+ total = len(mask)
+ if total <= 0:
+ return 0.0
+ # HARDENING (lead, from the multiangle worker's finding): build_foreground_mask has
+ # a <3.5%-coverage safety fallback that INVERTS a tiny mask to "all opaque pixels"
+ # (coverage → ~1.0). For degenerate-view detection that is exactly backwards — a plane
+ # orbited edge-on yields a near-zero silhouette that MUST read as collapsed, not full.
+ # So when the fallback fired, report near-zero (the true, pre-inversion silhouette).
+ if any("tiny" in str(w).lower() for w in mask_warnings):
+ return 0.0
+ foreground = sum(1 for value in mask if value)
+ return foreground / total
+
+
+def analyze_angles(
+ reference_png: Path,
+ orbit_pngs: list[Path],
+ collapse_ratio: float = 0.15,
+) -> dict[str, Any]:
+ """Compare each orbit angle's silhouette area against the reference angle.
+
+ For every orbit angle, ``ratio = orbit_area / reference_area``. When the
+ reference area is 0 the ratio is treated as 0.0 (divide-by-zero guard). Any
+ orbit angle whose ratio is below ``collapse_ratio`` is flagged degenerate:
+ the object nearly vanished from that viewpoint, which is what a flat plane
+ faking a volume does when orbited.
+ """
+ reference_area = silhouette_area_fraction(Path(reference_png))
+ angles: list[dict[str, Any]] = []
+ any_degenerate = False
+ for orbit in orbit_pngs:
+ orbit_area = silhouette_area_fraction(Path(orbit))
+ ratio = 0.0 if reference_area <= 0.0 else orbit_area / reference_area
+ degenerate = ratio < collapse_ratio
+ if degenerate:
+ any_degenerate = True
+ angles.append(
+ {
+ "path": str(orbit),
+ "areaFraction": orbit_area,
+ "ratio": ratio,
+ "degenerate": degenerate,
+ }
+ )
+ return {
+ "referenceAreaFraction": reference_area,
+ "angles": angles,
+ "degenerate": any_degenerate,
+ "collapseRatio": collapse_ratio,
+ "note": (
+ "deterministic; zero token; a flat-plane-faking-a-volume collapses "
+ "in silhouette area when orbited"
+ ),
+ }
+
+
+def _format_summary(result: dict[str, Any]) -> str:
+ lines = [
+ f"reference area fraction: {result['referenceAreaFraction']:.4f}",
+ f"collapse ratio threshold: {result['collapseRatio']}",
+ ]
+ for angle in result["angles"]:
+ flag = "DEGENERATE" if angle["degenerate"] else "ok"
+ lines.append(
+ f" [{flag}] {angle['path']} "
+ f"area={angle['areaFraction']:.4f} ratio={angle['ratio']:.4f}"
+ )
+ verdict = "DEGENERATE-VIEW DETECTED" if result["degenerate"] else "no degenerate view"
+ lines.append(f"verdict: {verdict}")
+ return "\n".join(lines)
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--reference", type=Path, required=True, help="reference-angle PNG")
+ parser.add_argument(
+ "--orbit",
+ type=Path,
+ action="append",
+ default=[],
+ help="orbit-angle PNG (repeat for each angle)",
+ )
+ parser.add_argument("--collapse-ratio", type=float, default=0.15)
+ parser.add_argument("--json", action="store_true", help="print JSON instead of a summary")
+ args = parser.parse_args(argv)
+
+ try:
+ result = analyze_angles(args.reference, args.orbit, args.collapse_ratio)
+ if args.json:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ else:
+ print(_format_summary(result))
+ return 1 if result["degenerate"] else 0
+ except Exception as exc:
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/divine_eye.py b/forge/stage4_review/divine_eye.py
new file mode 100644
index 0000000..f5a8079
--- /dev/null
+++ b/forge/stage4_review/divine_eye.py
@@ -0,0 +1,431 @@
+#!/usr/bin/env python3
+"""The Divine Eye (đôi mắt thần) — deterministic multi-signal render↔reference evaluator.
+
+Plan 1.3 Phase 3 core (§3.1 ensemble, §3.3 combination + self-uncertainty). This is
+the single authority the correction loop asks "how close is this render to the
+reference, and what's wrong?". It is DETERMINISTIC and ZERO-TOKEN: pure Python +
+pixel math, reusing the Tier-1 primitives (diagnose_render) + the shared pHash. No
+LLM/VLM call lives here — the VLM layer (§3.4) is a separate, gated, subordinate step.
+
+Signals (each → normalized [0,1] agreement + a defect tag when it fails):
+ HARD gates (a fail cannot be averaged away):
+ - silhouette IoU (< 0.85 ⇒ reject)
+ - scale delta (> 0.08 ⇒ reject)
+ SOFT signals (ensemble-weighted):
+ - proportion / aspect ratio
+ - bilateral symmetry
+ - pHash structural similarity
+ - global SSIM (luma)
+ - edge-map overlap (Sobel linework)
+ - blowout parity (QA: blown-highlight fraction vs reference)
+ - flat-region ratio (QA: material reacting to light, not a dead flat fill)
+ - tonal/contrast parity (QA: luma-histogram match)
+
+Deferred to later Phase-3 increments (documented, not silently missing):
+ Directional Chamfer Distance, OSIM objectness (numpy+weights, R-DEP/R-OSIM-EFFORT),
+ multi-angle browser capture (diagnose_render_multi_angle.py), CIE-Lab per-region ΔE
+ wiring (available via extract_part_color_recipe; folded in with per-feature §3.8).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from diagnose_render import ( # noqa: E402
+ bbox_of,
+ bilateral_symmetry_error,
+ load_mask,
+ proportion_delta,
+ silhouette_iou,
+)
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
+from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
+
+from objectness import objectness_similarity # noqa: E402 (stdlib OSIM-lite, same dir)
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from color_metrics import ciede2000, srgb_to_lab # noqa: E402
+from image_hash import normalized_similarity, phash_from_image # noqa: E402
+
+# Hard-gate thresholds (shared with diagnose_render; calibratable in Phase 5).
+IOU_HARD_MIN = 0.85
+SCALE_HARD_MAX = 0.08
+# Ensemble: fidelity target + disagreement (self-uncertainty) spread.
+FIDELITY_TARGET = 0.85
+DISAGREEMENT_SPREAD = 0.35 # if soft-signal spread exceeds this ⇒ low-confidence → probe
+RECON_OBJ_MIN = 0.48 # objectness ≥ this rescues an IoU-only hard reject → probe (recon mode).
+# Separates same-object-different-framing (real pairs ~0.53–0.58) from a
+# genuinely different shape (~0.43). Rescue only ever downgrades reject→probe.
+LUMA_SIZE = 64 # SSIM / tonal / blowout / flat work on this downsampled luma grid
+EDGE_SIZE = 96 # edge overlap grid
+HUE_ZONE_DELTA_E = 2.3 # per-band CIEDE2000 "same hue zone" tolerance (Context Part 2.2)
+HUE_ZONE_BANDS = 8 # bands sampled along the axis for hue_zone_parity
+COLOR_SAMPLE = 160 # coarse per-axis subsample cap for colour helpers (perf on full-res refs)
+
+
+def _banded_median_lab(png_path: Path, axis: str, bands: int) -> list[tuple[float, float, float] | None]:
+ """Median CIELAB per foreground-masked band along the axis (axis 'u'=x, 'v'=y).
+ Colour-aware (not luma) — used only by hue_zone_parity, which is report-only until calibrated."""
+ width, height, pixels, _ = load_image(png_path)
+ mask, _meta, _warn = build_foreground_mask(width, height, pixels)
+ span = width if axis == "u" else height
+ band = max(1, span // bands)
+ # Subsample on a coarse grid (≤ COLOR_SAMPLE px/axis) so full-res references stay O(fast) —
+ # median hue is stable under downsampling (Context Part 2.5 perf note).
+ sx = max(1, width // COLOR_SAMPLE)
+ sy = max(1, height // COLOR_SAMPLE)
+ out: list[tuple[float, float, float] | None] = []
+ for b in range(bands):
+ lo = b * band
+ hi = span if b == bands - 1 else (b + 1) * band
+ rs: list[int] = []
+ gs: list[int] = []
+ bs: list[int] = []
+ for y in range(0, height, sy):
+ for x in range(0, width, sx):
+ coord = x if axis == "u" else y
+ if coord < lo or coord >= hi:
+ continue
+ idx = y * width + x
+ if idx >= len(mask) or not mask[idx]:
+ continue
+ r, g, bl, _a = pixels[idx]
+ rs.append(r)
+ gs.append(g)
+ bs.append(bl)
+ if not rs:
+ out.append(None)
+ continue
+ rs.sort(); gs.sort(); bs.sort()
+ m = len(rs) // 2
+ out.append(srgb_to_lab((rs[m], gs[m], bs[m])))
+ return out
+
+
+def _foreground_hsv_stats(png_path: Path) -> tuple[float, float]:
+ """Saturation-weighted mean (hueDeg, saturation) over the foreground. Colour-aware."""
+ import colorsys
+ import math as _m
+ width, height, pixels, _ = load_image(png_path)
+ mask, _meta, _warn = build_foreground_mask(width, height, pixels)
+ sx = max(1, width // COLOR_SAMPLE)
+ sy = max(1, height // COLOR_SAMPLE)
+ sc = ss = wsum = sat_sum = 0.0
+ n = 0
+ for y in range(0, height, sy):
+ for x in range(0, width, sx):
+ idx = y * width + x
+ if idx >= len(mask) or not mask[idx]:
+ continue
+ r, g, b, _a = pixels[idx]
+ h, s, _v = colorsys.rgb_to_hsv(r / 255.0, g / 255.0, b / 255.0)
+ sat_sum += s
+ n += 1
+ if s > 0.15:
+ sc += s * _m.cos(2 * _m.pi * h)
+ ss += s * _m.sin(2 * _m.pi * h)
+ wsum += s
+ mean_sat = sat_sum / n if n else 0.0
+ mean_hue = (_m.degrees(_m.atan2(ss, sc)) % 360.0) if wsum > 0 else 0.0
+ return mean_hue, mean_sat
+
+
+def specular_wash(reference_png: Path, render_png: Path) -> dict[str, Any]:
+ """Detect the envMap/metalness 'hue theft': the render desaturates a saturated reference AND
+ drifts its hue toward cyan (~180°). Report-only — advisory, never a gate (lighting legitimately
+ shifts hue). Returns {satRatio, hueDriftDeg, towardCyan, flagged}. (Context Part 3.2)."""
+ ref_hue, ref_sat = _foreground_hsv_stats(reference_png)
+ ren_hue, ren_sat = _foreground_hsv_stats(render_png)
+ sat_ratio = (ren_sat / ref_sat) if ref_sat > 1e-6 else 1.0
+ # circular hue drift toward cyan (180°): did the render move closer to 180 than the reference?
+ ref_to_cyan = min(abs(ref_hue - 180.0), 360.0 - abs(ref_hue - 180.0))
+ ren_to_cyan = min(abs(ren_hue - 180.0), 360.0 - abs(ren_hue - 180.0))
+ toward_cyan = ren_to_cyan < ref_to_cyan
+ flagged = ref_sat > 0.35 and sat_ratio < 0.6 and toward_cyan
+ return {
+ "satRatio": round(sat_ratio, 3),
+ "hueDriftDeg": round(ref_to_cyan - ren_to_cyan, 1),
+ "towardCyan": toward_cyan,
+ "flagged": flagged,
+ "advice": "lower metalness / envMapIntensity (candy-coat dielectric recipe)" if flagged else None,
+ }
+
+
+def hue_zone_parity(reference_png: Path, render_png: Path, axis: str = "u",
+ bands: int = HUE_ZONE_BANDS) -> float:
+ """Fraction of along-axis bands whose median colour matches the reference within CIEDE2000
+ ≤ HUE_ZONE_DELTA_E. Catches "purple rendered blue" that luma/structure signals miss.
+ Report-only (no ensemble weight) until calibrated on the labeled corpus."""
+ ref = _banded_median_lab(reference_png, axis, bands)
+ ren = _banded_median_lab(render_png, axis, bands)
+ matched = 0
+ counted = 0
+ for a, b in zip(ref, ren):
+ if a is None or b is None:
+ continue
+ counted += 1
+ if ciede2000(a, b) <= HUE_ZONE_DELTA_E:
+ matched += 1
+ return matched / counted if counted else 0.0
+
+
+def load_luma(png_path: Path, size: int) -> list[float]:
+ """Box-average downsample of Rec.709 luma to size×size, normalized 0..1."""
+ width, height, pixels, _warn = load_image(png_path)
+ acc = [0.0] * (size * size)
+ cnt = [0] * (size * size)
+ for idx, (r, g, b, _a) in enumerate(pixels):
+ x = idx % width
+ y = idx // width
+ if y >= height:
+ break
+ cell = min(size - 1, y * size // height) * size + min(size - 1, x * size // width)
+ acc[cell] += (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255.0
+ cnt[cell] += 1
+ return [acc[i] / cnt[i] if cnt[i] else 0.0 for i in range(size * size)]
+
+
+def _mean(xs: list[float]) -> float:
+ return sum(xs) / len(xs) if xs else 0.0
+
+
+def global_ssim(a: list[float], b: list[float]) -> float:
+ """Single-window SSIM over the whole downsampled luma image (structure signal)."""
+ n = len(a)
+ if n == 0 or len(b) != n:
+ return 0.0
+ mu_a, mu_b = _mean(a), _mean(b)
+ var_a = _mean([(x - mu_a) ** 2 for x in a])
+ var_b = _mean([(x - mu_b) ** 2 for x in b])
+ cov = _mean([(a[i] - mu_a) * (b[i] - mu_b) for i in range(n)])
+ c1, c2 = 0.01 ** 2, 0.03 ** 2
+ ssim = ((2 * mu_a * mu_b + c1) * (2 * cov + c2)) / (
+ (mu_a ** 2 + mu_b ** 2 + c1) * (var_a + var_b + c2)
+ )
+ return max(0.0, min(1.0, ssim))
+
+
+def _sobel_edges(luma: list[float], size: int, thresh: float = 0.12) -> list[bool]:
+ edges = [False] * (size * size)
+ for y in range(1, size - 1):
+ for x in range(1, size - 1):
+ def g(dx, dy):
+ return luma[(y + dy) * size + (x + dx)]
+ gx = (g(-1, -1) + 2 * g(-1, 0) + g(-1, 1)) - (g(1, -1) + 2 * g(1, 0) + g(1, 1))
+ gy = (g(-1, -1) + 2 * g(0, -1) + g(1, -1)) - (g(-1, 1) + 2 * g(0, 1) + g(1, 1))
+ if math.hypot(gx, gy) > thresh:
+ edges[y * size + x] = True
+ return edges
+
+
+def edge_overlap(a: list[float], b: list[float], size: int) -> float:
+ ea, eb = _sobel_edges(a, size), _sobel_edges(b, size)
+ inter = union = 0
+ for i in range(len(ea)):
+ if ea[i] or eb[i]:
+ union += 1
+ if ea[i] and eb[i]:
+ inter += 1
+ return inter / union if union else 1.0
+
+
+def _blown_fraction(luma: list[float], hi: float = 0.95) -> float:
+ return sum(1 for v in luma if v >= hi) / max(1, len(luma))
+
+
+def blowout_parity(ref: list[float], ren: list[float]) -> float:
+ diff = abs(_blown_fraction(ren) - _blown_fraction(ref))
+ return max(0.0, 1.0 - diff * 4.0) # 25% extra blown pixels ⇒ score 0
+
+
+def flat_fraction(luma: list[float], size: int, eps: float = 0.02) -> float:
+ """Fraction of pixels whose local gradient is ~0 (a dead flat fill)."""
+ flat = 0
+ total = 0
+ for y in range(1, size - 1):
+ for x in range(1, size - 1):
+ c = luma[y * size + x]
+ grad = abs(c - luma[y * size + x - 1]) + abs(c - luma[(y - 1) * size + x])
+ total += 1
+ if grad < eps:
+ flat += 1
+ return flat / total if total else 0.0
+
+
+def tonal_parity(ref: list[float], ren: list[float], bins: int = 16) -> float:
+ def hist(xs):
+ h = [0] * bins
+ for v in xs:
+ h[min(bins - 1, int(v * bins))] += 1
+ tot = sum(h) or 1
+ return [c / tot for c in h]
+ ha, hb = hist(ref), hist(ren)
+ l1 = sum(abs(ha[i] - hb[i]) for i in range(bins))
+ return max(0.0, 1.0 - l1 / 2.0) # L1 over two distributions ∈ [0,2]
+
+
+def evaluate(reference_png: Path, render_png: Path) -> dict[str, Any]:
+ """Run all deterministic signals and combine into a verdict + routing action."""
+ ref_mask = load_mask(reference_png)
+ ren_mask = load_mask(render_png)
+ ref_luma = load_luma(reference_png, LUMA_SIZE)
+ ren_luma = load_luma(render_png, LUMA_SIZE)
+ ref_edge = load_luma(reference_png, EDGE_SIZE)
+ ren_edge = load_luma(render_png, EDGE_SIZE)
+ rw, rh, rpx, _ = load_image(reference_png)
+ vw, vh, vpx, _ = load_image(render_png)
+
+ iou = silhouette_iou(ref_mask, ren_mask)
+ prop = proportion_delta(bbox_of(ref_mask), bbox_of(ren_mask))
+ scale_delta = prop.get("scaleDelta", 0.0)
+ aspect_delta = prop.get("aspectRatioDelta", 0.0)
+ # symmetry + flat-region are PARITY signals (render vs reference), NOT absolute —
+ # a legitimately asymmetric or flat-lit subject must not be penalized when the
+ # render matches the reference. score = 1 when render is as (a)symmetric / as flat
+ # as the reference; drops when the render diverges (e.g. render flatter ⇒ material
+ # not reacting to light).
+ sym_ref = bilateral_symmetry_error(ref_mask)
+ sym_ren = bilateral_symmetry_error(ren_mask)
+ sym = max(0.0, 1.0 - abs(sym_ren - sym_ref) / 0.10)
+ flat_ref = flat_fraction(ref_luma, LUMA_SIZE)
+ flat_ren = flat_fraction(ren_luma, LUMA_SIZE)
+ flat = max(0.0, 1.0 - abs(flat_ren - flat_ref) * 4.0)
+ phash_sim = normalized_similarity(phash_from_image(rw, rh, rpx), phash_from_image(vw, vh, vpx))
+ ssim = global_ssim(ref_luma, ren_luma)
+ edges = edge_overlap(ref_edge, ren_edge, EDGE_SIZE)
+ blow = blowout_parity(ref_luma, ren_luma)
+ tonal = tonal_parity(ref_luma, ren_luma)
+ # OSIM-lite objectness (stdlib HOG-like, bg/pose/scale/brightness-invariant). Graceful:
+ # if it errors it degrades to absent (must-not-block, R-OSIM-EFFORT). It is the one
+ # signal that stays meaningful for photo-vs-procedural where IoU/SSIM/edge collapse.
+ try:
+ objectness: float | None = objectness_similarity(reference_png, render_png)
+ except Exception:
+ objectness = None
+
+ # hue_zone_parity: colour-aware along-axis hue match (CIEDE2000). REPORT-ONLY — not in the
+ # weighted ensemble until calibrated on the labeled corpus. Catches "purple→blue" that
+ # every luma/structure signal above is blind to. Graceful: degrades to None on error.
+ try:
+ hue_zone: float | None = hue_zone_parity(reference_png, render_png)
+ except Exception:
+ hue_zone = None
+ try:
+ spec_wash: dict[str, Any] | None = specular_wash(reference_png, render_png)
+ except Exception:
+ spec_wash = None
+
+ # HARD gates: a fail is an immediate reject with a specific numeric reason.
+ hard_failures: list[str] = []
+ if iou < IOU_HARD_MIN:
+ hard_failures.append(f"silhouette IoU {iou:.3f} < {IOU_HARD_MIN}")
+ if scale_delta > SCALE_HARD_MAX:
+ hard_failures.append(f"scale delta {scale_delta:.3f} > {SCALE_HARD_MAX}")
+
+ # SOFT signals → weighted ensemble fidelity. Weights are provisional (Phase 5
+ # calibrates them on the known-good/known-bad corpus); recorded here so they are
+ # auditable, not magic.
+ soft = {
+ "proportion": (max(0.0, 1.0 - aspect_delta / 0.05), 1.0),
+ "symmetry": (sym, 0.5),
+ "phash": (phash_sim, 1.0),
+ "ssim": (ssim, 1.5),
+ "edgeOverlap": (edges, 1.0),
+ "blowoutParity": (blow, 0.8),
+ "flatRegion": (flat, 0.8),
+ "tonalParity": (tonal, 1.0),
+ }
+ if objectness is not None:
+ soft["objectness"] = (objectness, 1.5) # strongest structural signal when present
+ weighted = sum(s * w for s, w in soft.values())
+ total_w = sum(w for _s, w in soft.values())
+ fidelity = weighted / total_w if total_w else 0.0
+
+ soft_scores = [s for s, _w in soft.values()]
+ spread = max(soft_scores) - min(soft_scores) if soft_scores else 0.0
+
+ # Verdict + routing (deterministic function of which signal failed — §3.5).
+ if hard_failures:
+ verdict, action = "reject", "refine-code"
+ elif spread > DISAGREEMENT_SPREAD and fidelity < FIDELITY_TARGET:
+ verdict, action = "low-confidence", "probe"
+ elif fidelity >= FIDELITY_TARGET:
+ verdict, action = "pass", "continue"
+ else:
+ verdict, action = "reject", "refine-code"
+
+ # Reconstruction-mode rescue: a *photo* reference vs a *procedural* render fails the
+ # silhouette-IoU hard gate purely from framing/background/scale mismatch. When the only
+ # hard failure is IoU AND objectness says "same object" (high, brightness/bg-invariant),
+ # downgrade the confident reject to a probe rather than hard-failing a faithful build.
+ # Never rescues a scale-delta failure or a genuinely different object (low objectness).
+ reconstruction_suspected = False
+ if hard_failures and objectness is not None and objectness >= RECON_OBJ_MIN:
+ if all("silhouette IoU" in f for f in hard_failures):
+ reconstruction_suspected = True
+ verdict, action = "low-confidence", "probe"
+
+ return {
+ "verdict": verdict,
+ "action": action,
+ "fidelity": round(fidelity, 4),
+ "fidelityTarget": FIDELITY_TARGET,
+ "hardGateFailures": hard_failures,
+ "disagreementSpread": round(spread, 4),
+ "signals": {
+ "silhouetteIoU": round(iou, 4),
+ "scaleDelta": round(scale_delta, 4),
+ "aspectRatioDelta": round(aspect_delta, 4),
+ "symmetryParity": round(sym, 4),
+ "phashSimilarity": round(phash_sim, 4),
+ "ssim": round(ssim, 4),
+ "edgeOverlap": round(edges, 4),
+ "blowoutParity": round(blow, 4),
+ "flatRegionScore": round(flat, 4),
+ "tonalParity": round(tonal, 4),
+ "objectness": round(objectness, 4) if objectness is not None else None,
+ "hueZoneParity": round(hue_zone, 4) if hue_zone is not None else None,
+ },
+ "specularWash": spec_wash,
+ "reportOnlySignals": ["hueZoneParity", "specularWash"],
+ "reconstructionModeSuspected": reconstruction_suspected,
+ "weights": {k: w for k, (_s, w) in soft.items()},
+ "reference": str(reference_png.resolve()),
+ "render": str(render_png.resolve()),
+ "note": "deterministic ensemble; zero VLM/token. hueZoneParity is REPORT-ONLY (colour-aware, "
+ "CIEDE2000) — not yet in the weighted fidelity; promote after corpus calibration. "
+ "VLM layer (§3.4) runs only if this passes.",
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--reference", required=True, type=Path)
+ parser.add_argument("--render", required=True, type=Path)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ result = evaluate(args.reference.expanduser().resolve(), args.render.expanduser().resolve())
+ except Exception as exc: # noqa: BLE001
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ if args.json:
+ print(json.dumps(result, indent=2, ensure_ascii=False))
+ else:
+ print(f"{result['verdict'].upper()} → {result['action']} fidelity={result['fidelity']} "
+ f"(target {result['fidelityTarget']})")
+ for f in result["hardGateFailures"]:
+ print(f" HARD: {f}")
+ # exit 0 only on a clean pass; non-zero otherwise so a pipeline can gate on it.
+ return 0 if result["verdict"] == "pass" else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/objectness.py b/forge/stage4_review/objectness.py
new file mode 100644
index 0000000..38f154f
--- /dev/null
+++ b/forge/stage4_review/objectness.py
@@ -0,0 +1,143 @@
+#!/usr/bin/env python3
+"""Stdlib objectness proxy (OSIM-lite) for the Divine Eye — Plan 1.3 task #18, Pillar-1 safe.
+
+A pure-Python gradient-orientation-histogram (HOG-like) descriptor compared by cosine
+similarity. The object's foreground is masked, cropped to its bbox, and resampled to a
+canonical square grid, so the descriptor is invariant to:
+ - background (foreground mask drops it)
+ - position (bbox crop)
+ - scale (resample to a fixed grid)
+ - absolute brightness / colour (gradient *orientations*, per-cell L2-normalised)
+
+Those are exactly the photo-vs-procedural axes where silhouette-IoU, SSIM and edge-overlap
+collapse (a faithful reconstruction on a dark background vs a white-bg studio photo). This
+is the graceful *stdlib floor* objectness signal — no numpy, no weights, no download. A
+learned CNN-OSIM remains an optional V2 upgrade behind the same signal name.
+
+CLI: objectness.py --reference REF --render RENDER [--json]
+API: objectness_similarity(ref_path, render_path) -> float in [0,1]
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import sys
+from pathlib import Path
+from typing import Any
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage1_intake"))
+from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402
+
+GRID = 96 # canonical square the object bbox is resampled to
+CELLS = 8 # CELLS x CELLS spatial cells
+BINS = 9 # orientation bins over 0..180 (unsigned gradient)
+
+
+def _to_gray(pixels: list[tuple[int, int, int, int]]) -> list[int]:
+ return [(p[0] * 30 + p[1] * 59 + p[2] * 11) // 100 for p in pixels]
+
+
+def _bbox(mask: list[bool], w: int, h: int) -> tuple[int, int, int, int]:
+ minx = miny = 1 << 30
+ maxx = maxy = -1
+ for y in range(h):
+ row = y * w
+ for x in range(w):
+ if mask[row + x]:
+ if x < minx:
+ minx = x
+ if x > maxx:
+ maxx = x
+ if y < miny:
+ miny = y
+ if y > maxy:
+ maxy = y
+ if maxx < 0: # empty mask -> whole frame
+ return (0, 0, w, h)
+ return (minx, miny, maxx + 1, maxy + 1)
+
+
+def _resample_bbox(gray: list[int], w: int, h: int, box: tuple[int, int, int, int], n: int) -> list[float]:
+ x0, y0, x1, y1 = box
+ bw = max(1, x1 - x0)
+ bh = max(1, y1 - y0)
+ out = [0.0] * (n * n)
+ for j in range(n):
+ sy = min(h - 1, y0 + (j * bh) // n)
+ base = sy * w
+ for i in range(n):
+ sx = min(w - 1, x0 + (i * bw) // n)
+ out[j * n + i] = float(gray[base + sx])
+ return out
+
+
+def descriptor(path: str | Path) -> list[float]:
+ """HOG-like descriptor of the object's foreground, canonicalised for pose/scale/bg."""
+ w, h, pixels, _ = load_image(Path(path))
+ gray = _to_gray(pixels)
+ mask, _diag, _warn = build_foreground_mask(w, h, pixels)
+ x0, y0, x1, y1 = _bbox(mask, w, h)
+ # pad the bbox so the object's silhouette contour (its strongest shape cue) lands
+ # INSIDE the resampled grid — a solid object cropped flush would otherwise put its
+ # only edges on the border (skipped by the gradient loop) and yield a zero descriptor.
+ px = int((x1 - x0) * 0.10) + 2
+ py = int((y1 - y0) * 0.10) + 2
+ box = (max(0, x0 - px), max(0, y0 - py), min(w, x1 + px), min(h, y1 + py))
+ g = _resample_bbox(gray, w, h, box, GRID)
+
+ hist = [0.0] * (CELLS * CELLS * BINS)
+ cell = GRID // CELLS
+ for y in range(1, GRID - 1):
+ row = y * GRID
+ cy = min(CELLS - 1, y // cell)
+ for x in range(1, GRID - 1):
+ gx = g[row + x + 1] - g[row + x - 1]
+ gy = g[(y + 1) * GRID + x] - g[(y - 1) * GRID + x]
+ mag = math.hypot(gx, gy)
+ if mag < 1e-6:
+ continue
+ ang = math.degrees(math.atan2(gy, gx)) % 180.0
+ b = int(ang / 180.0 * BINS) % BINS
+ cx = min(CELLS - 1, x // cell)
+ hist[(cy * CELLS + cx) * BINS + b] += mag
+ # per-cell L2 block normalisation -> contrast/brightness invariance
+ for c in range(CELLS * CELLS):
+ base = c * BINS
+ norm = math.sqrt(sum(hist[base + k] ** 2 for k in range(BINS))) + 1e-6
+ for k in range(BINS):
+ hist[base + k] /= norm
+ return hist
+
+
+def cosine(a: list[float], b: list[float]) -> float:
+ dot = sum(x * y for x, y in zip(a, b))
+ na = math.sqrt(sum(x * x for x in a))
+ nb = math.sqrt(sum(y * y for y in b))
+ if na < 1e-9 or nb < 1e-9:
+ return 0.0
+ return max(0.0, min(1.0, dot / (na * nb)))
+
+
+def objectness_similarity(ref_path: str | Path, render_path: str | Path) -> float:
+ """Cosine similarity of the two objectness descriptors, in [0,1]. 1 = same structure."""
+ return cosine(descriptor(ref_path), descriptor(render_path))
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description="Stdlib objectness (OSIM-lite) similarity")
+ ap.add_argument("--reference", required=True)
+ ap.add_argument("--render", required=True)
+ ap.add_argument("--json", action="store_true")
+ args = ap.parse_args(argv)
+ score = objectness_similarity(args.reference, args.render)
+ out: dict[str, Any] = {"objectness": round(score, 4), "grid": GRID, "cells": CELLS, "bins": BINS}
+ if args.json:
+ print(json.dumps(out))
+ else:
+ print(f"objectness similarity: {score:.4f}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/forge/stage4_review/per_feature.py b/forge/stage4_review/per_feature.py
new file mode 100644
index 0000000..857981e
--- /dev/null
+++ b/forge/stage4_review/per_feature.py
@@ -0,0 +1,210 @@
+"""Per-feature verification for the img2threejs review stage.
+
+A high *global* fidelity score can still hide a wrong or missing
+identity-defining feature (a blade tip, a logo, a recurved hook). This
+module verifies EACH declared feature independently against its own
+threshold and fails the pass when a *gating* feature is missing or below
+its threshold — even if the global score passed.
+
+Operationalizes SKILL.md's rule: "fail a pass if an identity-defining
+feature is wrong even when the global score looks fine."
+
+Pure-logic module: it consumes already-computed per-feature scores and
+decides pass/fail. It does NOT load or inspect images. Stdlib only.
+
+Data shapes
+-----------
+feature_targets : list[dict]
+ {"id": str, "tier": "critical"|"important"|"detail",
+ "minimumScore": float (optional), "mustPass": bool (optional)}
+feature_scores : dict[str, float | None]
+ id -> score in [0, 1], or None meaning the feature's region showed
+ no corresponding signal in the render (MISSING). A target id absent
+ from this dict is treated the same as None (missing).
+"""
+
+import argparse
+import json
+import sys
+
+TIER_DEFAULTS = {
+ "critical": 0.8,
+ "important": 0.65,
+ "detail": 0.5,
+}
+UNKNOWN_TIER_DEFAULT = 0.5
+
+
+def threshold_for(target):
+ """Return the minimum score a feature must reach.
+
+ Uses target["minimumScore"] when it is a number, otherwise the tier
+ default (critical 0.8, important 0.65, detail 0.5, unknown 0.5).
+ """
+ minimum = target.get("minimumScore")
+ if isinstance(minimum, bool):
+ # bool is a subclass of int/float; never treat it as a threshold.
+ minimum = None
+ if isinstance(minimum, (int, float)):
+ return float(minimum)
+ tier = target.get("tier")
+ return TIER_DEFAULTS.get(tier, UNKNOWN_TIER_DEFAULT)
+
+
+def is_gating(target):
+ """A feature gates the pass when it is critical OR flagged mustPass."""
+ return target.get("tier") == "critical" or target.get("mustPass") is True
+
+
+def evaluate_features(feature_targets, feature_scores):
+ """Evaluate every declared feature independently.
+
+ Returns a dict:
+ {"passed": bool, "action": str,
+ "features": [{"id","tier","score","threshold",
+ "status","gating"}, ...],
+ "defects": [str, ...]}
+
+ "passed" is True only if NO gating feature is missing or below its
+ threshold. Non-gating features below threshold are reported but do
+ not fail the pass.
+ """
+ feature_scores = feature_scores or {}
+
+ features = []
+ defects = []
+ any_gating_missing = False
+ any_gating_below = False
+
+ for target in feature_targets:
+ fid = target.get("id")
+ tier = target.get("tier")
+ gating = is_gating(target)
+ threshold = threshold_for(target)
+
+ # A target absent from the scores dict is treated as missing (None).
+ score = feature_scores.get(fid) if fid in feature_scores else None
+
+ if score is None:
+ status = "missing"
+ defects.append("missing-feature:%s" % fid)
+ if gating:
+ any_gating_missing = True
+ elif score < threshold:
+ status = "below"
+ defects.append(
+ "below-threshold:%s(%s<%s)" % (fid, _fmt(score), _fmt(threshold))
+ )
+ if gating:
+ any_gating_below = True
+ else:
+ status = "ok"
+
+ features.append(
+ {
+ "id": fid,
+ "tier": tier,
+ "score": score,
+ "threshold": threshold,
+ "status": status,
+ "gating": gating,
+ }
+ )
+
+ passed = not (any_gating_missing or any_gating_below)
+
+ if passed:
+ action = "continue"
+ elif any_gating_missing:
+ # A gating feature was never built — a spec problem.
+ action = "refine-spec"
+ else:
+ # Built but below threshold — a manifestation problem.
+ action = "refine-code"
+
+ return {
+ "passed": passed,
+ "action": action,
+ "features": features,
+ "defects": defects,
+ }
+
+
+def _fmt(value):
+ """Compact numeric formatting for defect strings (0.61, 0.75, ...)."""
+ text = ("%.4f" % float(value)).rstrip("0").rstrip(".")
+ return text if text else "0"
+
+
+def _load_targets(path):
+ with open(path, "r", encoding="utf-8") as handle:
+ data = json.load(handle)
+ if isinstance(data, dict):
+ return data.get("featureReviewTargets", [])
+ return data
+
+
+def _load_scores(path):
+ with open(path, "r", encoding="utf-8") as handle:
+ data = json.load(handle)
+ if not isinstance(data, dict):
+ raise ValueError("scores file must be a JSON object {id: score-or-null}")
+ return data
+
+
+def _format_text(result):
+ lines = []
+ lines.append("passed: %s" % result["passed"])
+ lines.append("action: %s" % result["action"])
+ lines.append("features:")
+ for feature in result["features"]:
+ score = feature["score"]
+ score_text = "missing" if score is None else _fmt(score)
+ gating = " [gating]" if feature["gating"] else ""
+ lines.append(
+ " - %s (%s): %s / %s -> %s%s"
+ % (
+ feature["id"],
+ feature["tier"],
+ score_text,
+ _fmt(feature["threshold"]),
+ feature["status"],
+ gating,
+ )
+ )
+ if result["defects"]:
+ lines.append("defects:")
+ for defect in result["defects"]:
+ lines.append(" - %s" % defect)
+ else:
+ lines.append("defects: none")
+ return "\n".join(lines)
+
+
+def main(argv):
+ parser = argparse.ArgumentParser(
+ description="Per-feature verification for img2threejs review."
+ )
+ parser.add_argument("--targets", required=True, help="JSON file of feature targets")
+ parser.add_argument("--scores", required=True, help="JSON file of feature scores")
+ parser.add_argument("--json", action="store_true", help="emit JSON result")
+ args = parser.parse_args(argv)
+
+ try:
+ targets = _load_targets(args.targets)
+ scores = _load_scores(args.scores)
+ result = evaluate_features(targets, scores)
+ except Exception as exc: # noqa: BLE001 - surface any failure cleanly
+ sys.stderr.write("error: %s\n" % exc)
+ return 2
+
+ if args.json:
+ print(json.dumps(result, indent=2))
+ else:
+ print(_format_text(result))
+
+ return 0 if result["passed"] else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/stage4_review/vlm_gate.py b/forge/stage4_review/vlm_gate.py
new file mode 100644
index 0000000..0244744
--- /dev/null
+++ b/forge/stage4_review/vlm_gate.py
@@ -0,0 +1,191 @@
+#!/usr/bin/env python3
+"""VLM gating layer (Plan 1.3 §3.4) — the model as gated, calibrated, cross-checked lubricant.
+
+The VLM is the ONLY place a model opinion enters the Divine Eye, and it is deliberately
+subordinate to the deterministic ensemble (divine_eye.py). This module encodes the RULES
+around the model so a wrong/overconfident model verdict cannot mislead the generator:
+
+ 1. The VLM NEVER runs on a render that failed a deterministic HARD gate. A geometrically
+ broken render is rejected by math; asking the model about it only invites a confident-
+ but-wrong "looks fine". (Reliability property, not a token optimization.)
+ 2. Multi-sample self-consistency voting: sample the VLM N times, aggregate (median), and
+ treat high spread across samples as an uncertainty signal → probe, never a coin-flip.
+ 3. Post-hoc score calibration: raw VLM scores are remapped through a monotonic calibration
+ fitted on the §5 corpus (true temperature scaling is impossible without logits). Default
+ is identity until calibration data exists.
+ 4. Evidence cross-check: the VLM's claimed object class is checked against the deterministic
+ geometric descriptor; a contradiction flags the verdict uncertain (the model's semantics
+ must not override measured geometry).
+ 5. Hard vs soft: the VLM can NEVER grant past a hard geometric failure (it doesn't even run
+ then), but it CAN rescue a SOFT near-threshold reject when its criteria + evidence agree.
+
+The actual VLM call is INJECTED as `vlm_sampler` (a callable), so this whole layer is
+deterministic + testable with a stub — no real model, no token, in tests. Pure stdlib.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+from typing import Any, Callable
+
+CRITERIA = ("objectness", "semantic", "structural", "specular")
+DEFAULT_CRITERIA_MIN = 0.80
+VARIANCE_SPREAD_MAX = 0.20 # spread across samples above this ⇒ uncertain → probe
+
+
+def _median(xs: list[float]) -> float:
+ if not xs:
+ return 0.0
+ s = sorted(xs)
+ m = len(s) // 2
+ return s[m] if len(s) % 2 else 0.5 * (s[m - 1] + s[m])
+
+
+def aggregate_samples(samples: list[dict]) -> dict[str, Any]:
+ """Median per criterion + the worst (max) per-criterion spread across samples."""
+ agg: dict[str, float] = {}
+ max_spread = 0.0
+ for crit in CRITERIA:
+ vals = [float(s.get(crit, 0.0)) for s in samples]
+ agg[crit] = _median(vals)
+ if vals:
+ max_spread = max(max_spread, max(vals) - min(vals))
+ # majority claimed class (ties → first seen)
+ classes = [s.get("claimedClass") for s in samples if s.get("claimedClass")]
+ claimed = None
+ if classes:
+ counts: dict[str, int] = {}
+ for c in classes:
+ counts[c] = counts.get(c, 0) + 1
+ claimed = max(counts, key=lambda k: counts[k])
+ return {"criteria": agg, "maxSpread": max_spread, "claimedClass": claimed}
+
+
+def calibrate(score: float, calibration: list[list[float]] | None = None) -> float:
+ """Monotonic piecewise-linear remap fitted on the §5 corpus. `calibration` is a sorted
+ list of [raw, calibrated] control points. Default (None) is identity."""
+ if not calibration:
+ return score
+ pts = sorted(calibration, key=lambda p: p[0])
+ if score <= pts[0][0]:
+ return pts[0][1]
+ if score >= pts[-1][0]:
+ return pts[-1][1]
+ for i in range(1, len(pts)):
+ x0, y0 = pts[i - 1]
+ x1, y1 = pts[i]
+ if x0 <= score <= x1:
+ t = 0.0 if x1 == x0 else (score - x0) / (x1 - x0)
+ return y0 + t * (y1 - y0)
+ return score
+
+
+def evidence_consistent(vlm_class: str | None, geometry_class: str | None) -> bool:
+ """True if the VLM's claimed class does not contradict the deterministic geometry
+ descriptor. Unknown geometry (None) cannot contradict → consistent."""
+ if not vlm_class or not geometry_class:
+ return True
+ return vlm_class.strip().lower() == geometry_class.strip().lower()
+
+
+def gate(
+ eye_result: dict[str, Any],
+ vlm_sampler: Callable[[int], dict] | None,
+ n_samples: int = 3,
+ criteria_min: float = DEFAULT_CRITERIA_MIN,
+ calibration: list[list[float]] | None = None,
+ geometry_class: str | None = None,
+) -> dict[str, Any]:
+ """Decide the final verdict given the deterministic Eye result + an (injected) VLM sampler."""
+ hard_failures = eye_result.get("hardGateFailures") or []
+ if hard_failures:
+ # RULE 1: never consult the VLM on a hard-gate failure.
+ return {
+ "verdict": "reject",
+ "action": "refine-code",
+ "ranVlm": False,
+ "reason": f"deterministic hard gate failed ({'; '.join(hard_failures)}); VLM not consulted",
+ }
+
+ if vlm_sampler is None:
+ # No VLM available: fall back to the deterministic verdict unchanged.
+ return {
+ "verdict": eye_result.get("verdict", "reject"),
+ "action": eye_result.get("action", "refine-code"),
+ "ranVlm": False,
+ "reason": "no VLM sampler provided; deterministic verdict stands",
+ }
+
+ samples = [vlm_sampler(i) for i in range(max(1, n_samples))]
+ agg = aggregate_samples(samples)
+ calibrated = {c: calibrate(agg["criteria"].get(c, 0.0), calibration) for c in CRITERIA}
+
+ # RULE 2: high spread across samples ⇒ uncertain → probe.
+ if agg["maxSpread"] > VARIANCE_SPREAD_MAX:
+ return {
+ "verdict": "uncertain", "action": "probe", "ranVlm": True,
+ "criteria": calibrated, "maxSpread": agg["maxSpread"],
+ "reason": f"VLM sample spread {agg['maxSpread']:.2f} > {VARIANCE_SPREAD_MAX} (unstable opinion)",
+ }
+ # RULE 4: evidence cross-check against geometry.
+ if not evidence_consistent(agg.get("claimedClass"), geometry_class):
+ return {
+ "verdict": "uncertain", "action": "probe", "ranVlm": True,
+ "criteria": calibrated, "claimedClass": agg.get("claimedClass"),
+ "reason": f"VLM claimed {agg.get('claimedClass')!r} contradicts geometry {geometry_class!r}",
+ }
+
+ below = {c: v for c, v in calibrated.items() if v < criteria_min}
+ if not below:
+ # All criteria satisfied. Confirm a pass, or RESCUE a soft near-threshold reject.
+ eye_verdict = eye_result.get("verdict")
+ rescued = eye_verdict in ("low-confidence", "reject") # soft (no hard failure — checked above)
+ return {
+ "verdict": "pass", "action": "continue", "ranVlm": True,
+ "criteria": calibrated,
+ "reason": ("VLM criteria all ≥ min; soft-reject rescued (deterministic hard gates already passed)"
+ if rescued else "VLM criteria all ≥ min; pass confirmed"),
+ }
+
+ # RULE 5: a criterion is below min → withhold. Route by which criterion.
+ conceptual = any(c in below for c in ("objectness", "semantic"))
+ return {
+ "verdict": "withhold",
+ "action": "refine-spec" if conceptual else "refine-code",
+ "ranVlm": True,
+ "criteria": calibrated,
+ "below": below,
+ "reason": ("VLM objectness/semantic below min (conceptual — spec wrong)"
+ if conceptual else "VLM structural/specular below min (execution — code wrong)"),
+ }
+
+
+def main(argv: list[str]) -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--eye", required=True, type=Path, help="divine_eye result JSON")
+ parser.add_argument("--samples", type=Path, help="JSON list of VLM sample dicts (offline/testing)")
+ parser.add_argument("--geometry-class", default=None)
+ parser.add_argument("--criteria-min", type=float, default=DEFAULT_CRITERIA_MIN)
+ parser.add_argument("--json", action="store_true")
+ args = parser.parse_args(argv)
+ try:
+ eye = json.loads(args.eye.read_text(encoding="utf-8"))
+ sampler = None
+ if args.samples:
+ preloaded = json.loads(args.samples.read_text(encoding="utf-8"))
+ sampler = lambda i: preloaded[i % len(preloaded)] # noqa: E731
+ result = gate(eye, sampler, n_samples=len(json.loads(args.samples.read_text())) if args.samples else 3,
+ criteria_min=args.criteria_min, geometry_class=args.geometry_class)
+ except Exception as exc: # noqa: BLE001
+ print(f"error: {exc}", file=sys.stderr)
+ return 2
+ print(json.dumps(result, indent=2, ensure_ascii=False) if args.json
+ else f"{result['verdict'].upper()} → {result['action']} (ranVlm={result['ranVlm']})")
+ return 0 if result["verdict"] == "pass" else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main(sys.argv[1:]))
diff --git a/forge/tests/test_analyze_texture.py b/forge/tests/test_analyze_texture.py
new file mode 100644
index 0000000..ea6c17f
--- /dev/null
+++ b/forge/tests/test_analyze_texture.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+"""Tests for analyze_texture.py — finish classification + recipe. Pure stdlib, zero token.
+Run: python3 forge/tests/test_analyze_texture.py
+"""
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage1_intake"))
+from analyze_texture import RECIPES, analyze # noqa: E402
+
+PNG_SIG = b"\x89PNG\r\n\x1a\n"
+
+
+def write_png(path, w, h, fn):
+ def chunk(t, d):
+ return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(fn(x, y))
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
+ path.write_bytes(PNG_SIG + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
+
+
+def cl(v):
+ return max(0, min(255, int(v)))
+
+
+class AnalyzeTextureTest(unittest.TestCase):
+ def setUp(self):
+ self.d = Path(tempfile.mkdtemp())
+ self.S = 160
+
+ def _mk(self, name, fn):
+ p = self.d / name
+ write_png(p, self.S, self.S, fn)
+ return p
+
+ def test_pigment_dominant_doppler_is_candy_coat(self):
+ # doppler-like blue->purple gradient + smoky mottle, NO chrome specular (colour survives
+ # into mid-tones) -> candy-coat (dielectric). This is the M9-Doppler case that previously
+ # mis-classed as high-metalness gem-metal and rendered blue (env stole the hue).
+ def fn(x, y):
+ noise = ((x * 5 + y * 9) % 23) - 11 # smoke variance
+ return (cl(20 + x * 1.2 + noise), cl(25 + noise), cl(130 + noise))
+ r = analyze(self._mk("candy.png", fn))
+ self.assertEqual(r["finishClass"], "candy-coat")
+ self.assertEqual(r["recipe"]["procedural"], "gradient-smoke")
+ self.assertLessEqual(r["recipe"]["metalness"], 0.4) # dielectric-led → hue survives
+ self.assertLessEqual(r["recipe"]["envMapIntensity"], 0.9)
+ self.assertEqual(len(r["palette"]), 5)
+ # blue-leaning stops (B > R) flagged for hue-survival with a magenta-lean suggestion
+ self.assertTrue(r["paletteHueRisk"], "expected blue-collapse flag on blue-leaning stops")
+ self.assertEqual(r["paletteHueRisk"][0]["hueRisk"], "blue-collapse")
+
+ def test_chrome_specular_doppler_is_gem_metal(self):
+ # same chromatic gradient but WITH bright chrome specular hotspots -> genuinely metallic
+ # doppler (gem-metal, high metalness). Bright hotspots on ~6% of pixels (lum > 235).
+ def fn(x, y):
+ noise = ((x * 5 + y * 9) % 23) - 11
+ if (x + y) % 17 == 0:
+ return (250, 250, 255) # chrome specular hotspot
+ return (cl(20 + x * 1.2 + noise), cl(25 + noise), cl(130 + noise))
+ r = analyze(self._mk("gem.png", fn))
+ self.assertEqual(r["finishClass"], "gem-metal")
+ self.assertGreaterEqual(r["recipe"]["metalness"], 0.6)
+
+ def test_flat_saturated_is_painted_metal(self):
+ img = self._mk("paint.png", lambda x, y: (230, 150, 50))
+ r = analyze(img)
+ self.assertEqual(r["finishClass"], "painted-metal")
+ self.assertAlmostEqual(r["recipe"]["clearcoat"], 1.0)
+
+ def test_mottled_grey_is_worn_composite(self):
+ # dark neutral grey with isotropic mottle -> worn composite
+ def fn(x, y):
+ v = 55 + ((x * 7 + y * 13) % 37) - 18
+ return (cl(v), cl(v), cl(v + 2))
+ r = analyze(self._mk("worn.png", fn))
+ self.assertEqual(r["finishClass"], "worn-composite")
+ self.assertAlmostEqual(r["recipe"]["roughness"], 0.9)
+
+ def test_directional_streaks_is_brushed_steel(self):
+ # coarse bright horizontal grain (bands vary in Y, survive downsample), neutral -> brushed
+ def fn(x, y):
+ v = 150 + (38 if (y // 8) % 2 == 0 else -38)
+ return (cl(v), cl(v), cl(v))
+ r = analyze(self._mk("brushed.png", fn))
+ self.assertEqual(r["finishClass"], "brushed-steel")
+ self.assertAlmostEqual(r["recipe"]["metalness"], 1.0)
+ self.assertAlmostEqual(r["recipe"]["anisotropy"], 1.0)
+
+ def test_apply_to_material_writes_recipe(self):
+ from analyze_texture import apply_to_material
+ img = self._mk("paint2.png", lambda x, y: (230, 150, 50))
+ result = analyze(img)
+ mat = {"id": "frame", "roughness": {"base": 0.3, "variation": 0.1}}
+ apply_to_material(mat, result)
+ self.assertEqual(mat["finishClass"], "painted-metal")
+ self.assertEqual(mat["roughness"]["base"], result["recipe"]["roughness"]) # layer shape kept
+ self.assertEqual(mat["roughness"]["variation"], 0.1)
+ self.assertIn("texturePalette", mat)
+ self.assertEqual(mat["clearcoat"]["base"], result["recipe"]["clearcoat"])
+
+ def test_all_recipes_have_required_scalars(self):
+ keys = {"metalness", "roughness", "clearcoat", "clearcoatRoughness", "transmission",
+ "ior", "envMapIntensity", "anisotropy", "procedural"}
+ for name, rec in RECIPES.items():
+ self.assertTrue(keys <= set(rec), f"{name} missing keys")
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_calibrate_eye.py b/forge/tests/test_calibrate_eye.py
new file mode 100644
index 0000000..db23aea
--- /dev/null
+++ b/forge/tests/test_calibrate_eye.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python3
+"""Tests for the Divine Eye calibration harness (Plan 1.3 §5). Synthetic pairs, zero token."""
+
+from __future__ import annotations
+
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage4_review"))
+
+from calibrate_eye import calibrate, run_corpus, separation # noqa: E402
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def write_rgb_png(path, w, h, pixel_fn):
+ def chunk(tag, data):
+ c = struct.pack(">I", len(data)) + tag + data
+ return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(pixel_fn(x, y, w, h))
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
+ path.write_bytes(PNG_SIGNATURE + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
+
+
+def block(x0, y0, x1, y1):
+ return lambda x, y, w, h: (40, 40, 40) if (x0 <= x < x1 and y0 <= y < y1) else (255, 255, 255)
+
+
+class CalibrateEyeTest(unittest.TestCase):
+ def setUp(self):
+ self.dir = Path(tempfile.mkdtemp())
+ self.ref = self.dir / "ref.png"
+ write_rgb_png(self.ref, 200, 200, block(50, 50, 150, 150))
+ # good render == reference (fidelity 1.0, pass)
+ self.good = self.dir / "good.png"
+ write_rgb_png(self.good, 200, 200, block(50, 50, 150, 150))
+ # bad render: subject collapsed to a small block (hard-gate reject)
+ self.bad = self.dir / "bad.png"
+ write_rgb_png(self.bad, 200, 200, block(92, 92, 108, 108))
+
+ def _corpus(self):
+ return [
+ {"reference": str(self.ref), "render": str(self.good), "label": "good"},
+ {"reference": str(self.ref), "render": str(self.bad), "label": "bad"},
+ ]
+
+ def test_run_corpus_collects_per_label(self):
+ c = run_corpus(self._corpus())
+ self.assertEqual(c["signalStats"]["good"]["count"], 1)
+ self.assertEqual(c["signalStats"]["bad"]["count"], 1)
+ self.assertGreater(c["signalStats"]["good"]["fidelityMean"],
+ c["signalStats"]["bad"]["fidelityMean"])
+
+ def test_clean_separation_and_acceptable(self):
+ result = calibrate(self._corpus())
+ sep = result["separation"]
+ self.assertTrue(sep["cleanSeparation"])
+ self.assertTrue(sep["allGoodPass"])
+ self.assertTrue(sep["allBadRejected"])
+ self.assertTrue(sep["corpusAcceptable"])
+ self.assertIsNotNone(sep["suggestedThreshold"])
+
+ def test_corpus_needs_both_classes(self):
+ good_only = [{"reference": str(self.ref), "render": str(self.good), "label": "good"}]
+ sep = separation(run_corpus(good_only)["rows"])
+ self.assertFalse(sep["corpusAcceptable"])
+ self.assertIn("warning", sep)
+
+ def test_report_only_flag_set(self):
+ result = calibrate(self._corpus())
+ self.assertTrue(result["reportOnly"])
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_color_metrics.py b/forge/tests/test_color_metrics.py
new file mode 100644
index 0000000..46d8fbf
--- /dev/null
+++ b/forge/tests/test_color_metrics.py
@@ -0,0 +1,53 @@
+#!/usr/bin/env python3
+"""Verify CIEDE2000 against Sharma et al.'s canonical published test pairs (tolerance 1e-3).
+Pure stdlib, zero token.
+"""
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "_shared"))
+from color_metrics import ciede2000, delta_e_rgb # noqa: E402
+
+# (lab1, lab2, expected ΔE00) — Sharma/Wu/Dalal CIEDE2000 verification data.
+SHARMA = [
+ ((50.0000, 2.6772, -79.7751), (50.0000, 0.0000, -82.7485), 2.0425),
+ ((50.0000, 3.1571, -77.2803), (50.0000, 0.0000, -82.7485), 2.8615),
+ ((50.0000, 2.8361, -74.0200), (50.0000, 0.0000, -82.7485), 3.4412),
+ ((50.0000, -1.3802, -84.2814), (50.0000, 0.0000, -82.7485), 1.0000),
+ ((50.0000, -1.1848, -84.8006), (50.0000, 0.0000, -82.7485), 1.0000),
+ ((60.2574, -34.0099, 36.2677), (60.4626, -34.1751, 39.4387), 1.2644),
+ ((63.0109, -31.0961, -5.8663), (62.8187, -29.7946, -4.0864), 1.2630),
+ ((35.0831, -44.1164, 3.7933), (35.0232, -40.0716, 1.5901), 1.8645),
+ ((22.7233, 20.0904, -46.6940), (23.0331, 14.9730, -42.5619), 2.0373),
+]
+
+
+class ColorMetricsTest(unittest.TestCase):
+ def test_ciede2000_matches_sharma_reference(self):
+ for lab1, lab2, expected in SHARMA:
+ got = ciede2000(lab1, lab2)
+ self.assertAlmostEqual(got, expected, places=3,
+ msg=f"ΔE00{lab1}->{lab2}: got {got:.4f}, expected {expected}")
+
+ def test_symmetry_and_identity(self):
+ a = (50.0, 2.6772, -79.7751)
+ b = (50.0, 0.0, -82.7485)
+ self.assertAlmostEqual(ciede2000(a, a), 0.0, places=6)
+ self.assertAlmostEqual(ciede2000(a, b), ciede2000(b, a), places=6)
+
+ def test_delta_e_rgb_same_colour_zero(self):
+ self.assertAlmostEqual(delta_e_rgb((120, 40, 200), (120, 40, 200)), 0.0, places=6)
+
+ def test_same_hue_zone_threshold(self):
+ # two close blues within the ~2.3 "same hue zone"; a blue vs orange far outside it
+ near = delta_e_rgb((46, 108, 236), (50, 112, 232))
+ far = delta_e_rgb((46, 108, 236), (236, 140, 40))
+ self.assertLess(near, 3.0)
+ self.assertGreater(far, 20.0)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_color_recipe.py b/forge/tests/test_color_recipe.py
new file mode 100644
index 0000000..3d34ddd
--- /dev/null
+++ b/forge/tests/test_color_recipe.py
@@ -0,0 +1,148 @@
+#!/usr/bin/env python3
+"""Unit tests for the Plan 1.3 Workstream C color/material math: srgb_to_lab,
+lab_to_rgba round-trip, lab_kmeans_palette, estimate_roughness_from_hotspot,
+and detect_color_gradient (including the monotonicity gate). Independent of
+forge/tests/test_pipeline.py per the plan's acceptance criteria — these test
+pure functions directly, not the CLI subprocess surface.
+
+Run: python3 forge/tests/test_color_recipe.py
+ or: python3 -m unittest discover -s forge/tests
+"""
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+SKILL = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(SKILL / "forge" / "stage1_intake"))
+
+from extract_part_color_recipe import ( # noqa: E402
+ build_recipe,
+ detect_color_gradient,
+ lab_distance,
+ lab_kmeans_palette,
+ lab_to_rgba,
+ srgb_to_lab,
+ estimate_roughness_from_hotspot,
+)
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def write_rgb_png(path: Path, w: int, h: int, pixel_fn) -> None:
+ def chunk(tag: bytes, data: bytes) -> bytes:
+ c = struct.pack(">I", len(data)) + tag + data
+ return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(pixel_fn(x, y, w, h))
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
+ png = (
+ PNG_SIGNATURE
+ + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
+ + chunk(b"IEND", b"")
+ )
+ path.write_bytes(png)
+
+
+class SrgbToLabTest(unittest.TestCase):
+ def test_white_is_l100_a0_b0(self):
+ l_star, a_star, b_star = srgb_to_lab((255, 255, 255))
+ self.assertAlmostEqual(l_star, 100.0, delta=0.5)
+ self.assertAlmostEqual(a_star, 0.0, delta=0.5)
+ self.assertAlmostEqual(b_star, 0.0, delta=0.5)
+
+ def test_pure_red_matches_reference_values(self):
+ l_star, a_star, b_star = srgb_to_lab((255, 0, 0))
+ self.assertAlmostEqual(l_star, 53.24, delta=0.5)
+ self.assertAlmostEqual(a_star, 80.09, delta=0.5)
+ self.assertAlmostEqual(b_star, 67.20, delta=0.5)
+
+
+class LabToRgbaRoundTripTest(unittest.TestCase):
+ def test_round_trip_within_one_unit(self):
+ for rgb in [(138, 109, 75), (12, 200, 44), (0, 0, 0), (255, 255, 255)]:
+ with self.subTest(rgb=rgb):
+ lab = srgb_to_lab(rgb)
+ rgba = lab_to_rgba(lab, alpha=0.5)
+ self.assertTrue(rgba.startswith("rgba("))
+ r, g, b, a = rgba[5:-1].split(",")
+ self.assertAlmostEqual(int(r), rgb[0], delta=1)
+ self.assertAlmostEqual(int(g), rgb[1], delta=1)
+ self.assertAlmostEqual(int(b), rgb[2], delta=1)
+ self.assertEqual(float(a), 0.5)
+
+
+class LabKmeansPaletteTest(unittest.TestCase):
+ def test_two_known_colors_in_known_split(self):
+ color_a = srgb_to_lab((200, 60, 40))
+ color_b = srgb_to_lab((40, 60, 200))
+ samples = [color_a] * 70 + [color_b] * 30
+ clusters = lab_kmeans_palette(samples, k=2)
+ self.assertEqual(len(clusters), 2)
+ shares = sorted((c["share_pct"] for c in clusters), reverse=True)
+ self.assertAlmostEqual(shares[0], 0.7, delta=0.02)
+ self.assertAlmostEqual(shares[1], 0.3, delta=0.02)
+
+
+class RoughnessFromHotspotTest(unittest.TestCase):
+ def test_tight_hotspot_is_lower_roughness_than_broad_hotspot(self):
+ # Tight: only 2% of foreground pixels are near-max brightness.
+ tight_lumas = [0.95] * 2 + [0.2] * 98
+ tight_mask = [True] * 100
+ tight_roughness, _ = estimate_roughness_from_hotspot(tight_lumas, tight_mask)
+
+ # Broad: half the foreground is near-max brightness (gradual falloff).
+ broad_lumas = [0.95] * 50 + [0.3] * 50
+ broad_mask = [True] * 100
+ broad_roughness, _ = estimate_roughness_from_hotspot(broad_lumas, broad_mask)
+
+ self.assertLess(tight_roughness, broad_roughness)
+
+
+class ColorGradientDetectionTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp())
+
+ def test_flat_color_yields_no_gradient(self):
+ write_rgb_png(self.tmp / "flat.png", 64, 64, lambda x, y, w, h: (120, 90, 60))
+ recipe = build_recipe("flat-part", self.tmp / "flat.png")
+ self.assertNotIn("colorGradient", recipe)
+
+ def test_linear_gradient_is_detected_with_correct_axis(self):
+ def grad_pixel(x, y, w, h):
+ t = x / (w - 1)
+ return (round(60 + t * 140), round(45 + t * 110), round(30 + t * 90))
+
+ write_rgb_png(self.tmp / "gradient.png", 64, 64, grad_pixel)
+ recipe = build_recipe("gradient-part", self.tmp / "gradient.png")
+ self.assertIn("colorGradient", recipe)
+ gradient = recipe["colorGradient"]
+ self.assertEqual(gradient["type"], "linear")
+ # horizontal gradient -> axis should point predominantly along x
+ self.assertGreater(abs(gradient["axis"][0]), abs(gradient["axis"][1]))
+ self.assertEqual(len(gradient["stops"]), 3)
+ offsets = [stop["offset"] for stop in gradient["stops"]]
+ self.assertEqual(offsets, sorted(offsets))
+
+ def test_checkerboard_pattern_yields_no_gradient(self):
+ # Real color variance (two colors), but zero monotonic directional trend —
+ # proves the monotonicity gate rejects textured/patterned regions, not just
+ # the magnitude gate.
+ def checker_pixel(x, y, w, h):
+ on = ((x // 8) + (y // 8)) % 2 == 0
+ return (60, 45, 30) if on else (200, 155, 100)
+
+ write_rgb_png(self.tmp / "checker.png", 64, 64, checker_pixel)
+ recipe = build_recipe("checker-part", self.tmp / "checker.png")
+ self.assertNotIn("colorGradient", recipe)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_correction_loop.py b/forge/tests/test_correction_loop.py
new file mode 100644
index 0000000..d1be4ab
--- /dev/null
+++ b/forge/tests/test_correction_loop.py
@@ -0,0 +1,113 @@
+#!/usr/bin/env python3
+"""Tests for the bounded correction-loop stop policy (§3.6).
+
+Pure stdlib unittest. The termination guarantee (test_hard_ceiling_always_terminates
+and test_loop_cannot_exceed_max_iter) is the load-bearing property of this suite.
+"""
+
+import os
+import sys
+import unittest
+
+sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "stage4_review"))
+
+from correction_loop import budget_exceeded, decide # noqa: E402
+
+
+def _it(fidelity, defect_tags=None, reverted=False):
+ """Build one iteration record."""
+ return {
+ "fidelity": fidelity,
+ "defectTags": list(defect_tags or []),
+ "reverted": reverted,
+ }
+
+
+class CorrectionLoopTest(unittest.TestCase):
+ def test_empty_history_continues(self):
+ d = decide([])
+ self.assertFalse(d["stop"])
+ self.assertEqual(d["action"], "continue-iterating")
+ self.assertEqual(d["reason"], "no iterations yet")
+
+ def test_success_when_target_met_and_no_defects(self):
+ d = decide([_it(0.90, [])])
+ self.assertTrue(d["stop"])
+ self.assertEqual(d["action"], "continue")
+
+ def test_success_requires_no_defects(self):
+ # Fidelity above target BUT open defects remain -> NOT success.
+ d = decide([_it(0.95, ["visible-seam"])])
+ self.assertNotEqual(d["action"], "continue")
+
+ def test_repeated_defect_stops_refine_spec(self):
+ history = [
+ _it(0.60, ["seam"]),
+ _it(0.72, ["seam", "gap"]),
+ ]
+ d = decide(history)
+ self.assertTrue(d["stop"])
+ self.assertEqual(d["action"], "refine-spec")
+ self.assertIn("seam", d["reason"])
+
+ def test_plateau_stops_request_input(self):
+ # Second iteration improves by < min_delta and stays below target.
+ history = [
+ _it(0.60, []),
+ _it(0.61, []),
+ ]
+ d = decide(history)
+ self.assertTrue(d["stop"])
+ self.assertEqual(d["action"], "request-input")
+
+ def test_hard_ceiling_always_terminates(self):
+ # Steadily improving (delta 0.05 > min_delta so PLATEAU cannot fire),
+ # never reaching target 0.85, no shared defect tags, no reverts.
+ history = [
+ _it(0.50, []),
+ _it(0.55, []),
+ _it(0.60, []),
+ _it(0.65, []),
+ _it(0.70, []),
+ _it(0.75, []),
+ ]
+ self.assertEqual(len(history), 6) # == default max_iter
+ d = decide(history)
+ self.assertTrue(d["stop"])
+ self.assertIn("ceiling", d["reason"].lower())
+
+ def test_oscillation_two_reverts_stops(self):
+ history = [
+ _it(0.50, [], reverted=True),
+ _it(0.50, [], reverted=False),
+ _it(0.50, [], reverted=True),
+ ]
+ d = decide(history)
+ self.assertTrue(d["stop"])
+ self.assertEqual(d["action"], "refine-spec")
+ self.assertEqual(d["reason"], "oscillating/thrashing")
+
+ def test_loop_cannot_exceed_max_iter(self):
+ # Simulate a real caller loop. Even with monotonic tiny improvements,
+ # the body MUST execute at most max_iter times. A hard safety counter
+ # fails the test if the loop somehow refuses to terminate.
+ max_iter = 6
+ history = []
+ iterations = 0
+ safety = 0
+ while not decide(history, max_iter=max_iter)["stop"]:
+ safety += 1
+ if safety > 100:
+ self.fail("did not terminate")
+ history.append(_it(0.001 * (len(history) + 1), []))
+ iterations += 1
+ self.assertLessEqual(iterations, max_iter)
+
+ def test_budget_exceeded_helper(self):
+ self.assertTrue(budget_exceeded(100, 100))
+ self.assertTrue(budget_exceeded(101, 100))
+ self.assertFalse(budget_exceeded(99, 100))
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_divine_eye.py b/forge/tests/test_divine_eye.py
new file mode 100644
index 0000000..ffb1e5f
--- /dev/null
+++ b/forge/tests/test_divine_eye.py
@@ -0,0 +1,141 @@
+#!/usr/bin/env python3
+"""Tests for the Divine Eye deterministic ensemble (Plan 1.3 Phase 3 §3.1/§3.3)."""
+
+from __future__ import annotations
+
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage4_review"))
+
+from divine_eye import ( # noqa: E402
+ blowout_parity,
+ edge_overlap,
+ evaluate,
+ flat_fraction,
+ global_ssim,
+ tonal_parity,
+)
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def write_rgb_png(path: Path, w: int, h: int, pixel_fn) -> None:
+ def chunk(tag: bytes, data: bytes) -> bytes:
+ c = struct.pack(">I", len(data)) + tag + data
+ return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(pixel_fn(x, y, w, h))
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
+ path.write_bytes(PNG_SIGNATURE + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
+
+
+def block(x0, y0, x1, y1, fg=(200, 40, 40), bg=(255, 255, 255)):
+ return lambda x, y, w, h: fg if (x0 <= x < x1 and y0 <= y < y1) else bg
+
+
+class SignalUnitTest(unittest.TestCase):
+ def test_ssim_identical_is_one(self):
+ a = [0.2, 0.8, 0.5, 0.1] * 16
+ self.assertAlmostEqual(global_ssim(a, a), 1.0, places=5)
+
+ def test_ssim_different_is_low(self):
+ a = [0.0] * 64
+ b = [1.0 if i % 2 else 0.0 for i in range(64)]
+ self.assertLess(global_ssim(a, b), 0.5)
+
+ def test_tonal_parity_identical_is_one(self):
+ a = [i / 64 for i in range(64)]
+ self.assertAlmostEqual(tonal_parity(a, a), 1.0, places=5)
+
+ def test_tonal_parity_disjoint_is_low(self):
+ dark = [0.02] * 64
+ bright = [0.98] * 64
+ self.assertLess(tonal_parity(dark, bright), 0.1)
+
+ def test_blowout_parity_penalizes_extra_blown(self):
+ ref = [0.5] * 64
+ blown = [0.99] * 64
+ self.assertLess(blowout_parity(ref, blown), 0.1)
+ self.assertAlmostEqual(blowout_parity(ref, ref), 1.0, places=5)
+
+ def test_flat_fraction_high_for_uniform(self):
+ uniform = [0.5] * (16 * 16)
+ self.assertGreater(flat_fraction(uniform, 16), 0.9)
+
+ def test_edge_overlap_identical_is_one(self):
+ # a vertical edge in the middle
+ size = 32
+ img = [0.0 if (i % size) < size // 2 else 1.0 for i in range(size * size)]
+ self.assertAlmostEqual(edge_overlap(img, img, size), 1.0, places=5)
+
+
+class DivineEyeIntegrationTest(unittest.TestCase):
+ def setUp(self):
+ self.dir = Path(tempfile.mkdtemp())
+ self.ref = self.dir / "ref.png"
+ write_rgb_png(self.ref, 200, 200, block(50, 50, 150, 150))
+
+ def test_identical_passes_with_full_fidelity(self):
+ r = evaluate(self.ref, self.ref)
+ self.assertEqual(r["verdict"], "pass")
+ self.assertEqual(r["action"], "continue")
+ self.assertEqual(r["fidelity"], 1.0)
+ self.assertEqual(r["hardGateFailures"], [])
+
+ def test_wrong_scale_trips_hard_gate(self):
+ # a much smaller subject → scale/IoU hard gate → reject + refine-code
+ ren = self.dir / "small.png"
+ write_rgb_png(ren, 200, 200, block(90, 90, 110, 110))
+ r = evaluate(self.ref, ren)
+ self.assertEqual(r["verdict"], "reject")
+ self.assertEqual(r["action"], "refine-code")
+ self.assertTrue(r["hardGateFailures"])
+
+ def test_shifted_same_shape_is_rescued_by_objectness(self):
+ # subject moved to a corner → low IoU hard gate, BUT it is the same (square)
+ # shape → objectness (bg/pose/scale-invariant) recognises it → reconstruction-mode
+ # rescue downgrades the confident reject to a probe (still not a pass).
+ ren = self.dir / "shifted.png"
+ write_rgb_png(ren, 200, 200, block(0, 0, 60, 60))
+ r = evaluate(self.ref, ren)
+ self.assertTrue(r["hardGateFailures"]) # IoU still trips
+ self.assertTrue(r["reconstructionModeSuspected"])
+ self.assertEqual(r["action"], "probe") # rescued, NOT refine-code
+ self.assertNotEqual(r["verdict"], "pass") # never auto-passes
+
+ def test_different_shape_iou_fail_is_not_rescued(self):
+ # a genuinely different shape (thin bar vs square) → low objectness → NO rescue,
+ # stays a hard reject. Guards the rescue from masking real geometric failures.
+ ren = self.dir / "wrongshape.png"
+ write_rgb_png(ren, 200, 200, block(10, 92, 190, 108)) # thin horizontal bar
+ r = evaluate(self.ref, ren)
+ self.assertTrue(r["hardGateFailures"])
+ self.assertFalse(r["reconstructionModeSuspected"])
+ self.assertEqual(r["action"], "refine-code")
+
+ def test_asymmetric_subject_not_penalized_when_matched(self):
+ # an asymmetric L-shape compared to itself must still score fidelity 1.0
+ # (symmetry is a parity signal, not an absolute one).
+ def lshape(x, y, w, h):
+ if (20 <= x < 60 and 20 <= y < 160) or (20 <= x < 140 and 120 <= y < 160):
+ return (30, 120, 90)
+ return (255, 255, 255)
+ aref = self.dir / "l.png"
+ write_rgb_png(aref, 180, 180, lshape)
+ r = evaluate(aref, aref)
+ self.assertEqual(r["fidelity"], 1.0)
+ self.assertEqual(r["verdict"], "pass")
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_geometry_derivation.py b/forge/tests/test_geometry_derivation.py
new file mode 100644
index 0000000..2e17ffb
--- /dev/null
+++ b/forge/tests/test_geometry_derivation.py
@@ -0,0 +1,86 @@
+#!/usr/bin/env python3
+"""Tests for Plan 1.3 §4 Blum-medial-axis lathe-profile derivation (Phase 2)."""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage2_spec"))
+
+from derive_geometry import derive_lathe_profile # noqa: E402
+
+
+def circle_mask(size: int, r: float):
+ c = (size - 1) / 2.0
+ return [((x - c) ** 2 + (y - c) ** 2) <= r * r for y in range(size) for x in range(size)]
+
+
+def rect_mask(w: int, h: int, mx: int):
+ # a vertical bar of constant half-width mx, centered
+ cx = w // 2
+ return [abs(x - cx) <= mx for y in range(h) for x in range(w)]
+
+
+def triangle_mask(w: int, h: int):
+ # point at top (y=0), widening to full at bottom (y=h-1)
+ cx = w // 2
+ mask = []
+ for y in range(h):
+ half = int((y / (h - 1)) * (cx - 1))
+ for x in range(w):
+ mask.append(abs(x - cx) <= half)
+ return mask
+
+
+class LatheProfileTest(unittest.TestCase):
+ def test_circle_radius_peaks_in_middle(self):
+ size = 64
+ mask = circle_mask(size, 28)
+ prof = derive_lathe_profile(mask, size, size, samples=15)
+ radii = [p[0] for p in prof["points"]]
+ mid = radii[len(radii) // 2]
+ self.assertGreater(mid, radii[0])
+ self.assertGreater(mid, radii[-1])
+ self.assertLess(radii[0], 0.15) # near the poles the radius is ~0
+ self.assertLess(radii[-1], 0.15)
+
+ def test_rectangle_radius_roughly_constant(self):
+ w, h = 40, 80
+ mask = rect_mask(w, h, 8)
+ prof = derive_lathe_profile(mask, w, h, samples=15)
+ # drop first/last (endpoints can clip) and check the middle band is stable
+ mids = [p[0] for p in prof["points"][3:-3]]
+ self.assertTrue(mids)
+ self.assertLess(max(mids) - min(mids), 0.03, mids)
+
+ def test_triangle_radius_increases_top_to_bottom(self):
+ w, h = 60, 80
+ mask = triangle_mask(w, h)
+ prof = derive_lathe_profile(mask, w, h, samples=15)
+ radii = [p[0] for p in prof["points"]]
+ # top (axisPos -0.5) narrow → bottom (+0.5) wide
+ self.assertLess(radii[0], radii[-1])
+ self.assertEqual(prof["axis"], "vertical")
+
+ def test_axis_picks_longer_dimension(self):
+ # a subject whose bbox is WIDER than tall → horizontal revolve axis.
+ w, h = 80, 40
+ cy = h // 2
+ mask = [abs(y - cy) <= 6 for y in range(h) for x in range(w)] # wide horizontal bar
+ prof = derive_lathe_profile(mask, w, h, samples=10)
+ self.assertEqual(prof["axis"], "horizontal")
+
+ def test_axis_positions_span_normalized_range(self):
+ size = 40
+ mask = circle_mask(size, 16)
+ prof = derive_lathe_profile(mask, size, size, samples=9)
+ positions = [p[1] for p in prof["points"]]
+ self.assertAlmostEqual(positions[0], -0.5, delta=0.05)
+ self.assertAlmostEqual(positions[-1], 0.5, delta=0.05)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_gradient_stops.py b/forge/tests/test_gradient_stops.py
new file mode 100644
index 0000000..4058caf
--- /dev/null
+++ b/forge/tests/test_gradient_stops.py
@@ -0,0 +1,91 @@
+#!/usr/bin/env python3
+"""Reference-grounded gradient-stop extractor.
+
+Synthetic 3-zone gradient PNG (violet → blue → navy on white bg) → assert the extractor
+recovers the correct hue zones, names them, and flags the blue-leaning violet (B > R) as
+blue-collapse. Deterministic across runs. Pure stdlib.
+"""
+from __future__ import annotations
+
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+INTAKE = Path(__file__).resolve().parent.parent / "stage1_intake"
+sys.path.insert(0, str(INTAKE))
+from extract_gradient_stops import extract_gradient_stops, hue_name # noqa: E402
+
+
+def write_rgb_png(path: Path, width: int, height: int, fn) -> None:
+ raw = bytearray()
+ for y in range(height):
+ raw.append(0)
+ for x in range(width):
+ raw += bytes(fn(x, y))
+
+ def chunk(tag: bytes, data: bytes) -> bytes:
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ png = (
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
+ + chunk(b"IEND", b"")
+ )
+ path.write_bytes(png)
+
+
+class GradientStopsTest(unittest.TestCase):
+ def setUp(self) -> None:
+ self.dir = Path(tempfile.mkdtemp())
+ self.img = self.dir / "grad.png"
+ W, H = 96, 48
+ VIOLET = (150, 70, 210) # B > R → blue-collapse risk, hue ~274° = violet
+ BLUE = (46, 108, 236) # hue ~221° = blue
+ NAVY = (8, 10, 30) # dark blue
+ WHITE = (255, 255, 255)
+
+ def px(x, y):
+ if y < 8 or y >= 40:
+ return WHITE # white border → corner-background = white, bar = foreground
+ if x < 32:
+ return VIOLET
+ if x < 64:
+ return BLUE
+ return NAVY
+
+ write_rgb_png(self.img, W, H, px)
+
+ def test_hue_name_boundaries(self):
+ self.assertEqual(hue_name(274.0), "violet")
+ self.assertEqual(hue_name(221.0), "blue")
+ self.assertEqual(hue_name(5.0), "red")
+
+ def test_extracts_three_zones_in_order(self):
+ result = extract_gradient_stops(self.img, axis="u", stops=6)
+ names = [z["hueName"] for z in result["hueZones"]]
+ # violet must appear before blue (order preserved along the axis)
+ self.assertIn("violet", names)
+ self.assertIn("blue", names)
+ self.assertLess(names.index("violet"), names.index("blue"))
+
+ def test_flags_blue_collapse_on_violet(self):
+ result = extract_gradient_stops(self.img, axis="u", stops=6)
+ violet_stops = [s for s in result["stops"] if s["hueName"] == "violet"]
+ self.assertTrue(violet_stops, "expected at least one violet stop")
+ v = violet_stops[0]
+ self.assertEqual(v.get("hueRisk"), "blue-collapse")
+ # suggested correction is magenta-leaning: R >= B
+ self.assertGreaterEqual(v["suggestedRgb"][0], v["suggestedRgb"][2])
+
+ def test_deterministic(self):
+ a = extract_gradient_stops(self.img, axis="u", stops=6)
+ b = extract_gradient_stops(self.img, axis="u", stops=6)
+ self.assertEqual([s["rgb"] for s in a["stops"]], [s["rgb"] for s in b["stops"]])
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_hue_zone_parity.py b/forge/tests/test_hue_zone_parity.py
new file mode 100644
index 0000000..ad6683a
--- /dev/null
+++ b/forge/tests/test_hue_zone_parity.py
@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+"""Divine Eye hue_zone_parity (report-only, CIEDE2000).
+Same-shape wrong-hue render must score LOWER than a right-hue render. Pure stdlib.
+"""
+from __future__ import annotations
+
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+REVIEW = Path(__file__).resolve().parents[1] / "stage4_review"
+sys.path.insert(0, str(REVIEW))
+from divine_eye import hue_zone_parity # noqa: E402
+
+
+def write_rgb_png(path: Path, w: int, h: int, fn) -> None:
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(fn(x, y))
+
+ def chunk(t, d):
+ return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
+
+ path.write_bytes(b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
+
+
+VIOLET = (150, 70, 210)
+BLUE = (46, 108, 236)
+WHITE = (255, 255, 255)
+W, H = 96, 48
+
+
+def _bar(color_left, color_right):
+ def fn(x, y):
+ if y < 8 or y >= 40:
+ return WHITE
+ return color_left if x < 48 else color_right
+ return fn
+
+
+class HueZoneParityTest(unittest.TestCase):
+ def setUp(self):
+ self.d = Path(tempfile.mkdtemp())
+ self.ref = self.d / "ref.png"
+ self.right = self.d / "right.png"
+ self.wrong = self.d / "wrong.png"
+ write_rgb_png(self.ref, W, H, _bar(VIOLET, BLUE)) # violet | blue
+ write_rgb_png(self.right, W, H, _bar(VIOLET, BLUE)) # identical hues
+ write_rgb_png(self.wrong, W, H, _bar(BLUE, BLUE)) # left zone collapsed to blue
+
+ def test_right_hue_scores_higher_than_wrong(self):
+ right = hue_zone_parity(self.ref, self.right)
+ wrong = hue_zone_parity(self.ref, self.wrong)
+ self.assertGreater(right, wrong)
+ self.assertGreaterEqual(right, 0.9) # near-perfect hue match
+ self.assertLess(wrong, right) # violet→blue zone drags it down
+
+ def test_deterministic(self):
+ self.assertEqual(hue_zone_parity(self.ref, self.right), hue_zone_parity(self.ref, self.right))
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_intake_binding.py b/forge/tests/test_intake_binding.py
new file mode 100644
index 0000000..b91c266
--- /dev/null
+++ b/forge/tests/test_intake_binding.py
@@ -0,0 +1,88 @@
+#!/usr/bin/env python3
+"""Tests for Plan 1.3 Workstream J (property auto-binding) + §4.6 intake-correctness."""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage1_intake"))
+
+from bind_detail_properties import bind # noqa: E402
+from check_intake_correctness import decide, expose_assumptions # noqa: E402
+
+
+class PropertyBindingTest(unittest.TestCase):
+ def test_glossy_binds_clearcoat(self):
+ b = bind("glossy lacquered paint")
+ self.assertEqual(b["materialProperties"].get("clearcoat"), 1.0)
+ self.assertIn("clearcoatRoughness", b["materialProperties"])
+
+ def test_gem_binds_transmission_ior(self):
+ b = bind("translucent jade blade")
+ self.assertGreater(b["materialProperties"].get("transmission", 0), 0)
+ self.assertIn("ior", b["materialProperties"])
+ self.assertTrue(b["materialProperties"].get("requiresEnvMap"))
+
+ def test_brushed_metal_binds_anisotropy(self):
+ b = bind("brushed steel guard")
+ self.assertIn("anisotropy", b["materialProperties"])
+ self.assertEqual(b["materialProperties"].get("metalness"), 1.0)
+
+ def test_screws_hint_instancing(self):
+ b = bind("row of small screws and rivets")
+ self.assertEqual(b["primitiveHint"], "instanced-cluster")
+
+ def test_logo_hint_decal(self):
+ b = bind("engraved GERBER wordmark logo")
+ self.assertEqual(b["primitiveHint"], "decal")
+
+ def test_fabric_binds_sheen(self):
+ b = bind("velvet cloth grip")
+ self.assertIn("sheen", b["materialProperties"])
+
+ def test_unmatched_is_empty_but_safe(self):
+ b = bind("a nondescript thing")
+ self.assertFalse(b["bound"])
+ self.assertEqual(b["materialProperties"], {})
+ self.assertIsNone(b["primitiveHint"])
+
+
+class IntakeCorrectnessTest(unittest.TestCase):
+ KNIFE = {"preSpecAssessment": {"objectClass": {
+ "primaryType": "karambit knife", "primaryDomain": "object",
+ "materialFamilies": ["jade", "polymer"]}}}
+
+ def test_exposes_assumptions(self):
+ a = expose_assumptions(self.KNIFE)
+ self.assertEqual(a["primaryType"], "karambit knife")
+ self.assertEqual(a["primaryDomain"], "object")
+
+ def test_no_verdict_proceeds_but_defers(self):
+ r = decide(self.KNIFE, None)
+ self.assertEqual(r["action"], "proceed")
+ self.assertFalse(r["confirmed"])
+ self.assertIn("DEFERRED", r["reason"])
+
+ def test_confident_contradiction_halts(self):
+ verdict = {"matchesDeclaredClass": False, "confidence": 0.82, "detectedClass": "spoon"}
+ r = decide(self.KNIFE, verdict)
+ self.assertEqual(r["action"], "halt")
+ self.assertFalse(r["confirmed"])
+
+ def test_low_confidence_contradiction_does_not_halt(self):
+ verdict = {"matchesDeclaredClass": False, "confidence": 0.3, "detectedClass": "spoon"}
+ r = decide(self.KNIFE, verdict)
+ self.assertEqual(r["action"], "proceed")
+
+ def test_match_confirms_and_proceeds(self):
+ verdict = {"matchesDeclaredClass": True, "confidence": 0.9, "detectedClass": "knife"}
+ r = decide(self.KNIFE, verdict)
+ self.assertEqual(r["action"], "proceed")
+ self.assertTrue(r["confirmed"])
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_module_cache.py b/forge/tests/test_module_cache.py
new file mode 100644
index 0000000..d62c327
--- /dev/null
+++ b/forge/tests/test_module_cache.py
@@ -0,0 +1,103 @@
+"""Tests for the per-module code cache (Plan 1.3 Phase 6, Workstream I)."""
+
+import shutil
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "stage3_build"))
+from module_cache import ( # noqa: E402
+ get_module,
+ invalidate_attached,
+ module_cache_key,
+ put_module,
+)
+
+
+class ModuleCacheTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp())
+ self.manifest = self.tmp / ".cache" / "module_cache.json"
+ self.generator = self.tmp / "generator.py"
+ self.generator.write_bytes(b"# generator v1\nprint('hi')\n")
+
+ def tearDown(self):
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def test_key_changes_with_spec(self):
+ key_a = module_cache_key({"id": "blade", "len": 10}, self.generator)
+ key_b = module_cache_key({"id": "blade", "len": 20}, self.generator)
+ self.assertNotEqual(key_a, key_b)
+
+ def test_key_changes_with_generator_source(self):
+ spec = {"id": "blade", "len": 10}
+ gen2 = self.tmp / "generator2.py"
+ gen2.write_bytes(b"# generator v2 -- different bytes\nprint('yo')\n")
+ self.assertNotEqual(
+ module_cache_key(spec, self.generator),
+ module_cache_key(spec, gen2),
+ )
+
+ def test_key_stable_regardless_of_dict_order(self):
+ self.assertEqual(
+ module_cache_key({"a": 1, "b": 2}, self.generator),
+ module_cache_key({"b": 2, "a": 1}, self.generator),
+ )
+
+ def test_put_get_roundtrip(self):
+ spec = {"id": "blade", "len": 10}
+ code = "function makeBlade(){ return mesh; }"
+ put_module(self.manifest, spec, self.generator, code)
+ self.assertEqual(get_module(self.manifest, spec, self.generator), code)
+ # unknown spec -> miss
+ self.assertIsNone(
+ get_module(self.manifest, {"id": "ghost"}, self.generator)
+ )
+
+ def test_invalidate_attached_removes_dependents_only(self):
+ specs = {
+ "root": {"id": "root"},
+ "blade": {"id": "blade", "parent": "root"},
+ "handle": {"id": "handle", "parent": "root"},
+ "pommel": {"id": "pommel", "attachment": {"parentId": "handle"}},
+ }
+ for spec in specs.values():
+ put_module(self.manifest, spec, self.generator, f"code_{spec['id']}")
+
+ components = list(specs.values())
+ invalidated = invalidate_attached(self.manifest, "handle", components)
+
+ self.assertEqual(invalidated, ["pommel"])
+ # pommel gone, everyone else remains
+ self.assertIsNone(
+ get_module(self.manifest, specs["pommel"], self.generator)
+ )
+ self.assertEqual(
+ get_module(self.manifest, specs["root"], self.generator), "code_root"
+ )
+ self.assertEqual(
+ get_module(self.manifest, specs["blade"], self.generator), "code_blade"
+ )
+ self.assertEqual(
+ get_module(self.manifest, specs["handle"], self.generator), "code_handle"
+ )
+
+ def test_invalidate_returns_empty_when_no_dependents(self):
+ specs = {
+ "root": {"id": "root"},
+ "leaf": {"id": "leaf", "parent": "root"},
+ }
+ for spec in specs.values():
+ put_module(self.manifest, spec, self.generator, f"code_{spec['id']}")
+
+ # leaf has no dependents attached to it
+ self.assertEqual(invalidate_attached(self.manifest, "leaf", list(specs.values())), [])
+ # nothing removed
+ self.assertEqual(
+ get_module(self.manifest, specs["leaf"], self.generator), "code_leaf"
+ )
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_multi_angle.py b/forge/tests/test_multi_angle.py
new file mode 100644
index 0000000..93dc4b8
--- /dev/null
+++ b/forge/tests/test_multi_angle.py
@@ -0,0 +1,117 @@
+#!/usr/bin/env python3
+"""Tests for the deterministic Phase-3 §3.2 multi-angle degenerate-view check."""
+
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage4_review"))
+from diagnose_render_multi_angle import analyze_angles, silhouette_area_fraction # noqa: E402
+
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def write_rgb_png(path, w, h, pixel_fn):
+ def chunk(tag, data):
+ c = struct.pack(">I", len(data)) + tag + data
+ return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(pixel_fn(x, y, w, h))
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
+ path.write_bytes(
+ PNG_SIGNATURE
+ + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
+ + chunk(b"IEND", b"")
+ )
+
+
+def _centered_block(x0, y0, x1, y1):
+ """Pixel fn: dark block within [x0,x1)x[y0,y1) on a white background."""
+
+ def fn(x, y, w, h):
+ if x0 <= x < x1 and y0 <= y < y1:
+ return (20, 20, 20)
+ return (255, 255, 255)
+
+ return fn
+
+
+class MultiAngleTest(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp())
+
+ def test_volumetric_object_not_flagged(self):
+ ref = self.tmp / "ref.png"
+ orbit_a = self.tmp / "orbit_a.png"
+ orbit_b = self.tmp / "orbit_b.png"
+ # Reference: big centered block. Orbits: similarly large blocks (a real
+ # 3D volume keeps a substantial silhouette from other angles).
+ write_rgb_png(ref, 200, 200, _centered_block(50, 50, 150, 150))
+ write_rgb_png(orbit_a, 200, 200, _centered_block(55, 45, 155, 160))
+ write_rgb_png(orbit_b, 200, 200, _centered_block(45, 55, 145, 150))
+
+ result = analyze_angles(ref, [orbit_a, orbit_b])
+ self.assertFalse(result["degenerate"])
+ for angle in result["angles"]:
+ self.assertFalse(angle["degenerate"])
+
+ def test_flat_plane_collapses_flagged(self):
+ ref = self.tmp / "ref.png"
+ orbit = self.tmp / "orbit_sliver.png"
+ # Reference: big block filling most of the frame (~0.64). Orbit: a thin
+ # vertical strip, i.e. a billboard seen almost edge-on -> silhouette
+ # area collapses (~0.06, ratio ~0.09 < 0.15). The strip is kept wide
+ # enough (12px) to stay above the shared segmenter's tiny-mask floor
+ # (<3.5% coverage inverts to full-frame), so the collapse is real, not
+ # an artifact of the fallback.
+ write_rgb_png(ref, 200, 200, _centered_block(20, 20, 180, 180))
+ write_rgb_png(orbit, 200, 200, _centered_block(94, 0, 106, 200))
+
+ result = analyze_angles(ref, [orbit])
+ self.assertTrue(result["degenerate"])
+ self.assertTrue(result["angles"][0]["degenerate"])
+
+ def test_vanished_edge_on_plane_flagged(self):
+ # HARDENING regression (lead): a plane orbited nearly edge-on produces a
+ # sub-3.5% silhouette. The shared segmenter's tiny-mask fallback would
+ # otherwise INVERT that to full-frame (fraction ~1.0) and MISS the collapse —
+ # a false negative on the exact case this check exists to catch. The fix in
+ # silhouette_area_fraction reports near-zero when the fallback fired, so a
+ # genuinely-vanished orbit angle is now flagged degenerate.
+ ref = self.tmp / "ref.png"
+ sliver = self.tmp / "vanished.png"
+ write_rgb_png(ref, 200, 200, _centered_block(20, 20, 180, 180))
+ # 3px strip ≈ 1.5% coverage → triggers the tiny-mask fallback
+ write_rgb_png(sliver, 200, 200, _centered_block(99, 0, 102, 200))
+ self.assertLess(silhouette_area_fraction(sliver), 0.02) # near-zero, not inverted 1.0
+ result = analyze_angles(ref, [sliver])
+ self.assertTrue(result["degenerate"])
+ self.assertTrue(result["angles"][0]["degenerate"])
+
+ def test_area_fraction_monotonic(self):
+ big = self.tmp / "big.png"
+ small = self.tmp / "small.png"
+ # A large dark object on WHITE (≈0.64 of frame) vs a small dark dot (≈0.16).
+ # (A full-black frame is NOT used: with no distinguishable background the
+ # segmenter's tiny-mask fallback fires and the area is reported near-zero —
+ # correct for degenerate-view, but a poor fixture for a size-monotonicity check.)
+ write_rgb_png(big, 100, 100, _centered_block(10, 10, 90, 90))
+ write_rgb_png(small, 100, 100, _centered_block(30, 30, 70, 70))
+
+ big_fraction = silhouette_area_fraction(big)
+ small_fraction = silhouette_area_fraction(small)
+ self.assertGreater(big_fraction, small_fraction)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_objectness.py b/forge/tests/test_objectness.py
new file mode 100644
index 0000000..27db8e9
--- /dev/null
+++ b/forge/tests/test_objectness.py
@@ -0,0 +1,85 @@
+#!/usr/bin/env python3
+"""Tests for the stdlib objectness proxy (OSIM-lite), Plan 1.3 task #18.
+
+Proves the property the Divine Eye needed: structural similarity that is invariant to
+background colour and absolute brightness (the photo-vs-procedural axes), while still
+separating different shapes. Pure stdlib, zero token.
+
+Run: python3 forge/tests/test_objectness.py
+"""
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage4_review"))
+
+from objectness import cosine, descriptor, objectness_similarity # noqa: E402
+
+PNG_SIG = b"\x89PNG\r\n\x1a\n"
+
+
+def write_png(path, w, h, pixel_fn):
+ def chunk(tag, data):
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(pixel_fn(x, y))
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
+ path.write_bytes(PNG_SIG + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
+
+
+def diag_bar(fg, bg):
+ # a thick diagonal bar (same shape/orientation regardless of colours)
+ def fn(x, y):
+ return fg if abs((x - y)) < 40 else bg
+ return fn
+
+
+def horiz_bar(fg, bg):
+ def fn(x, y):
+ return fg if 90 <= y < 150 else bg
+ return fn
+
+
+class ObjectnessTest(unittest.TestCase):
+ def setUp(self):
+ self.d = Path(tempfile.mkdtemp())
+ self.W = self.H = 240
+ # same diagonal shape, but opposite brightness AND opposite background
+ self.dark_on_white = self.d / "dark_on_white.png"
+ write_png(self.dark_on_white, self.W, self.H, diag_bar((40, 40, 44), (250, 250, 250)))
+ self.bright_on_dark = self.d / "bright_on_dark.png"
+ write_png(self.bright_on_dark, self.W, self.H, diag_bar((205, 205, 210), (18, 20, 26)))
+ # a different shape (horizontal bar)
+ self.horiz = self.d / "horiz.png"
+ write_png(self.horiz, self.W, self.H, horiz_bar((40, 40, 44), (250, 250, 250)))
+
+ def test_identical_descriptor_cosine_is_one(self):
+ a = descriptor(self.dark_on_white)
+ self.assertAlmostEqual(cosine(a, a), 1.0, places=6)
+
+ def test_invariant_to_background_and_brightness(self):
+ # SAME shape, opposite bg + opposite brightness -> must still score high
+ # (this is exactly where SSIM/IoU/edge collapse for photo-vs-procedural)
+ s = objectness_similarity(self.dark_on_white, self.bright_on_dark)
+ self.assertGreater(s, 0.9, f"expected high objectness for same shape, got {s}")
+
+ def test_separates_different_shapes(self):
+ diag_vs_horiz = objectness_similarity(self.dark_on_white, self.horiz)
+ same = objectness_similarity(self.dark_on_white, self.bright_on_dark)
+ self.assertLess(diag_vs_horiz, same, "different shapes must score below same-shape")
+ self.assertLess(diag_vs_horiz, 0.8, f"diagonal vs horizontal should be clearly lower, got {diag_vs_horiz}")
+
+ def test_score_bounded(self):
+ s = objectness_similarity(self.dark_on_white, self.horiz)
+ self.assertGreaterEqual(s, 0.0)
+ self.assertLessEqual(s, 1.0)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_per_feature.py b/forge/tests/test_per_feature.py
new file mode 100644
index 0000000..8870d33
--- /dev/null
+++ b/forge/tests/test_per_feature.py
@@ -0,0 +1,102 @@
+"""Unit tests for forge/stage4_review/per_feature.py.
+
+Pure stdlib, no images. Exercises the per-feature gating decision logic.
+"""
+
+import os
+import sys
+import unittest
+
+# Make the stage4_review package importable regardless of cwd.
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_FORGE = os.path.dirname(_HERE)
+if _FORGE not in sys.path:
+ sys.path.insert(0, _FORGE)
+
+from stage4_review import per_feature # noqa: E402
+
+
+class PerFeatureTests(unittest.TestCase):
+ def test_all_features_pass(self):
+ targets = [
+ {"id": "recurved-hook", "tier": "critical", "minimumScore": 0.8},
+ {"id": "jade-blade", "tier": "critical", "minimumScore": 0.75},
+ ]
+ scores = {"recurved-hook": 0.9, "jade-blade": 0.85}
+
+ result = per_feature.evaluate_features(targets, scores)
+
+ self.assertTrue(result["passed"])
+ self.assertEqual(result["action"], "continue")
+ self.assertEqual(result["defects"], [])
+
+ def test_critical_below_fails_even_if_others_high(self):
+ targets = [
+ {"id": "recurved-hook", "tier": "critical", "minimumScore": 0.8},
+ {"id": "jade-blade", "tier": "critical", "minimumScore": 0.75},
+ {"id": "pommel", "tier": "detail", "minimumScore": 0.5},
+ ]
+ scores = {"recurved-hook": 0.5, "jade-blade": 1.0, "pommel": 1.0}
+
+ result = per_feature.evaluate_features(targets, scores)
+
+ self.assertFalse(result["passed"])
+ self.assertEqual(result["action"], "refine-code")
+ self.assertTrue(
+ any(d.startswith("below-threshold:recurved-hook") for d in result["defects"]),
+ result["defects"],
+ )
+
+ def test_missing_critical_feature_routes_refine_spec(self):
+ targets = [
+ {"id": "recurved-hook", "tier": "critical", "minimumScore": 0.8},
+ {"id": "jade-blade", "tier": "critical", "minimumScore": 0.75},
+ ]
+ scores = {"recurved-hook": None, "jade-blade": 0.9}
+
+ result = per_feature.evaluate_features(targets, scores)
+
+ self.assertFalse(result["passed"])
+ self.assertEqual(result["action"], "refine-spec")
+ self.assertIn("missing-feature:recurved-hook", result["defects"])
+
+ def test_non_gating_below_threshold_does_not_fail(self):
+ targets = [
+ {"id": "recurved-hook", "tier": "critical", "minimumScore": 0.8},
+ {"id": "engraving", "tier": "important"}, # non-gating, default 0.65
+ ]
+ scores = {"recurved-hook": 0.95, "engraving": 0.4}
+
+ result = per_feature.evaluate_features(targets, scores)
+
+ self.assertTrue(result["passed"])
+ self.assertEqual(result["action"], "continue")
+
+ engraving = next(f for f in result["features"] if f["id"] == "engraving")
+ self.assertEqual(engraving["status"], "below")
+ self.assertFalse(engraving["gating"])
+
+ def test_threshold_defaults_per_tier(self):
+ self.assertEqual(per_feature.threshold_for({"tier": "critical"}), 0.8)
+ self.assertEqual(per_feature.threshold_for({"tier": "important"}), 0.65)
+ self.assertEqual(per_feature.threshold_for({"tier": "detail"}), 0.5)
+
+ def test_missing_from_scores_dict_treated_as_missing(self):
+ targets = [
+ {"id": "recurved-hook", "tier": "critical", "minimumScore": 0.8},
+ ]
+ scores = {} # id not present at all
+
+ result = per_feature.evaluate_features(targets, scores)
+
+ self.assertFalse(result["passed"])
+ self.assertEqual(result["action"], "refine-spec")
+ self.assertIn("missing-feature:recurved-hook", result["defects"])
+
+ feature = result["features"][0]
+ self.assertEqual(feature["status"], "missing")
+ self.assertIsNone(feature["score"])
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_pipeline.py b/forge/tests/test_pipeline.py
index 474b0a1..aca52b5 100644
--- a/forge/tests/test_pipeline.py
+++ b/forge/tests/test_pipeline.py
@@ -74,7 +74,7 @@ class PipelineTest(unittest.TestCase):
"--out", self.spec)
self.assertEqual(r.returncode, 0, r.stderr)
spec = json.loads(self.spec.read_text())
- self.assertEqual(spec["schemaVersion"], "2.0")
+ self.assertEqual(spec["schemaVersion"], "2.1")
self.assertEqual(spec["targetName"], "Oak")
def test_normal_validate_passes_strict_fails_on_shallow(self):
@@ -89,6 +89,120 @@ class PipelineTest(unittest.TestCase):
self.assertNotEqual(strict.returncode, 0)
self.assertIn("strict quality failure", strict.stdout + strict.stderr)
+ def test_topology_rejects_missing_classification(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ del spec["componentTree"][0]["topologyClass"]
+ del spec["componentTree"][0]["topologyRationale"]
+ self.spec.write_text(json.dumps(spec))
+ strict = run("stage2_spec/validate_sculpt_spec.py", self.spec, "--strict-quality")
+ self.assertNotEqual(strict.returncode, 0)
+ self.assertIn("missing or invalid topologyClass", strict.stdout + strict.stderr)
+
+ def test_topology_rejects_restated_rationale(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ spec["componentTree"][0]["topologyClass"] = "assembled-solid"
+ spec["componentTree"][0]["topologyRationale"] = "Assembled Solid"
+ self.spec.write_text(json.dumps(spec))
+ strict = run("stage2_spec/validate_sculpt_spec.py", self.spec, "--strict-quality")
+ self.assertNotEqual(strict.returncode, 0)
+ self.assertIn("restates the enum value", strict.stdout + strict.stderr)
+
+ def test_topology_rejects_disallowed_continuous_sculpt_pairing(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ spec["componentTree"][0]["primitive"] = "box"
+ spec["componentTree"][0]["topologyClass"] = "continuous-sculpt"
+ spec["componentTree"][0]["topologyRationale"] = "Smooth organic bulge with no seams."
+ self.spec.write_text(json.dumps(spec))
+ strict = run("stage2_spec/validate_sculpt_spec.py", self.spec, "--strict-quality")
+ self.assertNotEqual(strict.returncode, 0)
+ self.assertIn("disallowed primitive", strict.stdout + strict.stderr)
+
+ def test_topology_rejects_disallowed_fiber_strand_pairing(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ spec["componentTree"][0]["primitive"] = "plane-card"
+ spec["componentTree"][0]["topologyClass"] = "fiber-strand"
+ spec["componentTree"][0]["topologyRationale"] = "Thin repeated strand form."
+ self.spec.write_text(json.dumps(spec))
+ strict = run("stage2_spec/validate_sculpt_spec.py", self.spec, "--strict-quality")
+ self.assertNotEqual(strict.returncode, 0)
+ self.assertIn("disallowed primitive", strict.stdout + strict.stderr)
+
+ def test_topology_accepts_all_six_classes_with_allowed_primitives(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ cases = [
+ ("continuous-sculpt", "lathe"),
+ ("assembled-solid", "box"),
+ ("conforming-shell", "plane-card"),
+ ("surface-relief", "box"),
+ ("fiber-strand", "tube"),
+ ("material-only", "plane-card"),
+ ]
+ for topology_class, primitive in cases:
+ with self.subTest(topology_class=topology_class):
+ spec["componentTree"][0]["primitive"] = primitive
+ spec["componentTree"][0]["topologyClass"] = topology_class
+ spec["componentTree"][0]["topologyRationale"] = (
+ f"Test fixture citing observed evidence for {topology_class}."
+ )
+ self.spec.write_text(json.dumps(spec))
+ strict = run("stage2_spec/validate_sculpt_spec.py", self.spec, "--strict-quality")
+ self.assertNotIn(
+ "topologyClass", strict.stdout + strict.stderr,
+ f"unexpected topology failure for {topology_class}/{primitive}: {strict.stdout}{strict.stderr}",
+ )
+ self.assertNotIn(
+ "disallowed primitive", strict.stdout + strict.stderr,
+ f"unexpected disallowed-pairing failure for {topology_class}/{primitive}",
+ )
+
+ def test_color_material_recipe_accepts_full_opacity_alpha_format(self):
+ # Regression: lab_to_rgba() in extract_part_color_recipe.py renders full opacity
+ # as "1.0" (round(1.0, 3) -> the float 1.0, not the bare int 1). RGBA_PATTERN must
+ # accept that exact format, or every real extracted recipe fails its own validator.
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ spec["componentTree"][0]["colorMaterialRecipe"] = {
+ "dominantAlbedo": "rgba(21, 87, 78, 1.0)",
+ "secondaryAlbedo": "rgba(34, 67, 67, 1.0)",
+ "materialClass": "glass",
+ "materialClassConfidence": 0.6,
+ }
+ self.spec.write_text(json.dumps(spec))
+ strict = run("stage2_spec/validate_sculpt_spec.py", self.spec, "--strict-quality")
+ self.assertNotIn(
+ "must be an 'rgba(r, g, b, a)' string", strict.stdout + strict.stderr,
+ f"1.0-alpha rgba string was wrongly rejected: {strict.stdout}{strict.stderr}",
+ )
+
+ def test_diagnose_render_tier1_help_and_identical_images(self):
+ r = run("stage4_review/diagnose_render.py", "--help")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ # Identical reference/render images should trivially pass every Tier-1 check.
+ r2 = run("stage4_review/diagnose_render.py", "--reference", self.ref, "--render", self.ref, "--json")
+ self.assertEqual(r2.returncode, 0, r2.stderr)
+ result = json.loads(r2.stdout)
+ self.assertTrue(result["passed"])
+ self.assertEqual(result["checks"]["silhouetteIoU"], 1.0)
+
+ def test_orchestrator_refuses_current_pass_without_passing_tier1(self):
+ # Plan 1.3 Workstream D: the current (unlocked) VISUAL pass must be blocked
+ # until a passing tier1Result is recorded for it.
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ blocked = run("stage3_build/orchestrate_passes.py", "check", self.spec, "--pass-id", "blockout")
+ self.assertNotEqual(blocked.returncode, 0)
+ self.assertIn("Tier 1 diagnostics have not passed", blocked.stdout + blocked.stderr)
+
+ # Recording a PASSING tier1 result (identical ref/render) unblocks it.
+ run("stage4_review/diagnose_render.py", "--reference", self.ref, "--render", self.ref,
+ "--pass-id", "blockout", "--spec", self.spec, "--in-place")
+ unblocked = run("stage3_build/orchestrate_passes.py", "check", self.spec, "--pass-id", "blockout")
+ self.assertEqual(unblocked.returncode, 0, unblocked.stderr)
+
def test_orchestrator_starts_at_blockout(self):
run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
r = run("stage3_build/orchestrate_passes.py", "status", self.spec)
@@ -112,6 +226,276 @@ class PipelineTest(unittest.TestCase):
"--pass-id", "lighting-pass")
self.assertNotEqual(locked.returncode, 0)
+ def test_generate_factory_emits_f3_f4_material_and_environment(self):
+ # Plan 1.3 F.3/F.4: previously-missing MeshPhysicalMaterial properties and the
+ # environment map must both appear in the generated code (codegen-output test,
+ # not a rendering test — fully automatable per the plan's acceptance criteria).
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ out = self.dir / "createObjectModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ for prop in ("sheen:", "sheenColor:", "iridescence:", "iridescenceIOR:",
+ "ior:", "attenuationDistance:", "anisotropy:", "anisotropyRotation:",
+ "specularIntensity:", "specularColor:", "emissive:", "emissiveIntensity:"):
+ self.assertIn(prop, ts, f"missing material property in generated code: {prop}")
+ self.assertIn("import { RoomEnvironment }", ts)
+ self.assertIn("PMREMGenerator", ts)
+ self.assertIn("Environment(renderer: THREE.WebGLRenderer)", ts)
+
+ def test_generate_factory_emits_auto_framing(self):
+ # Plan 1.3 §3.2: auto-framing by bounding box is a prerequisite for the Divine
+ # Eye — an object framed unlike the reference makes every silhouette comparison
+ # meaningless. The generated code must expose a frame<Type>Camera helper that
+ # positions the camera from the object's Box3 and updates the projection matrix.
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ out = self.dir / "createObjectModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("Camera(", ts)
+ self.assertIn("new THREE.Box3().setFromObject", ts)
+ self.assertIn("camera.updateProjectionMatrix()", ts)
+
+ def test_generate_factory_emits_presentation_composer_only(self):
+ # Plan 1.3 §3.2c / R-POSTFX: DOF+bloom live in a SEPARATE presentation composer
+ # (opt-in via options), never wired into the model factory itself — the Eye's
+ # evaluation render must stay post-fx-free. Codegen-output test.
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ out = self.dir / "createObjectModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("PresentationComposer", ts)
+ self.assertIn("EffectComposer", ts)
+ self.assertIn("BokehPass", ts)
+ self.assertIn("UnrealBloomPass", ts)
+ self.assertIn("R-POSTFX", ts)
+ # the composer must be gated on options.dof / options.bloom (opt-in, not forced)
+ self.assertIn("if (options.dof)", ts)
+ self.assertIn("if (options.bloom)", ts)
+
+ def test_generate_factory_builds_real_extrude_lathe_tube_geometry(self):
+ # Plan 1.3 F.5: the original bug — primitive: "extrude" (e.g. a knife blade
+ # tapering to a sharp point) used to validate fine but silently render as a
+ # generic box. Confirms all three previously-unimplemented primitives now
+ # produce real geometry-builder calls instead of raising or falling back.
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ spec["componentTree"][0]["primitive"] = "extrude"
+ spec["componentTree"][0]["topologyClass"] = "continuous-sculpt"
+ spec["componentTree"][0]["topologyRationale"] = "Blade tapering to a single sharp point."
+ spec["componentTree"][0]["geometryDescriptor"]["profile2D"] = {
+ "points": [[-0.05, 0.0], [0.05, 0.0], [0.0, 0.6]], # converges to a real point
+ "depth": 0.02,
+ }
+ self.spec.write_text(json.dumps(spec))
+ out = self.dir / "createOakModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("buildExtrudeGeometry", ts)
+ self.assertIn("bevelEnabled: false", ts)
+ self.assertIn("shape.lineTo", ts)
+ self.assertNotIn("BoxGeometry(1, 1, 1, 8, 8, 8)", ts) # the old silent fallback
+
+ for primitive, builder in (("lathe", "buildLatheGeometry"), ("tube", "buildTubeGeometry")):
+ with self.subTest(primitive=primitive):
+ spec["componentTree"][0]["primitive"] = primitive
+ self.spec.write_text(json.dumps(spec))
+ r2 = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out, "--force")
+ self.assertEqual(r2.returncode, 0, r2.stderr)
+ self.assertIn(builder, out.read_text())
+
+ def test_generate_factory_omits_unused_geometry_helpers(self):
+ # Regression: a real showcase integration build failed TypeScript's
+ # noUnusedLocals because buildLatheGeometry/buildTubeGeometry were emitted
+ # unconditionally even when no component in the pass used lathe/tube. Only
+ # the primitives actually present should get a helper function.
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ spec["componentTree"][0]["primitive"] = "extrude"
+ spec["componentTree"][0]["topologyClass"] = "continuous-sculpt"
+ spec["componentTree"][0]["topologyRationale"] = "Blade tapering to a single sharp point."
+ spec["componentTree"][0]["geometryDescriptor"]["profile2D"] = {
+ "points": [[-0.05, 0.0], [0.05, 0.0], [0.0, 0.6]],
+ "depth": 0.02,
+ }
+ self.spec.write_text(json.dumps(spec))
+ out = self.dir / "createOakModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("buildExtrudeGeometry", ts)
+ self.assertNotIn("function buildLatheGeometry", ts)
+ self.assertNotIn("function buildTubeGeometry", ts)
+
+ def test_instanced_cluster_component_now_implemented(self):
+ # instanced-cluster used to fall through geometry_for() and fail loudly; it now
+ # resolves to its base geometry (default box) so a component may declare it without
+ # crashing. The instancing itself is applied by repetition systems (test below).
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ spec["componentTree"][0]["primitive"] = "instanced-cluster"
+ self.spec.write_text(json.dumps(spec))
+ out = self.dir / "createOakModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ self.assertIn("BoxGeometry", out.read_text())
+
+ def test_repetition_system_emits_instanced_mesh(self):
+ # Repeated parts (teeth/fasteners/spokes) must render as ONE THREE.InstancedMesh
+ # (single draw call), not a per-instance Mesh clone loop (real-time perf principle).
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ first_mat = (spec.get("materials") or [{}])[0].get("id", "base")
+ spec["repetitionSystems"] = [{
+ "id": "teeth", "level": "macro", "parent": "root", "count": 8,
+ "primitive": "box", "material": first_mat,
+ "instanceScale": [0.05, 0.05, 0.05],
+ "placement": {"mode": "radial", "axis": [0, 0, 1], "radius": 0.5, "startAngleDeg": 0},
+ }]
+ self.spec.write_text(json.dumps(spec))
+ out = self.dir / "createOakModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("new THREE.InstancedMesh(geo, mat, 8)", ts)
+ self.assertIn("setMatrixAt", ts)
+ self.assertNotIn("new THREE.Mesh(geo, mat)", ts) # no leftover clone loop
+
+ def test_geometry_for_raises_for_unimplemented_primitive(self):
+ # The GeometryNotImplementedError guard still protects any FUTURE primitive added to
+ # VALID_PRIMITIVES without a geometry_for() branch (never a silent box fallback).
+ import importlib.util
+ gen_path = SCRIPTS / "stage3_build" / "generate_threejs_factory.py"
+ sys.path.insert(0, str(SCRIPTS / "stage3_build"))
+ mod_spec = importlib.util.spec_from_file_location("gen_factory_test", gen_path)
+ gen = importlib.util.module_from_spec(mod_spec)
+ mod_spec.loader.exec_module(gen)
+ with self.assertRaises(gen.GeometryNotImplementedError):
+ gen.geometry_for("some-future-unimplemented-primitive")
+
+ def test_generate_factory_builds_curve_sweep(self):
+ # F.6: curve-sweep sweeps a thin cross-section along a 3D spine so a curved form
+ # reads correctly from every angle (the karambit-blade fix). Must emit a real
+ # extrudePath + CatmullRomCurve3, only when a component uses curve-sweep.
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ spec["componentTree"][0]["primitive"] = "curve-sweep"
+ spec["componentTree"][0]["topologyClass"] = "continuous-sculpt"
+ spec["componentTree"][0]["topologyRationale"] = "Hooked blade curving through space."
+ spec["componentTree"][0]["geometryDescriptor"]["curveSweep"] = {
+ "spine": [[-0.5, -0.4, 0.0], [0.0, 0.1, 0.0], [0.5, -0.2, 0.0]],
+ "crossSection": {"points": [[-0.04, -0.02], [0.04, -0.02], [0.04, 0.02], [-0.04, 0.02]]},
+ "closed": False,
+ }
+ self.spec.write_text(json.dumps(spec))
+ out = self.dir / "createOakModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("buildCurveSweepGeometry", ts)
+ self.assertIn("extrudePath", ts)
+ self.assertIn("CatmullRomCurve3", ts)
+ self.assertIn("bevelEnabled: false", ts)
+ # conditional emission: a box-only spec must NOT carry the curve-sweep helper
+ spec["componentTree"][0]["primitive"] = "box"
+ self.spec.write_text(json.dumps(spec))
+ r2 = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out, "--force")
+ self.assertEqual(r2.returncode, 0, r2.stderr)
+ self.assertNotIn("function buildCurveSweepGeometry", out.read_text())
+
+ def test_ground_blade_uv_uses_actual_y_bounds(self):
+ # ground-blade UVs must map v across the blade's ACTUAL Y bounds, not a hardcoded
+ # ±0.12. An off-origin blade (y~0.4) with the old formula clamped v→1 so every face sampled
+ # the bright spine-rim row → white/washed tip facets. Corrected UV = (y - yMin) / yH.
+ run("stage2_spec/new_sculpt_spec.py", "Blade", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ c = spec["componentTree"][0]
+ c["primitive"] = "ground-blade"
+ c["topologyClass"] = "continuous-sculpt"
+ c["topologyRationale"] = "Blade lofted along beveled stations to a sharp point."
+ c["geometryDescriptor"]["bladeSpec"] = {
+ "stations": [[0, 0.55, 0.30], [0.5, 0.56, 0.31], [1.0, 0.50, 0.40]],
+ "thickness": 0.05,
+ }
+ self.spec.write_text(json.dumps(spec))
+ out = self.dir / "createBladeModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("yMin = Math.min(yMin, s[2])", ts) # bounds from actual stations
+ self.assertIn("(pos[t + 1] - yMin) / yH", ts) # v spans real height
+ self.assertNotIn("+ 0.12) / 0.24", ts) # old hardcoded formula gone
+
+ def test_extrude_supports_oval_hole_via_shape_holes(self):
+ # a cutout (wire-cutter oval hole) is done via THREE.Shape.holes — dep-free, no
+ # three-bvh-csg. The generator must emit hole-handling + oval-loop support on extrude.
+ run("stage2_spec/new_sculpt_spec.py", "Blade", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ c = spec["componentTree"][0]
+ c["primitive"] = "extrude"
+ c["topologyClass"] = "continuous-sculpt"
+ c["topologyRationale"] = "Flat blade plate with an oval wire-cutter cutout."
+ c["geometryDescriptor"]["profile2D"] = {
+ "points": [[-0.05, 0.0], [0.05, 0.0], [0.0, 0.6]],
+ "depth": 0.02,
+ "ovalHoles": [{"cx": 0.0, "cy": 0.3, "rx": 0.02, "ry": 0.035}],
+ }
+ self.spec.write_text(json.dumps(spec))
+ out = self.dir / "createBladeModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("shape.holes.push(path)", ts) # cutout via Shape.holes
+ self.assertIn("ovalLoop", ts) # oval-hole authoring helper
+ self.assertNotIn("three-bvh-csg", ts) # no CSG dependency
+
+ def test_flatness_pre_check_flags_thin_continuous_sculpt_extrude(self):
+ # G.1: a continuous-sculpt form (asserted to be a volumetric 3D shape) built as a
+ # THIN straight extrude (flat slab) must be flagged before render; the same form
+ # with real thickness must not.
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ c = spec["componentTree"][0]
+ c["primitive"] = "extrude"
+ c["topologyClass"] = "continuous-sculpt"
+ c["topologyRationale"] = "Hooked blade silhouette, single continuous form."
+ # thin slab (depth ≪ diagonal) under a continuous-sculpt claim → HIGH flatness risk
+ c["geometryDescriptor"]["profile2D"] = {
+ "points": [[0.0, 0.0], [0.5, 0.6], [1.0, 0.0], [0.5, -0.05]],
+ "depth": 0.02,
+ }
+ self.spec.write_text(json.dumps(spec))
+ strict = run("stage2_spec/validate_sculpt_spec.py", self.spec, "--strict-quality")
+ self.assertNotEqual(strict.returncode, 0)
+ self.assertIn("flatness risk", strict.stdout + strict.stderr)
+ # same profile with real depth (not a thin slab) must NOT trip the flatness gate
+ c["geometryDescriptor"]["profile2D"]["depth"] = 0.5
+ self.spec.write_text(json.dumps(spec))
+ strict2 = run("stage2_spec/validate_sculpt_spec.py", self.spec, "--strict-quality")
+ self.assertNotIn("flatness risk", strict2.stdout + strict2.stderr)
+
+ def test_generate_factory_emits_color_gradient_codegen(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ spec = json.loads(self.spec.read_text())
+ spec["materials"][0]["colorGradient"] = {
+ "type": "linear",
+ "axis": [1.0, 0.0],
+ "stops": [
+ {"offset": 0.0, "color": "rgba(60, 45, 30, 1.0)"},
+ {"offset": 1.0, "color": "rgba(200, 155, 120, 1.0)"},
+ ],
+ }
+ self.spec.write_text(json.dumps(spec))
+ out = self.dir / "createObjectModel.ts"
+ r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
+ self.assertEqual(r.returncode, 0, r.stderr)
+ ts = out.read_text()
+ self.assertIn("sampleColorGradient", ts)
+ self.assertIn("colorGradient", ts)
+
def test_comparison_sheet_packages_without_scoring(self):
cmp = self.dir / "cmp.png"
r = run("stage4_review/make_comparison_sheet.py", "--reference", self.ref,
@@ -214,10 +598,45 @@ class PipelineTest(unittest.TestCase):
def test_new_upgrade_scripts_help(self):
for script in ("stage1_intake/build_detail_inventory.py", "stage1_intake/extract_landmarks.py",
"stage1_intake/solve_camera_pose.py", "stage1_intake/delight_albedo.py",
- "stage3_build/bake_projected_texture.py"):
+ "stage3_build/bake_projected_texture.py", "stage1_intake/extract_part_color_recipe.py"):
r = run(script, "--help")
self.assertEqual(r.returncode, 0, f"{script}: {r.stderr}")
+ def test_extract_part_color_recipe_cache_hit_and_invalidation(self):
+ # Plan 1.3 Workstream E: same crop + unchanged script -> cache hit on 2nd run.
+ r1 = run("stage1_intake/extract_part_color_recipe.py", self.ref,
+ "--component-id", "root")
+ self.assertEqual(r1.returncode, 0, r1.stderr)
+ self.assertFalse(json.loads(r1.stdout)["cacheHit"])
+
+ r2 = run("stage1_intake/extract_part_color_recipe.py", self.ref,
+ "--component-id", "root")
+ self.assertEqual(r2.returncode, 0, r2.stderr)
+ self.assertTrue(json.loads(r2.stdout)["cacheHit"])
+
+ cache_file = self.ref.parent / ".cache" / "color_recipe_cache.json"
+ self.assertTrue(cache_file.exists())
+
+ # --no-cache bypasses the cache entirely, even with an existing hit available.
+ r3 = run("stage1_intake/extract_part_color_recipe.py", self.ref,
+ "--component-id", "root", "--no-cache")
+ self.assertEqual(r3.returncode, 0, r3.stderr)
+ self.assertFalse(json.loads(r3.stdout)["cacheHit"])
+
+ def test_extract_part_color_recipe_patches_spec(self):
+ run("stage2_spec/new_sculpt_spec.py", "Oak", "--out", self.spec)
+ r = run("stage1_intake/extract_part_color_recipe.py", self.ref,
+ "--component-id", "root", "--spec", self.spec, "--in-place",
+ "--allow-low-confidence")
+ self.assertEqual(r.returncode, 0, r.stderr)
+ recipe = json.loads(r.stdout)
+ self.assertIn("dominantAlbedo", recipe)
+ self.assertTrue(recipe["dominantAlbedo"].startswith("rgba("))
+ self.assertIn("materialClass", recipe)
+ spec = json.loads(self.spec.read_text())
+ self.assertIn("colorMaterialRecipe", spec["componentTree"][0])
+ self.assertEqual(spec["componentTree"][0]["colorMaterialRecipe"]["dominantAlbedo"], recipe["dominantAlbedo"])
+
def test_build_detail_inventory_slices_zones(self):
out = self.dir / "di.json"
zones = self.dir / "zones"
diff --git a/forge/tests/test_reference_admission.py b/forge/tests/test_reference_admission.py
new file mode 100644
index 0000000..55ff0c6
--- /dev/null
+++ b/forge/tests/test_reference_admission.py
@@ -0,0 +1,151 @@
+#!/usr/bin/env python3
+"""Tests for Plan 1.3 §4.5 reference admission + the shared pHash (§3.1 signal).
+
+Pure stdlib synthetic PNGs (RGB, 8-bit, non-interlaced — the format read_png parses
+natively). No PIL/numpy.
+"""
+
+from __future__ import annotations
+
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage1_intake"))
+sys.path.insert(0, str(ROOT / "_shared"))
+
+from check_reference_admission import check_admission, largest_component_fraction # noqa: E402
+from image_hash import hamming, phash_from_image # noqa: E402
+
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+
+
+def write_rgb_png(path: Path, w: int, h: int, pixel_fn) -> None:
+ def chunk(tag: bytes, data: bytes) -> bytes:
+ c = struct.pack(">I", len(data)) + tag + data
+ return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(pixel_fn(x, y, w, h))
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
+ png = (
+ PNG_SIGNATURE
+ + chunk(b"IHDR", ihdr)
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9))
+ + chunk(b"IEND", b"")
+ )
+ path.write_bytes(png)
+
+
+def _centered_block(cx0, cy0, cx1, cy1, fg=(200, 30, 30), bg=(255, 255, 255)):
+ def fn(x, y, w, h):
+ return fg if (cx0 <= x < cx1 and cy0 <= y < cy1) else bg
+ return fn
+
+
+class ImageHashTest(unittest.TestCase):
+ def _split_image(self, vertical: bool, size=64):
+ px = []
+ for y in range(size):
+ for x in range(size):
+ lo = (x if vertical else y) < size // 2
+ v = 30 if lo else 220
+ px.append((v, v, v, 255))
+ return px
+
+ def test_identical_hamming_zero(self):
+ px = self._split_image(vertical=True)
+ self.assertEqual(hamming(phash_from_image(64, 64, px), phash_from_image(64, 64, px)), 0)
+
+ def test_brightness_shift_barely_changes_hash(self):
+ px = self._split_image(vertical=True)
+ bright = [(min(255, v + 20),) * 3 + (255,) for (v, _g, _b, _a) in px]
+ bright = [(t[0], t[1], t[2], t[3]) for t in bright]
+ self.assertLessEqual(hamming(phash_from_image(64, 64, px), phash_from_image(64, 64, bright)), 4)
+
+ def test_different_structure_differs_substantially(self):
+ a = phash_from_image(64, 64, self._split_image(vertical=True))
+ b = phash_from_image(64, 64, self._split_image(vertical=False))
+ self.assertGreaterEqual(hamming(a, b), 8)
+
+
+class ReferenceAdmissionTest(unittest.TestCase):
+ def setUp(self):
+ self.dir = Path(tempfile.mkdtemp())
+
+ def test_admits_coherent_centered_subject(self):
+ p = self.dir / "good.png"
+ write_rgb_png(p, 200, 200, _centered_block(50, 50, 150, 150))
+ v = check_admission(p, viewpoint="side")
+ self.assertTrue(v["admitted"], v["reasons"])
+ self.assertGreater(v["provenance"]["largestComponentFraction"], 0.9)
+
+ def test_rejects_no_isolable_subject(self):
+ # all-background: build_foreground_mask's fallback treats every pixel as
+ # foreground → coverage saturates → "no background to segment" rejection.
+ p = self.dir / "blank.png"
+ write_rgb_png(p, 200, 200, lambda x, y, w, h: (255, 255, 255))
+ v = check_admission(p)
+ self.assertFalse(v["admitted"])
+ self.assertTrue(any("coverage" in r for r in v["reasons"]), v["reasons"])
+
+ def test_rejects_tiny_resolution(self):
+ p = self.dir / "tiny.png"
+ write_rgb_png(p, 40, 40, _centered_block(10, 10, 30, 30))
+ v = check_admission(p)
+ self.assertFalse(v["admitted"])
+ self.assertTrue(any("resolution floor" in r for r in v["reasons"]), v["reasons"])
+
+ def test_rejects_fragmented_mask(self):
+ # 16 separated 16×16 red squares on white → coverage ~0.10 (in band) but the
+ # largest connected blob is a tiny fraction of foreground → coherence rejection.
+ def fn(x, y, w, h):
+ for gx in (10, 55, 100, 145):
+ for gy in (10, 55, 100, 145):
+ if gx <= x < gx + 16 and gy <= y < gy + 16:
+ return (200, 30, 30)
+ return (255, 255, 255)
+ p = self.dir / "frag.png"
+ write_rgb_png(p, 200, 200, fn)
+ v = check_admission(p)
+ self.assertFalse(v["admitted"])
+ self.assertTrue(any("coherence" in r for r in v["reasons"]), v["reasons"])
+
+ def test_rejects_duplicate(self):
+ p = self.dir / "dup.png"
+ write_rgb_png(p, 200, 200, _centered_block(50, 50, 150, 150))
+ first = check_admission(p, viewpoint="front")
+ self.assertTrue(first["admitted"], first["reasons"])
+ again = check_admission(p, viewpoint="front", against_hashes=[first["provenance"]["pHash"]])
+ self.assertFalse(again["admitted"])
+ self.assertTrue(any("duplicate" in r for r in again["reasons"]), again["reasons"])
+
+ def test_rejects_undecodable_cleanly(self):
+ # a truncated/bogus file must be a clean rejection, never a crash/exit-2.
+ p = self.dir / "bogus.png"
+ p.write_bytes(PNG_SIGNATURE + b"\x00\x01\x02garbage")
+ v = check_admission(p)
+ self.assertFalse(v["admitted"])
+ self.assertTrue(any("cannot decode" in r for r in v["reasons"]), v["reasons"])
+
+ def test_largest_component_fraction_math(self):
+ # one solid 4×4 blob in a 6×6 grid → fraction 1.0
+ w = h = 6
+ mask = [(1 <= i % w <= 4 and 1 <= i // w <= 4) for i in range(w * h)]
+ self.assertAlmostEqual(largest_component_fraction(mask, w, h, grid=6), 1.0, places=3)
+ # two separated single cells → largest fraction 0.5
+ mask2 = [False] * (w * h)
+ mask2[0] = True
+ mask2[w * h - 1] = True
+ self.assertAlmostEqual(largest_component_fraction(mask2, w, h, grid=6), 0.5, places=3)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_reference_effects.py b/forge/tests/test_reference_effects.py
new file mode 100644
index 0000000..479073e
--- /dev/null
+++ b/forge/tests/test_reference_effects.py
@@ -0,0 +1,117 @@
+#!/usr/bin/env python3
+"""Tests for stage1_intake/detect_reference_effects.py (pure stdlib, unittest).
+
+Synthetic RGB PNGs are written with the verbatim helper below. Images are kept
+comfortably above the shared segmenter's tiny-mask floor: build_foreground_mask
+INVERTS any mask covering < 3.5% of the frame to "all foreground", so every
+subject here is ~5-25% of the frame.
+"""
+
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage1_intake"))
+from detect_reference_effects import ( # noqa: E402
+ detect_background_blur,
+ detect_highlight_glow,
+ recommend_effects,
+)
+
+
+# --- verbatim PNG helper (copied as instructed) --------------------------- #
+import struct, zlib
+PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
+def write_rgb_png(path, w, h, pixel_fn):
+ def chunk(tag, data):
+ c = struct.pack(">I", len(data)) + tag + data
+ return c + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(pixel_fn(x, y, w, h))
+ ihdr = struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0)
+ path.write_bytes(PNG_SIGNATURE + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
+# -------------------------------------------------------------------------- #
+
+
+class ReferenceEffectTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = Path(tempfile.mkdtemp())
+
+ def _sharp_scene(self, x, y, w, h):
+ # Colored (red) checkerboard subject block on a sharp grayscale
+ # checkerboard background. The red block is caught by the saturation
+ # path of the mask (coverage ~25%); the background stays highly
+ # textured so its gradient energy is NOT far below the subject.
+ checker = (x + y) % 2 == 0
+ in_subject = 30 <= x < 90 and 30 <= y < 90
+ if in_subject:
+ return (210, 50, 50) if checker else (110, 20, 20)
+ return (200, 200, 200) if checker else (60, 60, 60)
+
+ def _shallow_dof(self, x, y, w, h):
+ # High-contrast grayscale checkerboard subject block (~25% coverage)
+ # on a perfectly FLAT uniform background (zero gradient energy).
+ in_subject = 30 <= x < 90 and 30 <= y < 90
+ if in_subject:
+ return (200, 200, 200) if (x + y) % 2 == 0 else (20, 20, 20)
+ return (120, 120, 120)
+
+ def _flat_gray(self, x, y, w, h):
+ return (120, 120, 120)
+
+ def _glow(self, x, y, w, h):
+ # Concentric brightness: small white core (luma > 0.92) surrounded by a
+ # gradual gray halo (~0.7 luma) fading to a dark background.
+ dx = x - w // 2
+ dy = y - h // 2
+ dd = dx * dx + dy * dy
+ if dd <= 9: # core radius 3 -> ~0.8% hot pixels on a 60x60 frame
+ return (250, 250, 250)
+ if dd <= 81: # halo radius 4..9
+ return (180, 180, 180)
+ return (30, 30, 30)
+
+ def test_sharp_scene_no_blur(self):
+ path = self.tmp / "sharp.png"
+ write_rgb_png(path, 120, 120, self._sharp_scene)
+ result = detect_background_blur(path)
+ self.assertFalse(result["blurred"], result["reason"])
+
+ def test_shallow_dof_flagged(self):
+ path = self.tmp / "dof.png"
+ write_rgb_png(path, 120, 120, self._shallow_dof)
+ result = detect_background_blur(path)
+ self.assertTrue(result["blurred"], result["reason"])
+ self.assertLess(result["ratio"], 0.5)
+
+ def test_no_glow_on_flat_image(self):
+ path = self.tmp / "flat.png"
+ write_rgb_png(path, 60, 60, self._flat_gray)
+ result = detect_highlight_glow(path)
+ self.assertFalse(result["glow"], result["reason"])
+
+ def test_glow_flagged(self):
+ path = self.tmp / "glow.png"
+ write_rgb_png(path, 60, 60, self._glow)
+ result = detect_highlight_glow(path)
+ self.assertTrue(result["glow"], result["reason"])
+ self.assertGreater(result["hotFraction"], 0.005)
+ self.assertGreater(result["haloFraction"], 0.5)
+
+ def test_recommend_effects_shape(self):
+ path = self.tmp / "shape.png"
+ write_rgb_png(path, 120, 120, self._sharp_scene)
+ result = recommend_effects(path)
+ for key in ("dof", "bloom", "blur", "glow"):
+ self.assertIn(key, result)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_specular_wash.py b/forge/tests/test_specular_wash.py
new file mode 100644
index 0000000..53732a3
--- /dev/null
+++ b/forge/tests/test_specular_wash.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python3
+"""Divine Eye specular_wash (report-only). A saturated reference rendered
+desaturated + hue-drifted toward cyan must be flagged; a hue-matched render must not. Stdlib.
+"""
+from __future__ import annotations
+
+import struct
+import sys
+import tempfile
+import unittest
+import zlib
+from pathlib import Path
+
+REVIEW = Path(__file__).resolve().parents[1] / "stage4_review"
+sys.path.insert(0, str(REVIEW))
+from divine_eye import specular_wash # noqa: E402
+
+
+def write_rgb_png(path: Path, w: int, h: int, fn) -> None:
+ raw = bytearray()
+ for y in range(h):
+ raw.append(0)
+ for x in range(w):
+ raw += bytes(fn(x, y))
+
+ def chunk(t, d):
+ return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xFFFFFFFF)
+
+ path.write_bytes(b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(bytes(raw), 9)) + chunk(b"IEND", b""))
+
+
+WHITE = (255, 255, 255)
+W, H = 96, 48
+
+
+def _solid(color):
+ def fn(x, y):
+ return WHITE if (y < 8 or y >= 40) else color
+ return fn
+
+
+class SpecularWashTest(unittest.TestCase):
+ def setUp(self):
+ self.d = Path(tempfile.mkdtemp())
+ self.ref = self.d / "ref.png"
+ self.washed = self.d / "washed.png"
+ self.matched = self.d / "matched.png"
+ write_rgb_png(self.ref, W, H, _solid((150, 70, 210))) # saturated purple
+ write_rgb_png(self.washed, W, H, _solid((150, 180, 200))) # desaturated, drifted toward cyan
+ write_rgb_png(self.matched, W, H, _solid((150, 70, 210))) # same purple
+
+ def test_washed_render_flagged(self):
+ r = specular_wash(self.ref, self.washed)
+ self.assertTrue(r["flagged"])
+ self.assertLess(r["satRatio"], 0.6)
+ self.assertTrue(r["towardCyan"])
+ self.assertIsNotNone(r["advice"])
+
+ def test_matched_render_not_flagged(self):
+ r = specular_wash(self.ref, self.matched)
+ self.assertFalse(r["flagged"])
+ self.assertGreaterEqual(r["satRatio"], 0.95)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/forge/tests/test_tier1_diagnostics.py b/forge/tests/test_tier1_diagnostics.py
new file mode 100644
index 0000000..d5e5fe3
--- /dev/null
+++ b/forge/tests/test_tier1_diagnostics.py
@@ -0,0 +1,109 @@
+#!/usr/bin/env python3
+"""Unit tests for Plan 1.3 Workstream B's Tier-1 diagnostics: silhouette_iou,
+bilateral_symmetry_error, proportion_delta with golden values, independent of
+forge/tests/test_pipeline.py per the plan's acceptance criteria.
+
+Run: python3 forge/tests/test_tier1_diagnostics.py
+"""
+import sys
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "stage4_review"))
+
+from diagnose_render import ( # noqa: E402
+ bbox_of,
+ bilateral_symmetry_error,
+ color_is_gated,
+ proportion_delta,
+ silhouette_iou,
+)
+
+
+class ColorGateByPassTest(unittest.TestCase):
+ """Per-part color is a hard criterion only from material-pass onward.
+ Clay passes (blockout/structural/form) must not be failed on color they
+ deliberately lack (regression: teardrop-era blockout blocked by ΔE 56)."""
+
+ def test_pre_material_passes_are_not_color_gated(self):
+ for pid in ("blockout", "structural-pass", "form-refinement"):
+ self.assertFalse(color_is_gated(pid), pid)
+
+ def test_material_pass_and_later_are_color_gated(self):
+ for pid in ("material-pass", "surface-pass", "lighting-pass",
+ "interaction-pass", "optimization-pass"):
+ self.assertTrue(color_is_gated(pid), pid)
+
+ def test_unknown_or_missing_pass_is_not_gated(self):
+ self.assertFalse(color_is_gated(None))
+ self.assertFalse(color_is_gated("not-a-real-pass"))
+
+
+def make_mask(size: int, foreground_fn) -> list[bool]:
+ return [foreground_fn(x, y, size) for y in range(size) for x in range(size)]
+
+
+class SilhouetteIouTest(unittest.TestCase):
+ def test_identical_masks_give_iou_one(self):
+ mask = make_mask(10, lambda x, y, s: x < 5)
+ self.assertEqual(silhouette_iou(mask, mask), 1.0)
+
+ def test_disjoint_masks_give_iou_zero(self):
+ left = make_mask(10, lambda x, y, s: x < 5)
+ right = make_mask(10, lambda x, y, s: x >= 5)
+ self.assertEqual(silhouette_iou(left, right), 0.0)
+
+ def test_known_overlap_fraction(self):
+ # Two identical NxN squares offset by N/2 in both axes: analytically-known
+ # overlap fraction is 1/7 (area of intersection quadrant / union of the two
+ # L-shaped squares). Using two half-size (N/2 x N/2) foreground blocks placed
+ # so they overlap in exactly one N/2 x N/2 quadrant out of a 7-quadrant union.
+ size = 8
+ half = size // 2
+ # Block A: top-left half x half. Block B: offset by half in both axes.
+ block_a = make_mask(size, lambda x, y, s, h=half: x < h and y < h)
+ block_b = make_mask(size, lambda x, y, s, h=half: h // 2 <= x < h // 2 + h and h // 2 <= y < h // 2 + h)
+ iou = silhouette_iou(block_a, block_b)
+ # intersection = (h/2)^2, each block area = h^2, union = 2*h^2 - (h/2)^2 = 7/4 h^2
+ # iou = (h/2)^2 / (7/4 h^2) = (1/4) / (7/4) = 1/7
+ self.assertAlmostEqual(iou, 1 / 7, delta=0.01)
+
+
+class SymmetryErrorTest(unittest.TestCase):
+ def test_perfectly_symmetric_mask_has_zero_error(self):
+ size = 16
+ # bilateral_symmetry_error mirrors x -> size - 1 - x, whose axis sits at
+ # (size - 1) / 2 = 7.5 for size=16 — the foreground band must be centered
+ # there (not at size // 2 = 8) to be genuinely symmetric under that exact
+ # transform.
+ mask = make_mask(size, lambda x, y, s: abs(x - (s - 1) / 2) < 3)
+ self.assertAlmostEqual(bilateral_symmetry_error(mask, size=size), 0.0, delta=0.01)
+
+ def test_maximally_asymmetric_mask_has_error_one(self):
+ size = 16
+ mask = make_mask(size, lambda x, y, s: x < s // 2)
+ self.assertAlmostEqual(bilateral_symmetry_error(mask, size=size), 1.0, delta=0.01)
+
+
+class ProportionDeltaTest(unittest.TestCase):
+ def test_identical_bboxes_have_zero_deltas(self):
+ delta = proportion_delta((0, 0, 100, 50), (0, 0, 100, 50))
+ self.assertEqual(delta["aspect_ratio_delta"], 0.0)
+ self.assertEqual(delta["scale_delta"], 0.0)
+
+ def test_axis_scaled_bbox_has_known_aspect_ratio_delta(self):
+ # Reference is 100x50 (AR=2.0); render is 100x100 (AR=1.0) -> delta = |2-1|/2 = 0.5
+ delta = proportion_delta((0, 0, 100, 50), (0, 0, 100, 100))
+ self.assertAlmostEqual(delta["aspect_ratio_delta"], 0.5, delta=0.001)
+
+
+class BboxOfTest(unittest.TestCase):
+ def test_bbox_matches_known_foreground_region(self):
+ size = 20
+ mask = make_mask(size, lambda x, y, s: 4 <= x < 10 and 2 <= y < 8)
+ x0, y0, w, h = bbox_of(mask, size=size)
+ self.assertEqual((x0, y0, w, h), (4, 2, 6, 6))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/forge/tests/test_vlm_gate.py b/forge/tests/test_vlm_gate.py
new file mode 100644
index 0000000..59f9336
--- /dev/null
+++ b/forge/tests/test_vlm_gate.py
@@ -0,0 +1,101 @@
+#!/usr/bin/env python3
+"""Tests for the VLM gating layer (Plan 1.3 §3.4). Uses stub samplers — no real model, no token."""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "stage4_review"))
+
+from vlm_gate import aggregate_samples, calibrate, evidence_consistent, gate # noqa: E402
+
+
+def const_sampler(scores: dict):
+ return lambda i: dict(scores)
+
+
+def high_all(claimed="knife"):
+ return {"objectness": 0.9, "semantic": 0.88, "structural": 0.86, "specular": 0.85, "claimedClass": claimed}
+
+
+class VlmGateTest(unittest.TestCase):
+ def test_hard_gate_failure_does_not_consult_vlm(self):
+ eye = {"verdict": "reject", "action": "refine-code", "hardGateFailures": ["silhouette IoU 0.40 < 0.85"]}
+ called = {"n": 0}
+ def sampler(i):
+ called["n"] += 1
+ return high_all()
+ r = gate(eye, sampler)
+ self.assertFalse(r["ranVlm"])
+ self.assertEqual(r["verdict"], "reject")
+ self.assertEqual(called["n"], 0, "VLM must not be called when a hard gate failed")
+
+ def test_pass_confirmed_when_all_criteria_high(self):
+ eye = {"verdict": "pass", "action": "continue", "hardGateFailures": []}
+ r = gate(eye, const_sampler(high_all()), geometry_class="knife")
+ self.assertEqual(r["verdict"], "pass")
+ self.assertEqual(r["action"], "continue")
+ self.assertTrue(r["ranVlm"])
+
+ def test_soft_reject_rescued_by_vlm(self):
+ # deterministic ensemble was low-confidence (no HARD failure), VLM confirms → rescue
+ eye = {"verdict": "low-confidence", "action": "probe", "hardGateFailures": []}
+ r = gate(eye, const_sampler(high_all()), geometry_class="knife")
+ self.assertEqual(r["verdict"], "pass")
+ self.assertIn("rescued", r["reason"])
+
+ def test_low_objectness_withholds_refine_spec(self):
+ eye = {"verdict": "pass", "action": "continue", "hardGateFailures": []}
+ s = high_all(); s["objectness"] = 0.5
+ r = gate(eye, const_sampler(s), geometry_class="knife")
+ self.assertEqual(r["verdict"], "withhold")
+ self.assertEqual(r["action"], "refine-spec")
+
+ def test_low_structural_withholds_refine_code(self):
+ eye = {"verdict": "pass", "action": "continue", "hardGateFailures": []}
+ s = high_all(); s["structural"] = 0.4
+ r = gate(eye, const_sampler(s), geometry_class="knife")
+ self.assertEqual(r["verdict"], "withhold")
+ self.assertEqual(r["action"], "refine-code")
+
+ def test_high_sample_spread_is_uncertain_probe(self):
+ eye = {"verdict": "pass", "action": "continue", "hardGateFailures": []}
+ samples = [high_all(), {"objectness": 0.4, "semantic": 0.4, "structural": 0.4, "specular": 0.4, "claimedClass": "knife"}]
+ r = gate(eye, lambda i: samples[i % len(samples)], n_samples=2, geometry_class="knife")
+ self.assertEqual(r["verdict"], "uncertain")
+ self.assertEqual(r["action"], "probe")
+
+ def test_evidence_contradiction_is_uncertain(self):
+ eye = {"verdict": "pass", "action": "continue", "hardGateFailures": []}
+ r = gate(eye, const_sampler(high_all(claimed="spoon")), geometry_class="knife")
+ self.assertEqual(r["verdict"], "uncertain")
+ self.assertEqual(r["action"], "probe")
+
+ def test_no_sampler_keeps_deterministic_verdict(self):
+ eye = {"verdict": "pass", "action": "continue", "hardGateFailures": []}
+ r = gate(eye, None)
+ self.assertFalse(r["ranVlm"])
+ self.assertEqual(r["verdict"], "pass")
+
+ def test_calibrate_identity_and_monotonic(self):
+ self.assertEqual(calibrate(0.7), 0.7) # identity by default
+ # a map that pulls raw 0.9 down to 0.7 (anti-overconfidence)
+ cal = [[0.0, 0.0], [0.9, 0.7], [1.0, 0.8]]
+ self.assertAlmostEqual(calibrate(0.9, cal), 0.7, places=5)
+ self.assertLess(calibrate(0.9, cal), 0.9)
+
+ def test_evidence_consistent_unknown_geometry(self):
+ self.assertTrue(evidence_consistent("knife", None))
+ self.assertTrue(evidence_consistent("Knife", "knife"))
+ self.assertFalse(evidence_consistent("spoon", "knife"))
+
+ def test_aggregate_median(self):
+ agg = aggregate_samples([{"objectness": 0.2}, {"objectness": 0.8}, {"objectness": 0.6}])
+ self.assertAlmostEqual(agg["criteria"]["objectness"], 0.6, places=5)
+
+
+if __name__ == "__main__":
+ unittest.main(verbosity=2)
diff --git a/grimoire/build/geometry_patterns.md b/grimoire/build/geometry_patterns.md
index 5f11ed7..b6a9d94 100644
--- a/grimoire/build/geometry_patterns.md
+++ b/grimoire/build/geometry_patterns.md
@@ -118,3 +118,21 @@ A procedural object is usually failing when:
- lighting hides the form instead of explaining it
- repeated details are too evenly spaced
- close-up details add triangles but not recognizability
+
+---
+
+## Hard-won patterns — real-object reconstructions (2026-07: BMX bike + M9 bayonet)
+
+**Tube-network > single sweep for framed/tubular subjects.** A bike frame, knife-handle grip, fork, handlebar are *networks of straight members*. Model each member as a component with `attachment.localStart`/`localEnd` (+`baseRadius`) — the generator emits an oriented cylinder (quaternion Y→dir). A single closed `curve-sweep` CatmullRom-smooths into a teardrop blob. (BMX frame was a teardrop until rebuilt as a tube-network.)
+
+**Blockout must contain every silhouette-defining macro part.** A bike blockout with the frame but no wheels does not read as a bike, and coarse silhouette-IoU won't catch the omission. Put wheels/blade/major masses in at `level: macro`.
+
+**Root/container `transform.scale` MUST be `[1,1,1]`.** Children parent to the root node and inherit its transform — a `0.02` "hide" scale shrinks the whole model to a speck. Hide the container with a transparent material (`opacity:0`), never with scale.
+
+**Cloned components inherit `actionProfile.animationRole` — reset it.** Cloning a seeded root carries `animationRole:"root"`, and `root` ∈ ATTACHMENT_ROLES, so every part trips the structural attachment gate. Set a sensible per-part `animationRole` (e.g. `"static-part"`); keep roles like `handle` off non-appendage parts.
+
+**Curve the small details.** Serrations/scallops/teeth as straight boxes look wrong. Use `ellipsoid` (or slightly canted primitives, alternating ±angle) for rounded scallop teeth. Each detail with its own small cant reads as a hand-ground edge.
+
+**Grip / friction texture = geometric ridge segments.** For a knurled/wrapped/segmented grip, model raised barrel bands: a thin core cylinder + N short attachment-tube segments (radius just *proud* of the core, small groove gaps). Size them barely larger than the core — oversized tori read as a coil/spring, not a grip. Material texture alone (no geometry) reads as smooth/"thô".
+
+**`invisibleRoot`/container material is still subject to the material-pass PBR gate.** Give the container a *complete* material (roughness map, frequency bands, textureResolution) — copy a proven one — or it fails "needs usable referencePbr / roughness map" even though it never renders.
diff --git a/grimoire/build/threejs_texture_reference.md b/grimoire/build/threejs_texture_reference.md
new file mode 100644
index 0000000..36e8771
--- /dev/null
+++ b/grimoire/build/threejs_texture_reference.md
@@ -0,0 +1,48 @@
+# Three.js texture & PBR reference (notebooklm research, 2026-07-22)
+
+Doc-grounded (threejs.org MeshPhysicalMaterial / MeshStandardMaterial / Texture / CanvasTexture /
+DataTexture / manual §Textures). Drives `analyze_texture.py` (finish classification + recipe) and
+the emitted `makeProceduralTextureSet` / material presets in `generate_threejs_factory.py`.
+
+## Colour space — get this right or everything looks wrong
+- **Albedo / `map` / `emissiveMap` / `sheenColorMap` → `THREE.SRGBColorSpace`.**
+- **Data maps (`roughnessMap`, `metalnessMap`, `normalMap`, `aoMap`, `bumpMap`, `displacementMap`,
+ `thicknessMap`, `anisotropyMap`) → `THREE.NoColorSpace`** (linear data, never sRGB).
+- `CanvasTexture`: `flipY = true` (default), auto `needsUpdate` on construct.
+- `DataTexture`: `flipY = false` (default) — memory (0,0) is bottom-left. Set `needsUpdate = true`.
+- After changing `wrapS/wrapT` on an already-used texture you MUST set `needsUpdate = true`.
+- `aoMap`/`lightMap` read UV channel 1 — geometry needs a 2nd UV set, or set `texture.channel = 1`.
+- Tiling: `wrapS = wrapT = THREE.RepeatWrapping` + `repeat.set(u,v)`; set `anisotropy =
+ renderer.capabilities.getMaxAnisotropy()` so oblique angles stay sharp.
+
+## Per-finish material recipe (MeshPhysicalMaterial scalars)
+| finishClass | metalness | roughness | clearcoat | ccRoughness | transmission | ior | envMapIntensity | anisotropy | author maps |
+|---|---|---|---|---|---|---|---|---|---|
+| `gemstone` (translucent quartz/glass) | 0.0 | 0.05 | 1.0 | 0.0 | 1.0 | 1.54 | 1.0 | 0.0 | map(gradient), thicknessMap |
+| `gem-metal` (chromed doppler blade — our blend) | 0.75 | 0.14 | 0.6 | 0.06 | 0.0 | 1.5 | 1.3 | 0.0 | map(gradient+smoke), roughnessMap |
+| `painted-metal` (glossy paint) | 0.0 | 0.5 | 1.0 | 0.05 | 0.0 | 1.5 | 1.0 | 0.0 | map, roughnessMap, clearcoatRoughnessMap |
+| `worn-composite` (aged rubber/grip) | 0.0 | 0.9 | 0.0 | 0.0 | 0.0 | 1.5 | 0.5 | 0.0 | map(mottled), roughnessMap, bumpMap |
+| `brushed-steel` | 1.0 | 0.35 | 0.0 | 0.0 | 0.0 | 1.5 | 1.0 | 1.0 | anisotropyMap, roughnessMap, normalMap |
+
+> Note: pure `gemstone` (transmission 1.0) is see-through glass. A painted/anodised metallic blade
+> (CS Doppler) is opaque — use `gem-metal` (metalness + gradient map + clearcoat, no transmission).
+
+## Procedural map generation (in code)
+- **CanvasTexture** — draw to an `HTMLCanvasElement`: linear/radial gradients across palette stops
+ (gemstone/doppler), layered low-alpha blobs for smoke, per-pixel mottle noise for worn finishes,
+ thin horizontal streaks for brushed metal. `new THREE.CanvasTexture(canvas)` then set `colorSpace`.
+- **DataTexture** — push computed noise/height into a `Uint8Array`, `new THREE.DataTexture(arr,w,h,
+ THREE.RGBAFormat, THREE.UnsignedByteType)`, `colorSpace = NoColorSpace`, `needsUpdate = true`.
+- **Height → Normal (no native helper — compute it):** Sobel/neighbour-difference the height field →
+ `R = (dx*strength + 1)*0.5*255`, `G = (dy*strength + 1)*0.5*255`, `B = 255` (up +Z), A = 255.
+- **Independent channels** (skill rule, confirmed): never alias one map into another — albedo,
+ roughness, normal/height, AO are separate signals with separate frequency content.
+
+## Analysis → which finishClass?
+`analyze_texture.py` classifies a reference crop by pure-stdlib stats:
+- saturation + hue spread → chromatic gemstone vs neutral metal/grey.
+- luminance gradient across the crop → `gradient` finish (doppler) vs flat.
+- local variance / mottle → `worn-composite`.
+- directional (horizontal) high-freq streaks → `brushed-steel`.
+- specular-highlight fraction (very bright pixels) → metalness proxy.
+Output: `{finishClass, palette:[stops], mottle, gradientAxis, metalnessHint}` → material recipe.
diff --git a/grimoire/feedback/shading_realism.md b/grimoire/feedback/shading_realism.md
index 9703544..21b6dff 100644
--- a/grimoire/feedback/shading_realism.md
+++ b/grimoire/feedback/shading_realism.md
@@ -78,3 +78,38 @@ For quality-first work, capture three deliberate look-dev views before choosing
A material that only looks convincing in the reference-matched light has not passed. Fix its PBR response first, then tune the reference lighting.
If the mismatch is mostly color/texture/lighting, choose `refine-code` only when the spec already has the above details. Otherwise choose `refine-spec` first.
+
+---
+
+## Material & colour lessons — real-object reconstructions (2026-07: BMX + M9 Doppler)
+
+**Solid colour vs reference-crop albedo — pick by finish type:**
+- **Flat paint / single-colour** (bike frame): use a **solid** albedo (dominant colour) + flat normal. A raw photo crop tiles logos/gradients into stripes across long tubes. Sample the reference's *lit mid-tone* for the paint hue, then deepen/saturate (a photo mid-tone rendered under studio light reads lighter than the sample).
+- **Patterned / gemstone finish** (Doppler blade, hydro-dip, camo, quartz): use the **real reference crop** as albedo → the exact palette + smoke/pattern is literally the reference pixels ("100% same colour"). Extract the gradient **palette stops** (guard→tip) to document the look. Make it gem-glossy: high `metalness` + low `roughness` (solid-dark roughness map) + `clearcoat` + raised `envMapIntensity` → layered shine.
+
+**Sample the CORRECT region per material.** Verify the crop is actually on the part you think — a "handle" crop taken from the blade region gave a navy-blue "grey" handle. Crop, *look at the crop*, then extract.
+
+**Aged / worn / faded materials — preserve mottling, don't flatten.** A uniform dark band looks crude ("thô"). Instead: keep the crop's real luminance variation (scratches, worn patches) but remap it into a **dark aged band** (e.g. luminance→charcoal 15–45), add micro-grain, and a **roughness map that varies** (worn high-spots slightly glossier, grooves matte). Keep the cast cool-neutral for gunmetal — a warm remap drifts to tan. Darken more than you think: a mid-grey albedo reads light under a strong key light.
+
+**Render-capture must wait for textures.** `TextureLoader` is async; a screenshot fired before maps load shows `color:white` + metalness = a false "chrome" render (and a Divine-Eye false-reject). Poll `material.map.image.complete` before capturing. The render host must serve the reference PBR maps (copy to `public/`) or they 404 → white.
+
+**Soft shadows for a studio look:** `key.shadow.radius`/`blurSamples` + a tight shadow-camera frustum + a low `ShadowMaterial.opacity` (~0.16) beat a hard dark blob.
+
+## Candy/anodized colour washes to blue under a bright env — and prose can fight the reference
+- **Symptom:** a doppler/candy blade whose albedo genuinely contains violet (verified by sampling the
+ PNG: mid-body RGB ~ (150,50,170)) still renders **blue** in a white-studio scene.
+- **Cause 1 — metalness steals the hue.** At `metalness ≈ 0.7–1.0` most of the surface colour is the
+ *environment reflection* (specular F0), not the albedo diffuse; a bright/cool white env reflects
+ blue-white and the albedo hue is a minority contributor. A colored PVD/candy/anodized coat is
+ visually a **dielectric-led** surface: render it `metalness ≈ 0.35` + `clearcoat ≈ 0.6`
+ (roughness ~0.18) so the albedo colour leads and the coat supplies gloss. Also trim
+ `envMapIntensity` (~0.7) and clearcoat so the white env stops desaturating the hue.
+- **Cause 2 — a blue-leaning purple reads blue when darkened.** A violet with `B > R`
+ (e.g. 158,52,206) collapses toward blue under any tone-map/shadow darkening because B dominates.
+ For a purple that *survives* shading, make it **magenta-leaning, `R ≳ B`** (e.g. 175,48,150).
+- **Cause 3 (the real one here) — prose contradicted the reference.** A written brief said
+ "cyan guard → PURPLE middle (45%) → indigo tip"; the actual reference image was
+ **violet at the ricasso → SAPPHIRE-BLUE body (dominant) → navy-black tip**. img2threejs is
+ reconstruction-*from-the-image*: when a colour brief disagrees with the reference photo, **sample
+ the reference and match the photo**, then surface the discrepancy to the user — do not chase the
+ prose (it cost 4 wasted render iterations pushing purple into a region the photo shows as blue).
diff --git a/grimoire/intake/surface_topology.md b/grimoire/intake/surface_topology.md
new file mode 100644
index 0000000..9a26de1
--- /dev/null
+++ b/grimoire/intake/surface_topology.md
@@ -0,0 +1,63 @@
+# Surface Topology Classification
+
+Use this reference before assigning a `primitive` to any component. Classifying the *kind* of
+surface first prevents the most common geometry-mismatch failure: picking a primitive that is
+structurally wrong for what the silhouette actually is (see Plan 1.3 Workstream A/F — a continuous
+organic bulge modeled as a box-stack, or a blade modeled as a box because `extrude` was never
+attempted).
+
+## The six classes
+
+- **`continuous-sculpt`** — a single, smoothly-varying volume with no internal seams or panel
+ breaks: a horn, a smooth organic bulge, a worn stone, a revolved vessel. Never `box`/`cylinder`/
+ `cone` — use `lathe` (rotationally symmetric), `extrude` (profile with depth), or `curve-sweep`
+ (follows a 3D path).
+- **`assembled-solid`** — a discrete rigid part with flat or simply-curved faces, genuinely built
+ from a primitive: a crate, a cylindrical canister, a boxy chassis panel. `box`/`cylinder`/`cone`/
+ `capsule`/`torus` are all fine here.
+- **`conforming-shell`** — a thin surface that follows the form of something underneath it rather
+ than having independent volume: a fuselage skin panel, a thin curved cowling, a fitted cloth
+ layer over a body. Usually needs a `plane-card` bent/shaped to the underlying form, or a shallow
+ `extrude`.
+- **`surface-relief`** — detail that changes the surface but not the overall silhouette-defining
+ volume: ridges, panel lines, rivets, embossed logos. Represent via geometry only when the relief
+ is large enough to affect the silhouette at the intended viewing distance (see
+ `grimoire/feedback/shading_realism.md`'s "geometric relief" rule) — otherwise this is a material
+ concern (normal/bump), not a `topologyClass` concern, and the component doesn't need its own
+ entry.
+- **`fiber-strand`** — a thin, elongated, often-repeated strand-like form: cable, rope, hair clump,
+ root, vine, wire. Never `box`/`plane-card` — use `tube` (follows a path) or `instanced-cluster`
+ (many repeated strands).
+- **`material-only`** — no independent geometric footprint of its own; purely a material/decal
+ layer riding on a parent's surface (a printed logo panel, a flat sticker). Any primitive is
+ acceptable here since the "geometry" is just a thin carrier for the material.
+
+## Decision tree
+
+1. Does this component have its own volume, or does it just carry a material/decal on a parent's
+ surface? → if the latter, `material-only`, stop here.
+2. Is it long, thin, and either follows a path or repeats many times? → `fiber-strand`.
+3. Is the *silhouette itself* affected by fine detail (ridges/rivets/panel lines) with no other
+ independent volume? → `surface-relief`.
+4. Does it have hard, distinct faces you could point to and count ("this cube, that cylinder")? →
+ `assembled-solid`.
+5. Is it a thin skin that follows another form's curvature, with no volume of its own? →
+ `conforming-shell`.
+6. Otherwise — one continuous, smoothly-varying mass — `continuous-sculpt`.
+
+## Worked examples
+
+| Object | Component | Class | Why |
+| --- | --- | --- | --- |
+| Gerber knife | blade | `continuous-sculpt` | Smooth tapering wedge to a point — `extrude` with a `lineTo()`-only tip profile, not a box. |
+| Gerber knife | paracord wrap | `fiber-strand` | Repeated wound cord — `instanced-cluster` or a `tube` following a helical path. |
+| Doraemon house | wall panel | `assembled-solid` | Flat rigid panel, genuinely box-shaped. |
+| Sony earbuds | case shell | `conforming-shell` | Thin curved shell conforming to the earbud cavities beneath it — not solid all the way through. |
+| Character | shirt chest logo | `material-only` | Flat decal riding on the torso's surface; carries no geometry of its own. |
+| Warhauler | antenna wire | `fiber-strand` | Thin cable — `tube`, never `box`. |
+
+## Common mistake
+
+Classifying by "how big is it" instead of "what kind of surface is it." A large smooth stone and
+a small smooth pebble are both `continuous-sculpt`; a large flat wall panel and a small flat plate
+are both `assembled-solid`. Size doesn't change the class — surface behavior does.
diff --git a/grimoire/review/self_correction.md b/grimoire/review/self_correction.md
index e2f19d1..c3f9e2d 100644
--- a/grimoire/review/self_correction.md
+++ b/grimoire/review/self_correction.md
@@ -66,3 +66,22 @@ Use a practical 0-1 scale:
- `0.95`: near-reference, usually requires multiple views or manual art
Do not claim `0.9+` from a single ambiguous image unless the object is simple and symmetrical.
+
+---
+
+## Divine Eye caveat — photo-vs-procedural reconstruction (must read)
+
+When the reference is a **photograph** and the render is a **procedural reconstruction**, the pixel-aligned signals (`ssim`, `edgeOverlap`) and the silhouette-IoU hard gate are dominated by **framing + background + scale + lighting** differences, NOT fidelity. Confirmed on two objects: a faithful BMX scored `reject/0.53`, a clear M9 bayonet scored `reject/IoU 0.165` (white-bg photo vs dark render).
+
+**Do not chase the Eye's global score in this mode** — optimising toward it distorts the model trying to pixel-match a photo (impossible) and makes it worse. Instead:
+- Judge each pass against its **own goal** with agent vision (silhouette reads? part present? palette on-tone?).
+- Trust the **palette ΔE / phash / part-presence**, and IoU only **after** scale+translation alignment.
+- Treat `ssim`/`edgeOverlap` vs a photo as advisory, never a hard fail.
+
+The proper fix is a Divine-Eye **reconstruction mode** (reference==photo ⇒ drop pixel-aligned signals, align-then-IoU, palette+objectness) — this is exactly what the deferred **OSIM** objectness signal targets (feature-map similarity is invariant to lighting/background). See `docs/PLAN_1.3_FINAL.md` review log + ws-memories atom `divine-eye-photo-vs-procedural-miscalibration`.
+
+**Update (2026-07-22): the reconstruction-mode rescue now exists.** `divine_eye.py` computes a stdlib
+`objectness` signal (`objectness.py`, OSIM-lite — bg/pose/scale/brightness-invariant HOG cosine) and,
+when a photo-vs-procedural render fails *only* the IoU hard gate but objectness says "same object"
+(≥0.48), it downgrades the confident reject to `probe` and sets `reconstructionModeSuspected:true`. So the
+Eye no longer hard-rejects a faithful reconstruction on framing alone — but still never auto-passes it.