Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.
Python 3dai-agentsclaude-codecomputer-graphicsgenerativeimage-to-3dprocedural-generationthreejstypescriptwebgl
chore: merge beta release infra back to main (#69)
TamL.b604139f51d6
diff --git a/.github/workflows/beta-release.yml b/.github/workflows/beta-release.ymlnew file mode 100644index 0000000..4569ddf--- /dev/null+++ b/.github/workflows/beta-release.yml@@ -0,0 +1,58 @@+name: Beta Tag++on:+ push:+ branches: [beta]++permissions:+ contents: write++concurrency:+ group: beta-release+ cancel-in-progress: false++jobs:+ tag:+ if: "!startsWith(github.event.head_commit.message, 'chore(beta): v')"+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0+ - name: Update beta skill version and tag+ run: |+ set -euo pipefail++ current_version="$(sed -nE 's/^version: ([0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?)$/\1/p' SKILL.md)"+ if [ -z "$current_version" ]; then+ echo "SKILL.md must contain one supported version field."+ exit 1+ fi++ if [[ "$current_version" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)-beta\.([0-9]+)$ ]]; then+ major="${BASH_REMATCH[1]}"+ minor="${BASH_REMATCH[2]}"+ patch="${BASH_REMATCH[3]}"+ beta_sequence="${BASH_REMATCH[4]}"+ next_version="$major.$minor.$patch-beta.$((beta_sequence + 1))"+ elif [[ "$current_version" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then+ major="${BASH_REMATCH[1]}"+ minor="${BASH_REMATCH[2]}"+ next_version="$major.$((minor + 1)).0-beta.1"+ else+ echo "SKILL.md must contain a stable or beta semantic version."+ exit 1+ fi++ if git rev-parse "v$next_version" >/dev/null 2>&1; then+ echo "Tag v$next_version already exists."+ exit 1+ fi++ sed -i -E "s/^version: [0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$/version: $next_version/" SKILL.md+ git config user.name "github-actions[bot]"+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"+ git add SKILL.md+ git commit -m "chore(beta): v$next_version"+ git tag -a "v$next_version" -m "v$next_version"+ git push origin HEAD:beta --follow-tagsdiff --git a/.gitignore b/.gitignoreindex a9a6f6f..2638f9f 100644--- a/.gitignore+++ b/.gitignore@@ -19,6 +19,7 @@ docs/PLAN_*.md.omc/.omo/.opencode/+.img2threejs/# Extracted Valve CS2 textures -- IP belongs to Valve, never committed.cs2_textures/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 781e7c7..25758eb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,25 @@ 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.4.4-beta-2]++### Added+- Add a repository-local mandatory workflow checklist, resume gate, and evidence-backed step+ tracking under `.img2threejs/state.json`.+- Add per-pass and total correction ceilings derived from `reviewHistory`; `forge/next.py` now+ hard-stops when either limit is reached.+- Add an executable CS2 review CLI and profile-specific CS2/character checklist gates.+- Add explicit suitability, projection-route, and material-evidence decisions to every profile.++### Changed+- Keep progressive-disclosure references while making CS2 intake, deterministic review gates,+ self-correction, multi-angle review, part coverage, and action-ready validation explicit router+ requirements.+- Order each pass as build, render, Tier 1, multi-angle, deterministic pass check, profile review,+ AI review, and sync.+- Make regeneration action-aware so `refine-code` cannot overwrite the artifact it must repair,+ and reject spec paths that disagree with local state.+## [1.4.3] — 2026-07-30The accepted current release line is `1.4.x`. GitHub Releases are the canonical changelog fromdiff --git a/SKILL.md b/SKILL.mdindex 16042c8..9f6df47 100644--- a/SKILL.md+++ b/SKILL.md@@ -2,7 +2,8 @@name: img2threejsdescription: Turn an object or character reference image into a quality-gated, animation-ready procedural Three.js model built in code. Use for image-to-3D reconstruction, detail-accurate object rebuilds, stylized/likeness-maximized human characters, sculpt specs, and staged code generation.license: Apache-2.0-version: 1.4.3++version: 1.4.4-beta.3---# img2threejs — Image to procedural Three.js@@ -24,7 +25,9 @@ action-ready props, game objects, botanical/mechanical parts, and stylized recon## Core PromiseSculpt from a photo, in order — never one-shot a mesh:-1. **Run `python3 forge/next.py <spec>` first.** It reports the current unlocked pass, exact next command, and unmet acceptance criteria.+1. **Use local state first.** Initialize it once, then run+ `python3 forge/next.py --state .img2threejs/state.json [<spec>]` at every start/resume and before+ every correction iteration. Obey a hard stop; never continue from memory.2. **Validate** the image is a suitable 3D target (`grimoire/intake/validation_rubric.md`).3. **Assess** object class + complexity, then write a `qualityContract` before any code.3. **Spec** it: component hierarchy, materials, lighting, pivots, sockets, action anchors.@@ -34,19 +37,11 @@ Sculpt from a photo, in order — never one-shot a mesh:State explicitly when output is approximate/stylized/low-poly. A single image cannot revealhidden sides or guarantee exact geometry — say so instead of faking confidence.-## Transparency and Process Debugging (Critical — from Bowie Knife reconstruction)--**The problem:** When the user cannot tell what was done or where something went wrong, they cannot debug the process. Over-claiming (reporting success when features still don't match) destroys trust and makes iterative improvement impossible.--**Rule:** Be transparent + don't over-claim. State exactly what changed each pass, with evidence, and name what still doesn't match:-- After each pass, explicitly list what changed: "Updated guard shape to extend left edge from -0.56 to -0.48 for handle overlap"-- Provide evidence: reference the specific values, coordinates, or parameters that changed-- Name what still doesn't match: "Handle silhouette traced but still flat plane (no Z palm-swell), procedural crosshatch not reference's exact dot-grid knurl"-- Explain why a change was made: "Extended guard left edge because handle ends at X=-0.42 and guard ended at X=-0.20, causing visual gap"-- Never claim a feature is "done" when it's only "improved" — use precise language-- When a gate passes but visual inspection shows issues, explain the limitation: "2D gate passed (fidelity 0.83) but three-quarter render shows blade reads as toy (no grind wedge) — 2D gates are blind to 3D realism"+## Transparency and Process Debugging-**The user needs to be able to debug the process, not just the output.** If something is wrong, they should be able to trace which decision led to the error and correct it. Opaque processes force restarts; transparent processes enable refinement.+Report what changed each pass with evidence (exact values/coordinates), name what still doesn't+match, and never claim "done" when only "improved". A passing gate is not proof of 3D realism.+Full rule + examples: `grimoire/review/self_correction.md`.## Required Inputs@@ -57,6 +52,30 @@ hidden sides or guarantee exact geometry — say so instead of faking confidencean explicit request for the user/vision provider to supply one; heuristic detection alone is notenough to select a geometry adapter+## Mandatory Local State Gate++Conversation context is disposable; `.img2threejs/state.json` is the local checklist authority.+Initialize it once per reconstruction:++`python3 forge/state.py init --state .img2threejs/state.json --reference <img> --profile <generic|cs2|character>`++At every fresh start, resume, or correction loop, run+`python3 forge/next.py --state .img2threejs/state.json [object-sculpt-spec.json]` before touching+code. It prints the current step, pass, incomplete mandatory steps, exact next command, and+`loop/max`. Exit code 3 or `status=stopped` is a hard stop: report the reason and request input.+Never bypass it by reconstructing progress from chat history.++After evidence exists, record it with+`python3 forge/state.py mark <step-id> --state .img2threejs/state.json --evidence <path>`.+Mark a non-applicable step `skipped` only with `--reason`; silent omission is forbidden. Loop counts+are derived from `reviewHistory` actions `refine-spec`/`refine-code`, not agent memory. Defaults are+3 corrections per pass and 6 total.++Profiles add mandatory gates rather than changing the core order: `cs2` requires classification,+manifest, and a machine-readable CS2 review before AI review; `character` requires the character+contracts and landmark evidence. Every profile records suitability, projection applicability, and+material-evidence applicability; conditional steps require evidence or an explicit skip reason.+## The Loop (scripts do enforcement; agent vision does judgment)Run scripts from the skill root (`forge/...`). Pure Python 3.10+ stdlib, no pip installs.@@ -68,45 +87,28 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that iwhat the single view hides. Observation before inference; controlled 3D vocabulary; 3Dobject-space not 2D image-space. This is generic for any subject and feeds every field below.Then probe local images: `forge/stage1_intake/probe_image.py <image>` (metadata only, not a visual check).-1a. **Local Spec Search** — after image analysis and before writing or refining a spec, local- evidence is a pipeline stage, not an optional memory lookup, whenever the request needs- domain-specific anatomy, PBR, wear, geometry, runtime, or physics specifications. The pre-spec- command automatically runs BM25, chooses `cs2` for CS2 targets and `core_3d` otherwise, and- writes a `localSpecSearch` evidence bundle into the assessment:- `python3 forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --out assessment.json`.- Add observed terms with repeatable `--spec-query "<term>"`; use `--collection <collection>` only- when the automatic collection choice is insufficient. `new_sculpt_spec.py --assessment` carries- that bundle into the final spec, including snippets, `source_refs`, and `evidence_refs`.- For extra focused retrieval, the direct CLI remains available:- `python3 forge/stage1_intake/search_specs.py "<query>" --collection <collection> --limit 3 --snippet-chars 250 --json`.- For CS2, include English/Vietnamese variants, for example `--spec-query "safety ring vòng ngón"`- or `search_specs.py "roughness độ nhám" --collection cs2`. Expand queries with object names,- component names, material/finish terms, behavior terms, and bilingual aliases; retry focused- alternatives when the first result is incomplete. Build the spec from returned evidence and do- not invent domain specs when local evidence exists. Search caches are local/generated only;- preserve JSONL records and source provenance rather than replacing them with cache output.+1a. **Local Spec Search** — after image analysis, before writing or refining a spec, pull local+ domain evidence (anatomy/PBR/wear/geometry/runtime/physics) rather than inventing it:+ `python3 forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --out assessment.json`+ (auto-runs BM25, auto-picks `cs2`/`core_3d` collection, writes a `localSpecSearch` bundle that+ `new_sculpt_spec.py --assessment` carries into the spec). Full query-expansion recipe+ (bilingual terms, focused `search_specs.py` retrieval, cache rules):+ `grimoire/intake/local_spec_search.md`. MUST read it before retrying an incomplete or+ domain-specific query.1b. **CS2 intake manifest** — for a CS2 request, create and validate `cs2-intake.json` before- pre-spec authoring. Run admission and probing for every source view, record the heuristic signal- as non-authoritative evidence, attach the classification record, resolve the supported family,- and choose `route` independently from `exactnessTier`. Missing classification, insufficient- coverage, or a contradictory high-confidence class is `request-input`; unsupported families do- not continue into spec generation.+ pre-spec authoring (admission, heuristic signal, classification, family/route resolution).+ MUST read `grimoire/intake/cs2_intake_contract.md` completely before creating the manifest or+ running pre-spec assessment.2. **Pre-Spec Assessment Gate** — classify + score complexity + write the quality contract:`forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --complexity <simple|moderate|complex|ultra-complex> --out assessment.json`. Rules: `grimoire/intake/quality_contract.md`.Set `objectClass.primaryDomain` (`object` | `character` | `hybrid`) and fill the seeded`detailInventory` (its `targetMinDetails` scales with complexity). **Supported CS2 knifeskins**: always pass `--cs2`, which defaults the complexity tier to `ultra-complex`- (`targetMinDetails` 16) — the finish/wear/hardware is the item, so CS2 is held to the top- fidelity bar; `targetMinDetails` never drops below the 9 floor even if downgraded by hand.- **Author procedural GEOMETRY (blade/guard/grip profiles) but make the FINISH a de-lit- reference-crop PROJECTION, not a procedural finish material** — projecting the photo's own- pixels is what reaches reference fidelity for patterned skins (Doppler/Gamma/Marble/Fade), and- is what the v1.3 baseline demos do; a procedural finish for a patterned skin reads visibly wrong- against the reference. Take the projection path in step 2c (it generalizes from characters to- any reference-matched surface). Procedural finish is the fallback ONLY when live view-dependent- response matters more than matching this one reference. Finish routes + rulebook:- `grimoire/build/cs2_finishes.md`; optional exact-texture acquisition:- `grimoire/intake/cs2_texture_acquisition.md`.+ (`targetMinDetails` 16, floor 9) — the finish/wear/hardware is the item, so CS2 is held to the+ top fidelity bar. Author procedural GEOMETRY but route the FINISH through the projection path in+ step 2c — a procedural finish for a patterned skin (Doppler/Gamma/Marble/Fade) reads visibly+ wrong against the reference. Finish routes + rulebook: `grimoire/build/cs2_finishes.md`;+ optional exact-texture acquisition: `grimoire/intake/cs2_texture_acquisition.md`.2b. **Detail inventory** (do not skip for detailed subjects) — scan zones and enumerate everyidentity-defining small detail (gloss, bevel, fasteners, linework, contours, stains):`forge/stage1_intake/build_detail_inventory.py <image> --mode grid-3x3 --out-dir <dir> --out di.json`.@@ -153,20 +155,36 @@ Full flags: `grimoire/scripts.md`. Never let a script *score* visuals — that ilocal overrides, no micro groups is NOT implementation-ready even if JSON validates).6. **Locked build passes** — only touch the currently unlocked pass:`forge/stage3_build/orchestrate_passes.py status object-sculpt-spec.json`- `forge/stage3_build/orchestrate_passes.py check object-sculpt-spec.json --pass-id <pass>``forge/stage3_build/generate_threejs_factory.py object-sculpt-spec.json --out src/createObjectModel.ts`(generator is pass-gated: a future `--pass-id` fails until prior passes are reviewed `continue`).+ The local state adds `--force` only for a new pass or `refine-spec`; `refine-code` edits the+ current artifact without regenerating it. Before overwriting, carry valid hand refinement back+ into the spec; generated code must not be the only copy of reconstruction decisions.7. Render the current pass in a browser/preview, capture a screenshot at a review viewpoint.-8. Package one side-by-side sheet, then inspect it with agent vision:+8. **Run deterministic gates before AI vision.** MUST read+ `grimoire/review/gates_reference.md` and `grimoire/review/self_correction.md` completely. Run+ `forge/stage4_review/diagnose_render.py` and record the passing Tier 1 result with+ `--spec object-sculpt-spec.json --pass-id <pass> --in-place`; for non-planar forms also run+ `forge/stage4_review/diagnose_render_multi_angle.py` with the fixed view and at least two+ meaningful orbit views. Then run+ `forge/stage3_build/orchestrate_passes.py check object-sculpt-spec.json --pass-id <pass>`.+9. Package one side-by-side sheet, then inspect it with agent vision:`forge/stage4_review/make_comparison_sheet.py --reference <img> --render <shot> --out cmp.png --json`.-9. Record the review (overall + per-layer + per-feature scores + decision):+10. Record the review (overall + per-layer + per-feature scores + decision):`forge/stage4_review/append_review.py object-sculpt-spec.json --pass-id <pass> --fidelity <0-1> --action <continue|refine-spec|refine-code|request-input|stop> --summary "..." --render-screenshot <shot> --comparison-image cmp.png --ai-vision-score <0-1> --layer-scores-json '{...}' --feature-reviews-json <f.json> --in-place`.For the CS2 knife path, also attach the versioned report with`--cs2-review-json cs2-review.json --review-scene-json forge/tests/fixtures/knife_review_scene.json`.+ Produce that report first with+ `forge/stage4_review/cs2_review.py --manifest cs2-intake.json --metrics cs2-review-inputs.json --scene forge/tests/fixtures/knife_review_scene.json --out cs2-review.json`.A failed family, painted-region, projection-coverage, critical-detail, or orbit gate blocks`continue` even when the global score passes. See `docs/cs2/review-gates.md`.-10. Sync pipeline state after manual review edits:- `forge/stage3_build/orchestrate_passes.py sync object-sculpt-spec.json --in-place`.+11. Sync pipeline state after manual review edits, record checklist evidence, then re-run the local+ state gate before another correction or pass:+ `forge/stage3_build/orchestrate_passes.py sync object-sculpt-spec.json --in-place`+ `python3 forge/next.py --state .img2threejs/state.json object-sculpt-spec.json`.+12. Before declaring completion, run+ `forge/stage4_review/check_part_coverage.py --spec object-sculpt-spec.json --manifest parts.json`+ and verify the action-ready hierarchy. Mark `part-coverage` and `action-ready` only with evidence.## CS2 image-matched rule@@ -179,133 +197,39 @@ The initial CS2 family boundary is **knife only**. Pistol, rifle, SMG, sniper, hunknown knife subtypes must stop with `unsupported-family` or `unsupported-subtype`; they must notreceive the knife component tree as a generic fallback.-### Layer contract--Pass these records between layers. Do not copy an informal vision description into the next stage:--| Layer | Owns | Must emit | Must not decide alone |-| --- | --- | --- | --- |-| Intake | view validity and technical evidence | role, path/hash, resolution, coverage, duplicate status, admission verdict | item identity from aspect ratio or filename |-| Classification | semantic identity | family, subtype, confidence, evidence refs, provider/version, timeout state | geometry or finish parameters |-| Identity | skin/name/paint metadata | precedence, resolved values, ambiguity candidates, provenance | guessed paint index, float, or seed |-| Surface evidence | pixels and texture sources | de-lit reference, PBR channels, map provenance, colour space, UV orientation, confidence | albedo reused as roughness/normal/AO |-| Geometry adapter | family-specific form | component tree, topology, dimensions, edge/spine, hardware relationships, painted regions | hidden geometry without confidence notes |-| Spec/route | evidence-backed implementation choice | route, exactness tier, assumptions, feature targets, camera contract | exact-texture claim without exact evidence |-| Build/review | rendered observables | fixed view, two non-degenerate orbit views, per-region results, failed gates, next action | overriding a failed critical feature with a global score |--The canonical hand-off is `cs2-intake.json` (`schemaVersion: 1`). Its state is one of-`proceed`, `request-input`, `fallback`, `rejected`, `unsupported-family`, or-`unsupported-subtype`. Write it atomically and preserve unknown provider fields under-`extensions`; a fallback must never erase prior evidence.--### CS2 intake order--1. Admit and technically probe every view. Reject undecodable, empty, tiny, fragmented, or- duplicate references before classification.-2. Record the heuristic CS2 signal only as a routing hint. `detect_cs2.py` is never authoritative- identity evidence.-3. Require a classification record before selecting a family adapter. If classification is absent,- timed out, or contradicts a high-confidence objectness result, return `request-input`.-4. Resolve identity in this order: explicit user metadata, uniquely resolved metadata, then the- authoritative classification record. Preserve ambiguity rather than guessing.-5. Select route and exactness independently:- - `reference-projection`: default for matching a specific patterned image;- - `authored-texture`: only when independent texture maps are supplied or legally acquired;- - `procedural-finish`: fallback when projection evidence is unavailable or live response is the- stated priority.- Exactness is `image-only`, `metadata-assisted`, or `exact-texture`; changing route must not- silently upgrade or downgrade the evidence tier.-6. Select the knife adapter only after family/subtype validation. Record painted regions, unpainted- substrate, visible hardware, hidden-region confidence, and every approximation in the spec.-7. For projection, solve the camera and de-light the source first. Projected pixels provide colour- evidence, not automatic geometry truth; geometry still comes from the adapter and silhouette- review.--### Surface and review rule--For a specific CS2 reference, preserve the reference's own colour/pattern pixels whenever legal and-technically possible. Procedural Doppler/Fade/Gamma/Marble patterns are not equivalent to the input-image and may only be used with an explicit `procedural-finish` route and approximation warning.-Keep albedo, roughness, metalness, normal/height, AO, mask, and wear as independent channels. Record-channel source, colour space, UV orientation, dimensions, packed-channel decoding, and missing-channel-derivation. A low-confidence PBR inference is a refine-input signal, not proof of exact material.--Single-view reconstruction may proceed only when visible identity features are sufficiently covered;-hidden blade sides, underside, and back hardware must carry inference confidence and may trigger-`request-input`. Review the fixed camera plus two meaningful orbit views. Report what changed, which-evidence caused it, what still differs, and choose exactly one next action:-`continue`, `refine-spec`, `refine-code`, `request-input`, or `stop`.+For every CS2 reconstruction, MUST read the full layer contract, intake order, and surface/review+rule in `grimoire/intake/cs2_intake_contract.md` before intake state can advance.## Gates (do not skip)-- **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.-- **CS2 knife review contract**: `forge/stage4_review/cs2_review.py` consumes the manifest and- versioned scene fixture, then blocks wrong family identity, missing projection coverage,- painted-region mismatch, critical identity-detail failure, finish/material response failure,- and degenerate orbit form. It records exactness tier, hidden-region confidence, per-region- confidence, approximation notes, camera, environment hash, exposure, tone mapping, resolution,- background, and renderer version.-- **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.- Details + per-layer scorecard: `grimoire/feedback/render_capture.md`.-- **Action-ready**: build a runtime hierarchy (pivots, sockets, colliders, destruction groups),- never an inert lump; expose `root.userData.sculptRuntime`. `grimoire/readiness/action_rigging.md`.-- **Assembly gate (structure, not pixels) — every model ships explodable AND clickable**: this is- a build requirement, not a per-project extra. Name every mesh; flag surface relief- `userData.explodeWithParent` so it rides its shell; let a named group of *anonymous* meshes be one- part while a named group of *named* parts stays a container. Explode and part-picking must share- one definition of "a part" — if they disagree, both are wrong. Separate parts by SCALING the- layout about the model centre, never by pushing every part the same distance (that translates the- arrangement without opening any gap). Then run- `forge/stage4_review/check_part_coverage.py --spec <spec> --manifest <parts.json>`: it FAILS on a- specified component that was never built and on two components fused onto one mesh; it warns on- inventoried details that never reached the spec and on meshes belonging to no named part. This is- the only gate that scores STRUCTURE — every other one scores pixels, and a single fused mesh- wearing a projected photo passes all of those. Its limit is honest and must be stated when- reporting: it proves you built what you specified, never that you specified enough.- Full contract + the two rules it took a wrong pass to learn: `grimoire/build/geometry_patterns.md`.-- **Attachment**: child appendages (branches/limbs/handles/tubes) need `attachment.parentSocket`,- `localStart`, `localEnd`, `contactType`, `embedDepth`/`overlap`, `gapTolerance` — no mid-air parts.- `grimoire/readiness/joint_attachment.md`.-- **Material/lighting**: `grimoire/feedback/shading_realism.md` — independent PBR channels- (never alias albedo into roughness/normal/AO), macro/meso/micro frequency bands, real lights.-- **Detail inventory**: for `moderate`+ subjects strict-quality blocks code gen until the- `detailInventory` reaches `targetMinDetails` and every detail maps to a real component/material- entry (gloss needs low-roughness/clearcoat; fasteners need instancing/micro parts).-- **Character track**: when `primaryDomain` is `character`/`hybrid` (or `--character`), the spec- author auto-builds a stylized humanoid template (head/neck/torso/arms + hair, glasses,- headphones, face features), flattened to world space under a hidden root, with per-part- character materials and character build passes (`proportion-lock`, `feature-placement`).- strict-quality requires a filled `anatomy` block (head-units, proportions, face landmarks) and- character feature targets. Suitability routing for humans: `grimoire/intake/validation_rubric.md`- (stylized vs maximum-likeness). Stylized bust, not a face-copy; refine positions per reference.+Before any visual review or `continue` decision, MUST read the full gate-by-gate contract in+`grimoire/review/gates_reference.md` (Divine Eye, VLM rescue, multi-angle, CS2 review, bounded+correction, screenshot feedback, assembly, attachment, material, detail inventory, character+track). In short:++- Validate references first (`grimoire/intake/validation_rubric.md`, `check_reference_admission.py`).+- `divine_eye.py` is deterministic-first; the VLM (`vlm_gate.py`) is a gated last layer, never+ consulted on a hard-gate failure.+- A non-planar form must hold from ≥2 angles (`diagnose_render_multi_angle.py`).+- CS2 knife builds also run `cs2_review.py` against the versioned scene fixture.+- Local state enforces 3 corrections per pass and 6 total by default; reaching either limit is a+ hard stop. `correction_loop.py` may stop earlier on repeated defects, oscillation, or plateau.+- `continue` requires a render + comparison sheet + AI-vision score ≥ threshold, every critical+ feature ≥ its own threshold (`grimoire/feedback/render_capture.md`).+- Every model ships explodable AND clickable — a structure gate, not pixels+ (`check_part_coverage.py`, `grimoire/build/geometry_patterns.md`).+- Action-ready, attachment, material/lighting, detail inventory, and character-track requirements:+ `grimoire/readiness/action_rigging.md`, `grimoire/readiness/joint_attachment.md`,+ `grimoire/feedback/shading_realism.md`, `grimoire/intake/quality_contract.md`,+ `grimoire/intake/validation_rubric.md`.## Self-CorrectionAfter every pass, decide exactly one: `continue | refine-spec | refine-code | request-input | stop`.`refine-spec` fixes a wrong/missing/shallow spec (re-validate, don't patch code around it);-`refine-code` fixes geometry/material/lighting that doesn't match a sound spec. Full root-cause-guide + fidelity scale: `grimoire/review/self_correction.md`.+`refine-code` fixes geometry/material/lighting that doesn't match a sound spec. Before making the+decision, MUST read the root-cause guide + fidelity scale in `grimoire/review/self_correction.md`,+record the decision, and re-run the local state gate.## Implementation Rules (brief)diff --git a/forge/_shared/workflow_state.py b/forge/_shared/workflow_state.pynew file mode 100644index 0000000..35ead94--- /dev/null+++ b/forge/_shared/workflow_state.py@@ -0,0 +1,404 @@+from __future__ import annotations++import json+import os+import shlex+import tempfile+from copy import deepcopy+from pathlib import Path+from typing import Any, Final+++SCHEMA_VERSION: Final = 1+STEP_STATUSES: Final = {"pending", "done", "skipped"}+REFINE_ACTIONS: Final = {"refine-spec", "refine-code"}+++SETUP_STEPS: Final = (+ ("image-analysis", "Read grimoire/intake/image_analysis.md and analyze {reference}"),+ (+ "reference-suitability",+ "Read grimoire/intake/validation_rubric.md and record a pass, conditional, or reject verdict for {reference}",+ ),+ ("reference-admission", "python3 forge/stage1_intake/check_reference_admission.py {reference}"),+ ("local-spec-search", "Run the local evidence search before authoring the assessment"),+ ("pre-spec-assessment", "python3 forge/stage2_spec/new_pre_spec_assessment.py \"<name>\" --image {reference} --out assessment.json"),+ ("detail-inventory", "python3 forge/stage1_intake/build_detail_inventory.py {reference} --mode grid-3x3 --out-dir detail-inventory --out di.json"),+ (+ "projection-route",+ "Record whether projection is required; if required run solve_camera_pose.py, delight_albedo.py, and bake_projected_texture.py, otherwise skip with a reason",+ ),+ ("spec-authoring", "python3 forge/stage2_spec/new_sculpt_spec.py \"<name>\" --image {reference} --assessment assessment.json --out object-sculpt-spec.json"),+ (+ "material-evidence",+ "When material fidelity matters, run analyze_texture.py and extract_pbr_evidence.py per verified crop; otherwise skip with a reason",+ ),+ ("strict-validation", "python3 forge/stage2_spec/validate_sculpt_spec.py {spec} --strict-quality"),+)++CHARACTER_STEPS: Final = (+ (+ "character-contract-read",+ "Read grimoire/character/reconstruction.md and grimoire/character/likeness_maximization.md completely",+ ),+ (+ "character-landmarks",+ "python3 forge/stage1_intake/extract_landmarks.py {reference} --out anatomy.json --overlay landmarks.png",+ ),+)++CS2_STEPS: Final = (+ ("cs2-contract-read", "Read grimoire/intake/cs2_intake_contract.md completely"),+ ("cs2-authoritative-classification", "Obtain an authoritative CS2 family/subtype classification record"),+ ("cs2-manifest", "python3 forge/stage1_intake/cs2_manifest.py {reference} --classification classification.json --out cs2-intake.json"),+)++PASS_STEPS: Final = (+ ("build-current-pass", "python3 forge/stage3_build/generate_threejs_factory.py {spec} --out src/createObjectModel.ts --pass-id {pass_id}"),+ ("render-capture", "Render {pass_id} and capture the fixed review view plus meaningful orbit views"),+ ("review-contract-read", "Read grimoire/review/gates_reference.md and grimoire/review/self_correction.md completely"),+ ("tier1-diagnostics", "python3 forge/stage4_review/diagnose_render.py --reference {reference} --render <shot> --spec {spec} --pass-id {pass_id} --in-place"),+ ("multi-angle-review", "python3 forge/stage4_review/diagnose_render_multi_angle.py --reference <fixed-shot> --orbit <orbit-shot> --orbit <orbit-shot>"),+ ("pass-gate-check", "python3 forge/stage3_build/orchestrate_passes.py check {spec} --pass-id {pass_id}"),+ ("ai-review-recorded", "Create the comparison sheet, inspect it with agent vision, and append exactly one review action"),+ ("pipeline-sync", "python3 forge/stage3_build/orchestrate_passes.py sync {spec} --in-place"),+)++CS2_PASS_STEPS: Final = (+ (+ "cs2-review",+ "python3 forge/stage4_review/cs2_review.py --manifest cs2-intake.json --metrics cs2-review-inputs.json --scene forge/tests/fixtures/knife_review_scene.json --out cs2-review.json",+ ),+)++FINAL_STEPS: Final = (+ ("part-coverage", "python3 forge/stage4_review/check_part_coverage.py --spec {spec} --manifest parts.json"),+ ("action-ready", "Verify explodable/clickable hierarchy, pivots, sockets, and root.userData.sculptRuntime"),+)+++class WorkflowStateError(ValueError):+ pass+++def _step(step_id: str, command: str, *, scope: str) -> dict[str, Any]:+ return {+ "id": step_id,+ "scope": scope,+ "status": "pending",+ "evidence": [],+ "reason": "",+ "command": command,+ }+++def new_state(+ reference: str,+ *,+ profile: str = "generic",+ spec: str = "",+ max_per_pass: int = 3,+ max_total: int = 6,+) -> dict[str, Any]:+ if profile not in {"generic", "cs2", "character"}:+ raise WorkflowStateError("profile must be generic, cs2, or character")+ if max_per_pass < 1 or max_total < 1 or max_per_pass > max_total:+ raise WorkflowStateError("loop limits require 1 <= max-per-pass <= max-total")+ setup = [_step(*item, scope="setup") for item in SETUP_STEPS]+ insertion = next(index for index, item in enumerate(setup) if item["id"] == "local-spec-search")+ if profile == "cs2":+ setup[insertion:insertion] = [_step(*item, scope="setup") for item in CS2_STEPS]+ elif profile == "character":+ setup[insertion:insertion] = [_step(*item, scope="setup") for item in CHARACTER_STEPS]+ pass_steps = list(PASS_STEPS)+ if profile == "cs2":+ review_index = next(index for index, item in enumerate(pass_steps) if item[0] == "ai-review-recorded")+ pass_steps[review_index:review_index] = list(CS2_PASS_STEPS)+ state = {+ "schemaVersion": SCHEMA_VERSION,+ "status": "active",+ "profile": profile,+ "currentStep": setup[0]["id"],+ "currentPass": "",+ "checklist": setup+ + [_step(*item, scope="pass") for item in pass_steps]+ + [_step(*item, scope="final") for item in FINAL_STEPS],+ "loops": {+ "perPass": {},+ "total": 0,+ "maxPerPass": max_per_pass,+ "maxTotal": max_total,+ },+ "artifacts": {"reference": reference, "spec": spec},+ "passHistory": [],+ "reviewCursor": 0,+ "iterationAction": "initial",+ "stopReason": "",+ }+ recompute(state)+ return state+++def validate_state(state: Any) -> dict[str, Any]:+ if not isinstance(state, dict):+ raise WorkflowStateError("state must be a JSON object")+ if state.get("schemaVersion") != SCHEMA_VERSION:+ raise WorkflowStateError(f"unsupported state schemaVersion: {state.get('schemaVersion')!r}")+ if state.get("profile") not in {"generic", "cs2", "character"}:+ raise WorkflowStateError("state profile is invalid")+ checklist = state.get("checklist")+ if not isinstance(checklist, list) or not checklist:+ raise WorkflowStateError("state checklist must be a non-empty list")+ seen: set[str] = set()+ for entry in checklist:+ if not isinstance(entry, dict) or not isinstance(entry.get("id"), str):+ raise WorkflowStateError("every checklist entry needs a string id")+ if entry["id"] in seen:+ raise WorkflowStateError(f"duplicate checklist step: {entry['id']}")+ seen.add(entry["id"])+ if entry.get("scope") not in {"setup", "pass", "final"}:+ raise WorkflowStateError(f"invalid checklist scope for {entry['id']}")+ if entry.get("status") not in STEP_STATUSES:+ raise WorkflowStateError(f"invalid checklist status for {entry['id']}")+ loops = state.get("loops")+ if not isinstance(loops, dict):+ raise WorkflowStateError("state loops must be an object")+ max_per_pass = loops.get("maxPerPass")+ max_total = loops.get("maxTotal")+ if not isinstance(max_per_pass, int) or not isinstance(max_total, int):+ raise WorkflowStateError("loop limits must be integers")+ if max_per_pass < 1 or max_total < 1 or max_per_pass > max_total:+ raise WorkflowStateError("loop limits require 1 <= maxPerPass <= maxTotal")+ artifacts = state.get("artifacts")+ if not isinstance(artifacts, dict) or not artifacts.get("reference"):+ raise WorkflowStateError("state artifacts.reference is required")+ review_cursor = state.get("reviewCursor", 0)+ if not isinstance(review_cursor, int) or review_cursor < 0:+ raise WorkflowStateError("state reviewCursor must be a non-negative integer")+ return state+++def load_state(path: Path) -> dict[str, Any]:+ try:+ state = json.loads(path.expanduser().read_text(encoding="utf-8"))+ except FileNotFoundError as error:+ raise WorkflowStateError(f"state file does not exist: {path}") from error+ except json.JSONDecodeError as error:+ raise WorkflowStateError(f"state file is not valid JSON: {path}") from error+ return validate_state(state)+++def save_state(path: Path, state: dict[str, Any]) -> None:+ validate_state(state)+ target = path.expanduser().resolve()+ target.parent.mkdir(parents=True, exist_ok=True)+ handle, temporary = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent)+ try:+ with os.fdopen(handle, "w", encoding="utf-8") as stream:+ json.dump(state, stream, indent=2, ensure_ascii=False)+ stream.write("\n")+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, target)+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+++def _entries(state: dict[str, Any], scope: str) -> list[dict[str, Any]]:+ return [entry for entry in state["checklist"] if entry["scope"] == scope]+++def _pending(entries: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return [entry for entry in entries if entry["status"] == "pending"]+++def _format_command(state: dict[str, Any], entry: dict[str, Any]) -> str:+ artifacts = state.get("artifacts", {})+ command = str(entry["command"])+ if entry["id"] == "build-current-pass":+ action = state.get("iterationAction")+ if action == "refine-code":+ return "Refine the existing src/createObjectModel.ts from the latest review; do not regenerate it"+ if action in {"new-pass", "refine-spec"}:+ command += " --force"+ return command.format(+ reference=shlex.quote(str(artifacts.get("reference") or "<reference>")),+ spec=shlex.quote(str(artifacts.get("spec") or "<spec>")),+ pass_id=shlex.quote(str(state.get("currentPass") or "<pass>")),+ )+++def next_entry(state: dict[str, Any]) -> dict[str, Any] | None:+ setup_pending = _pending(_entries(state, "setup"))+ if setup_pending:+ return setup_pending[0]+ if state.get("currentPass") != "complete":+ pass_pending = _pending(_entries(state, "pass"))+ if pass_pending:+ return pass_pending[0]+ return {+ "id": "await-pass-transition",+ "scope": "pass",+ "status": "pending",+ "command": "python3 forge/next.py --state .img2threejs/state.json {spec}",+ }+ final_pending = _pending(_entries(state, "final"))+ return final_pending[0] if final_pending else None+++def recompute(state: dict[str, Any]) -> None:+ entry = next_entry(state)+ if state.get("status") == "stopped":+ state["currentStep"] = "stopped"+ elif entry is None:+ state["status"] = "complete"+ state["currentStep"] = "complete"+ state["stopReason"] = ""+ else:+ state["status"] = "active"+ state["currentStep"] = entry["id"]+ state["stopReason"] = ""+++def mark_steps(+ state: dict[str, Any],+ step_ids: list[str],+ *,+ status: str,+ evidence: list[str] | None = None,+ reason: str = "",+) -> None:+ if state.get("status") == "stopped":+ raise WorkflowStateError("state is hard-stopped; do not mark more work complete")+ if status not in {"done", "skipped", "pending"}:+ raise WorkflowStateError("mark status must be done, skipped, or pending")+ if status == "done" and not evidence:+ raise WorkflowStateError("completing a mandatory step requires at least one --evidence value")+ if status == "skipped" and not reason.strip():+ raise WorkflowStateError("skipping a mandatory step requires --reason")+ by_id = {entry["id"]: entry for entry in state["checklist"]}+ missing = [step_id for step_id in step_ids if step_id not in by_id]+ if missing:+ raise WorkflowStateError(f"unknown checklist step(s): {', '.join(missing)}")+ if status in {"done", "skipped"}:+ for step_id in step_ids:+ expected = next_entry(state)+ if expected is None or expected["id"] != step_id:+ expected_id = expected["id"] if expected else "complete"+ raise WorkflowStateError(+ f"out-of-order checklist update: expected {expected_id}, received {step_id}"+ )+ entry = by_id[step_id]+ entry["status"] = status+ entry["evidence"] = list(evidence or [])+ entry["reason"] = reason.strip()+ recompute(state)+ return+ for step_id in step_ids:+ entry = by_id[step_id]+ entry["status"] = status+ entry["evidence"] = list(evidence or [])+ entry["reason"] = reason.strip()+ recompute(state)+++def set_current_pass(state: dict[str, Any], pass_id: str) -> None:+ normalized = pass_id.strip()+ if not normalized:+ raise WorkflowStateError("current pass cannot be empty")+ previous = str(state.get("currentPass") or "")+ if previous and previous != normalized:+ state.setdefault("passHistory", []).append(+ {+ "passId": previous,+ "checklist": deepcopy(_entries(state, "pass")),+ }+ )+ if previous != normalized:+ for entry in _entries(state, "pass"):+ entry["status"] = "pending"+ entry["evidence"] = []+ entry["reason"] = ""+ state["iterationAction"] = "new-pass" if previous else "initial"+ state["currentPass"] = normalized+ recompute(state)+++def sync_from_spec(state: dict[str, Any], spec: dict[str, Any], current_pass: str) -> None:+ set_current_pass(state, current_pass)+ history = spec.get("reviewHistory", [])+ if not isinstance(history, list):+ history = []+ review_cursor = min(int(state.get("reviewCursor", 0)), len(history))+ new_reviews = history[review_cursor:]+ refinements = [+ entry+ for entry in new_reviews+ if isinstance(entry, dict)+ and entry.get("passId") == current_pass+ and entry.get("action") in REFINE_ACTIONS+ ]+ if current_pass != "complete" and refinements:+ state.setdefault("passHistory", []).append(+ {+ "passId": current_pass,+ "iteration": "refine",+ "checklist": deepcopy(_entries(state, "pass")),+ }+ )+ for checklist_entry in _entries(state, "pass"):+ checklist_entry["status"] = "pending"+ checklist_entry["evidence"] = []+ checklist_entry["reason"] = ""+ state["iterationAction"] = refinements[-1]["action"]+ state["reviewCursor"] = len(history)+ per_pass: dict[str, int] = {}+ total = 0+ for entry in history:+ if not isinstance(entry, dict) or entry.get("action") not in REFINE_ACTIONS:+ continue+ pass_id = str(entry.get("passId") or "unknown")+ per_pass[pass_id] = per_pass.get(pass_id, 0) + 1+ total += 1+ loops = state["loops"]+ loops["perPass"] = per_pass+ loops["total"] = total+ pass_count = per_pass.get(current_pass, 0)+ if pass_count >= loops["maxPerPass"]:+ state["status"] = "stopped"+ state["currentStep"] = "stopped"+ state["stopReason"] = f"max-correction-loops-reached:{current_pass}:{pass_count}/{loops['maxPerPass']}"+ elif total >= loops["maxTotal"]:+ state["status"] = "stopped"+ state["currentStep"] = "stopped"+ state["stopReason"] = f"max-total-correction-loops-reached:{total}/{loops['maxTotal']}"+ else:+ recompute(state)+++def status_payload(state: dict[str, Any]) -> dict[str, Any]:+ entry = next_entry(state)+ current_pass = str(state.get("currentPass") or "")+ loops = state["loops"]+ visible_scopes = {"setup", "final"}+ if current_pass != "complete":+ visible_scopes.add("pass")+ return {+ "status": state["status"],+ "currentStep": state["currentStep"],+ "currentPass": current_pass,+ "loop": {+ "passCount": loops.get("perPass", {}).get(current_pass, 0),+ "maxPerPass": loops["maxPerPass"],+ "totalCount": loops["total"],+ "maxTotal": loops["maxTotal"],+ },+ "nextCommand": None if state["status"] != "active" or entry is None else _format_command(state, entry),+ "stopReason": state.get("stopReason") or None,+ "pending": [+ entry["id"]+ for entry in state["checklist"]+ if entry["scope"] in visible_scopes and entry["status"] == "pending"+ ],+ }diff --git a/forge/next.py b/forge/next.pyindex fea8036..32e4e20 100644--- a/forge/next.py+++ b/forge/next.py@@ -10,24 +10,93 @@ sys.path.insert(0, str(ROOT / "_shared"))sys.path.insert(0, str(ROOT / "stage3_build"))from status_banner import emit_statusfrom orchestrate_passes import current_pass, pass_acceptance, pass_order, completed_passes+from workflow_state import (+ WorkflowStateError,+ load_state,+ save_state,+ status_payload,+ sync_from_spec,+)+++def emit_local_state(payload: dict) -> None:+ loop = payload["loop"]+ print(+ f"LOCAL_STATE status={payload['status']} step={payload['currentStep']} "+ f"pass={payload['currentPass'] or 'none'} "+ f"loop={loop['passCount']}/{loop['maxPerPass']} "+ f"total={loop['totalCount']}/{loop['maxTotal']}"+ )+ if payload["stopReason"]:+ print(f"STOP: {payload['stopReason']}")+ elif payload["nextCommand"]:+ print(f"next command: {payload['nextCommand']}")+ print("pending mandatory steps:")+ for step_id in payload["pending"]:+ print(f"- {step_id}")def main(argv: list[str]) -> int:parser = argparse.ArgumentParser(description="Report the exact next sculpt pipeline command")- parser.add_argument("spec", type=Path)+ parser.add_argument("spec", type=Path, nargs="?")+ parser.add_argument("--state", type=Path, help="local checklist state created by forge/state.py init")args = parser.parse_args(argv)- spec = json.loads(args.spec.expanduser().read_text(encoding="utf-8"))+ local_state = None+ spec_path = args.spec+ if args.state:+ try:+ local_state = load_state(args.state)+ except WorkflowStateError as error:+ print(f"state error: {error}", file=sys.stderr)+ return 2+ if spec_path is None:+ stored_spec = local_state.get("artifacts", {}).get("spec")+ spec_path = Path(stored_spec) if isinstance(stored_spec, str) and stored_spec else None+ else:+ stored_spec = local_state.get("artifacts", {}).get("spec")+ if isinstance(stored_spec, str) and stored_spec:+ if Path(stored_spec).expanduser().resolve() != spec_path.expanduser().resolve():+ print(+ f"state error: positional spec {spec_path} does not match stored spec {stored_spec}",+ file=sys.stderr,+ )+ return 2+ else:+ local_state["artifacts"]["spec"] = str(spec_path)++ if spec_path is None:+ if local_state is None:+ parser.error("spec is required unless --state points to an initialized pre-spec workflow")+ payload = status_payload(local_state)+ emit_local_state(payload)+ return 3 if payload["status"] == "stopped" else 0++ try:+ spec = json.loads(spec_path.expanduser().read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as error:+ print(f"spec error: {error}", file=sys.stderr)+ return 2if not isinstance(spec, dict):raise ValueError("spec must be an object")ids = pass_order(spec)completed = completed_passes(spec, ids)current = current_pass(ids, completed)++ if local_state is not None:+ sync_from_spec(local_state, spec, current)+ save_state(args.state, local_state)+ payload = status_payload(local_state)+ emit_local_state(payload)+ if payload["status"] == "stopped":+ return 3+ return 0+emit_status(spec)if current == "complete":print("pipeline: complete")return 0acceptance = pass_acceptance(spec, current)- command = f"python3 forge/stage3_build/orchestrate_passes.py check {args.spec} --pass-id {current}"+ command = f"python3 forge/stage3_build/orchestrate_passes.py check {spec_path} --pass-id {current}"print(f"current pass: {current}")print(f"next command: {command}")print("unmet acceptance criteria:")diff --git a/forge/stage4_review/cs2_review.py b/forge/stage4_review/cs2_review.pyindex 1af67e1..b90d66b 100644--- a/forge/stage4_review/cs2_review.py+++ b/forge/stage4_review/cs2_review.py@@ -1,6 +1,10 @@from __future__ import annotations+import argparseimport json+import os+import sys+import tempfilefrom pathlib import Pathfrom typing import Any@@ -166,3 +170,55 @@ def evaluate_knife_review("failedGates": failed,}return report+++def _load_object(path: Path, label: str) -> dict[str, Any]:+ payload = json.loads(path.expanduser().read_text(encoding="utf-8"))+ if not isinstance(payload, dict):+ raise ValueError(f"{label} must be a JSON object")+ return payload+++def _write_json_atomic(path: Path, payload: dict[str, Any]) -> None:+ target = path.expanduser().resolve()+ target.parent.mkdir(parents=True, exist_ok=True)+ handle, temporary = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent)+ try:+ with os.fdopen(handle, "w", encoding="utf-8") as stream:+ json.dump(payload, stream, indent=2, ensure_ascii=False)+ stream.write("\n")+ stream.flush()+ os.fsync(stream.fileno())+ os.replace(temporary, target)+ finally:+ if os.path.exists(temporary):+ os.unlink(temporary)+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description="Evaluate the blocking CS2 knife review contract")+ parser.add_argument("--manifest", type=Path, required=True, help="validated cs2-intake.json")+ parser.add_argument("--metrics", type=Path, required=True, help="render/review metrics JSON")+ parser.add_argument(+ "--scene",+ type=Path,+ default=Path("forge/tests/fixtures/knife_review_scene.json"),+ help="versioned review scene fixture",+ )+ parser.add_argument("--out", type=Path, required=True, help="output review report JSON")+ args = parser.parse_args(argv)+ try:+ manifest = _load_object(args.manifest, "manifest")+ metrics = _load_object(args.metrics, "metrics")+ scene = load_review_scene(args.scene.expanduser())+ report = evaluate_knife_review(manifest, metrics, scene)+ _write_json_atomic(args.out, report)+ print(json.dumps(report, indent=2, ensure_ascii=False))+ return 0 if report["verdict"] == "pass" else 1+ except (OSError, ValueError, json.JSONDecodeError) as error:+ print(f"error: {error}", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/forge/state.py b/forge/state.pynew file mode 100644index 0000000..93496c8--- /dev/null+++ b/forge/state.py@@ -0,0 +1,98 @@+#!/usr/bin/env python3+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent+sys.path.insert(0, str(ROOT / "_shared"))++from workflow_state import ( # noqa: E402+ WorkflowStateError,+ load_state,+ mark_steps,+ new_state,+ save_state,+ status_payload,+)+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="Minimal local checklist state for img2threejs")+ commands = parser.add_subparsers(dest="command", required=True)++ init = commands.add_parser("init")+ init.add_argument("--state", type=Path, default=Path(".img2threejs/state.json"))+ init.add_argument("--reference", required=True)+ init.add_argument("--profile", choices=("generic", "cs2", "character"), default="generic")+ init.add_argument("--spec", default="")+ init.add_argument("--max-per-pass", type=int, default=3)+ init.add_argument("--max-total", type=int, default=6)++ status = commands.add_parser("status")+ status.add_argument("--state", type=Path, default=Path(".img2threejs/state.json"))+ status.add_argument("--json", action="store_true")++ mark = commands.add_parser("mark")+ mark.add_argument("step", nargs="+")+ mark.add_argument("--state", type=Path, default=Path(".img2threejs/state.json"))+ mark.add_argument("--status", choices=("done", "skipped", "pending"), default="done")+ mark.add_argument("--evidence", action="append", default=[])+ mark.add_argument("--reason", default="")++ return parser+++def print_status(state: dict, *, as_json: bool = False) -> None:+ payload = status_payload(state)+ if as_json:+ print(json.dumps(payload, ensure_ascii=False))+ return+ loop = payload["loop"]+ print(+ f"STATE status={payload['status']} step={payload['currentStep']} "+ f"pass={payload['currentPass'] or 'none'} "+ f"loop={loop['passCount']}/{loop['maxPerPass']} total={loop['totalCount']}/{loop['maxTotal']}"+ )+ if payload["stopReason"]:+ print(f"STOP: {payload['stopReason']}")+ elif payload["nextCommand"]:+ print(f"next command: {payload['nextCommand']}")+ print("pending mandatory steps:")+ for step_id in payload["pending"]:+ print(f"- {step_id}")+++def main(argv: list[str]) -> int:+ args = build_parser().parse_args(argv)+ try:+ if args.command == "init":+ if args.state.expanduser().exists():+ raise WorkflowStateError(f"refusing to overwrite existing state: {args.state}")+ state = new_state(+ args.reference,+ profile=args.profile,+ spec=args.spec,+ max_per_pass=args.max_per_pass,+ max_total=args.max_total,+ )+ save_state(args.state, state)+ print_status(state)+ return 0+ state = load_state(args.state)+ if args.command == "status":+ print_status(state, as_json=args.json)+ elif args.command == "mark":+ mark_steps(state, args.step, status=args.status, evidence=args.evidence, reason=args.reason)+ save_state(args.state, state)+ print_status(state)+ return 3 if state.get("status") == "stopped" else 0+ except (OSError, WorkflowStateError) as error:+ print(f"state error: {error}", file=sys.stderr)+ return 2+++if __name__ == "__main__":+ raise SystemExit(main(sys.argv[1:]))diff --git a/forge/tests/test_cs2_review.py b/forge/tests/test_cs2_review.pyindex 5151f14..5827b3c 100644--- a/forge/tests/test_cs2_review.py+++ b/forge/tests/test_cs2_review.py@@ -4,12 +4,14 @@ import jsonimport sysimport tempfileimport unittest+from contextlib import redirect_stdout+from io import StringIOfrom pathlib import PathROOT = Path(__file__).resolve().parent.parentsys.path.insert(0, str(ROOT / "stage4_review"))-from cs2_review import evaluate_knife_review, load_review_scene # noqa: E402+from cs2_review import evaluate_knife_review, load_review_scene, main as cs2_review_main # noqa: E402from append_review import main as append_review_main # noqa: E402@@ -53,6 +55,24 @@ class Cs2ReviewGateTest(unittest.TestCase):self.assertEqual(report["failedGates"], [])self.assertEqual(report["approximationNotes"], ["hidden blade side inferred from single view"])+ def test_cli_writes_report_and_returns_verdict_status(self) -> None:+ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ manifest_path = root / "manifest.json"+ metrics_path = root / "metrics.json"+ report_path = root / "report.json"+ manifest_path.write_text(json.dumps(self.manifest), encoding="utf-8")+ metrics_path.write_text(json.dumps(self.passing_inputs()), encoding="utf-8")+ with redirect_stdout(StringIO()):+ result = cs2_review_main([+ "--manifest", str(manifest_path),+ "--metrics", str(metrics_path),+ "--scene", str(ROOT / "tests" / "fixtures" / "knife_review_scene.json"),+ "--out", str(report_path),+ ])+ self.assertEqual(result, 0)+ self.assertEqual(json.loads(report_path.read_text(encoding="utf-8"))["verdict"], "pass")+def test_wrong_family_is_blocking_even_when_visual_metrics_pass(self) -> None:manifest = {**self.manifest, "itemFamily": "rifle"}diff --git a/forge/tests/test_workflow_state.py b/forge/tests/test_workflow_state.pynew file mode 100644index 0000000..089a176--- /dev/null+++ b/forge/tests/test_workflow_state.py@@ -0,0 +1,295 @@+from __future__ import annotations++import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path+++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT / "forge" / "_shared"))++from workflow_state import ( # noqa: E402+ WorkflowStateError,+ mark_steps,+ new_state,+ set_current_pass,+ status_payload,+ sync_from_spec,+)+++class WorkflowStateTest(unittest.TestCase):+ def test_generic_state_starts_with_mandatory_image_analysis(self):+ state = new_state("reference.png")+ payload = status_payload(state)+ self.assertEqual(payload["currentStep"], "image-analysis")+ self.assertEqual(payload["loop"]["passCount"], 0)+ self.assertEqual(payload["loop"]["maxPerPass"], 3)+ self.assertIn("part-coverage", payload["pending"])+ ids = [entry["id"] for entry in state["checklist"]]+ self.assertLess(ids.index("reference-suitability"), ids.index("reference-admission"))+ self.assertLess(ids.index("detail-inventory"), ids.index("projection-route"))+ self.assertLess(ids.index("projection-route"), ids.index("spec-authoring"))+ self.assertLess(ids.index("material-evidence"), ids.index("strict-validation"))++ def test_cs2_state_includes_classification_and_manifest_before_pre_spec(self):+ state = new_state("knife.png", profile="cs2")+ ids = [entry["id"] for entry in state["checklist"]]+ self.assertLess(ids.index("cs2-contract-read"), ids.index("cs2-authoritative-classification"))+ self.assertLess(ids.index("cs2-authoritative-classification"), ids.index("pre-spec-assessment"))+ self.assertLess(ids.index("cs2-manifest"), ids.index("pre-spec-assessment"))+ self.assertLess(ids.index("pass-gate-check"), ids.index("cs2-review"))+ self.assertLess(ids.index("cs2-review"), ids.index("ai-review-recorded"))++ def test_character_state_requires_contract_landmarks_and_route_decision(self):+ state = new_state("character.png", profile="character")+ ids = [entry["id"] for entry in state["checklist"]]+ self.assertLess(ids.index("character-contract-read"), ids.index("character-landmarks"))+ self.assertLess(ids.index("character-landmarks"), ids.index("pre-spec-assessment"))+ self.assertLess(ids.index("character-landmarks"), ids.index("projection-route"))++ def test_pass_commands_follow_executable_gate_order(self):+ state = new_state("reference.png", spec="spec.json")+ entries = [entry for entry in state["checklist"] if entry["scope"] == "pass"]+ ids = [entry["id"] for entry in entries]+ commands = {entry["id"]: entry["command"] for entry in entries}+ self.assertIn("generate_threejs_factory.py", commands["build-current-pass"])+ self.assertLess(ids.index("build-current-pass"), ids.index("tier1-diagnostics"))+ self.assertLess(ids.index("tier1-diagnostics"), ids.index("pass-gate-check"))+ self.assertLess(ids.index("pass-gate-check"), ids.index("ai-review-recorded"))++ def test_skipping_a_mandatory_step_requires_reason(self):+ state = new_state("reference.png")+ with self.assertRaises(WorkflowStateError):+ mark_steps(state, ["image-analysis"], status="skipped")+ mark_steps(state, ["image-analysis"], status="skipped", reason="analysis supplied externally")+ entry = next(item for item in state["checklist"] if item["id"] == "image-analysis")+ self.assertEqual(entry["status"], "skipped")++ def test_completing_a_mandatory_step_requires_evidence(self):+ state = new_state("reference.png")+ with self.assertRaises(WorkflowStateError):+ mark_steps(state, ["image-analysis"], status="done")+ mark_steps(state, ["image-analysis"], status="done", evidence=["analysis.json"])+ entry = next(item for item in state["checklist"] if item["id"] == "image-analysis")+ self.assertEqual(entry["evidence"], ["analysis.json"])++ def test_new_pass_archives_and_resets_pass_checklist(self):+ state = new_state("reference.png")+ setup_ids = [entry["id"] for entry in state["checklist"] if entry["scope"] == "setup"]+ mark_steps(state, setup_ids, status="done", evidence=["setup-evidence.json"])+ set_current_pass(state, "blockout")+ mark_steps(+ state,+ ["build-current-pass", "render-capture", "review-contract-read", "tier1-diagnostics"],+ status="done",+ evidence=["shot.png"],+ )+ set_current_pass(state, "structural-pass")+ self.assertEqual(state["passHistory"][0]["passId"], "blockout")+ pass_entries = [entry for entry in state["checklist"] if entry["scope"] == "pass"]+ self.assertTrue(all(entry["status"] == "pending" for entry in pass_entries))++ def test_checklist_cannot_be_completed_out_of_order(self):+ state = new_state("reference.png")+ with self.assertRaisesRegex(WorkflowStateError, "out-of-order"):+ mark_steps(state, ["strict-validation"], status="done", evidence=["spec.json"])++ def test_refine_review_resets_same_pass_checklist_once(self):+ state = new_state("reference.png")+ setup_ids = [entry["id"] for entry in state["checklist"] if entry["scope"] == "setup"]+ pass_ids = [entry["id"] for entry in state["checklist"] if entry["scope"] == "pass"]+ mark_steps(state, setup_ids, status="done", evidence=["setup.json"])+ set_current_pass(state, "blockout")+ mark_steps(state, pass_ids, status="done", evidence=["review.json"])+ self.assertEqual(status_payload(state)["currentStep"], "await-pass-transition")++ spec = {"reviewHistory": [{"passId": "blockout", "action": "refine-code"}]}+ sync_from_spec(state, spec, "blockout")+ self.assertEqual(status_payload(state)["currentStep"], "build-current-pass")+ self.assertIn("do not regenerate", status_payload(state)["nextCommand"])+ self.assertTrue(+ all(entry["status"] == "pending" for entry in state["checklist"] if entry["scope"] == "pass")+ )+ archived = len(state["passHistory"])+ sync_from_spec(state, spec, "blockout")+ self.assertEqual(len(state["passHistory"]), archived)++ def test_new_pass_and_refine_spec_regenerate_with_force(self):+ state = new_state("reference.png", spec="spec.json")+ setup_ids = [entry["id"] for entry in state["checklist"] if entry["scope"] == "setup"]+ mark_steps(state, setup_ids, status="done", evidence=["setup.json"])+ set_current_pass(state, "blockout")+ self.assertNotIn("--force", status_payload(state)["nextCommand"])+ set_current_pass(state, "structural-pass")+ self.assertIn("--force", status_payload(state)["nextCommand"])+ sync_from_spec(+ state,+ {"reviewHistory": [{"passId": "structural-pass", "action": "refine-spec"}]},+ "structural-pass",+ )+ self.assertIn("--force", status_payload(state)["nextCommand"])++ def test_per_pass_refine_limit_is_a_hard_stop(self):+ state = new_state("reference.png", max_per_pass=3, max_total=6)+ spec = {+ "reviewHistory": [+ {"passId": "blockout", "action": "refine-code"},+ {"passId": "blockout", "action": "refine-spec"},+ {"passId": "blockout", "action": "refine-code"},+ ]+ }+ sync_from_spec(state, spec, "blockout")+ payload = status_payload(state)+ self.assertEqual(payload["status"], "stopped")+ self.assertEqual(payload["loop"]["passCount"], 3)+ self.assertIn("max-correction-loops-reached", payload["stopReason"])+ self.assertIsNone(payload["nextCommand"])++ def test_total_refine_limit_is_a_hard_stop(self):+ state = new_state("reference.png", max_per_pass=4, max_total=6)+ spec = {+ "reviewHistory": [+ {"passId": "blockout", "action": "refine-code"},+ {"passId": "blockout", "action": "refine-spec"},+ {"passId": "structural-pass", "action": "refine-code"},+ {"passId": "structural-pass", "action": "refine-spec"},+ {"passId": "form-refinement", "action": "refine-code"},+ {"passId": "form-refinement", "action": "refine-spec"},+ ]+ }+ sync_from_spec(state, spec, "material-pass")+ payload = status_payload(state)+ self.assertEqual(payload["status"], "stopped")+ self.assertIn("max-total-correction-loops-reached", payload["stopReason"])++ def test_next_cli_reads_state_before_a_spec_exists(self):+ with tempfile.TemporaryDirectory() as directory:+ state_path = Path(directory) / "state.json"+ init = subprocess.run(+ [+ sys.executable,+ str(ROOT / "forge" / "state.py"),+ "init",+ "--state",+ str(state_path),+ "--reference",+ "reference.png",+ ],+ capture_output=True,+ text=True,+ )+ self.assertEqual(init.returncode, 0, init.stderr)+ result = subprocess.run(+ [sys.executable, str(ROOT / "forge" / "next.py"), "--state", str(state_path)],+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("LOCAL_STATE status=active step=image-analysis", result.stdout)+ self.assertIn("pending mandatory steps", result.stdout)++ def test_next_cli_emits_only_state_ordered_build_command(self):+ with tempfile.TemporaryDirectory() as directory:+ state_path = Path(directory) / "state.json"+ spec_path = Path(directory) / "spec.json"+ state = new_state("reference.png", spec=str(spec_path))+ setup_ids = [entry["id"] for entry in state["checklist"] if entry["scope"] == "setup"]+ mark_steps(state, setup_ids, status="done", evidence=["setup.json"])+ state_path.write_text(json.dumps(state), encoding="utf-8")+ spec_path.write_text(+ json.dumps({"buildPasses": [{"id": "blockout", "acceptance": []}], "reviewHistory": []}),+ encoding="utf-8",+ )+ result = subprocess.run(+ [sys.executable, str(ROOT / "forge" / "next.py"), "--state", str(state_path)],+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 0, result.stderr)+ self.assertIn("generate_threejs_factory.py", result.stdout)+ self.assertNotIn("orchestrate_passes.py check", result.stdout)++ def test_next_cli_rejects_a_spec_that_differs_from_state(self):+ with tempfile.TemporaryDirectory() as directory:+ state_path = Path(directory) / "state.json"+ stored_spec = Path(directory) / "stored.json"+ other_spec = Path(directory) / "other.json"+ state_path.write_text(+ json.dumps(new_state("reference.png", spec=str(stored_spec))),+ encoding="utf-8",+ )+ other_spec.write_text(json.dumps({"buildPasses": []}), encoding="utf-8")+ result = subprocess.run(+ [+ sys.executable,+ str(ROOT / "forge" / "next.py"),+ str(other_spec),+ "--state",+ str(state_path),+ ],+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 2)+ self.assertIn("does not match stored spec", result.stderr)++ def test_state_cli_does_not_expose_manual_pass_bypass(self):+ result = subprocess.run(+ [sys.executable, str(ROOT / "forge" / "state.py"), "set-pass", "complete"],+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 2)+ self.assertIn("invalid choice", result.stderr)++ def test_next_cli_returns_nonzero_at_loop_ceiling(self):+ with tempfile.TemporaryDirectory() as directory:+ state_path = Path(directory) / "state.json"+ spec_path = Path(directory) / "spec.json"+ state = new_state("reference.png", spec=str(spec_path), max_per_pass=2, max_total=6)+ state_path.write_text(json.dumps(state), encoding="utf-8")+ spec_path.write_text(+ json.dumps(+ {+ "buildPasses": [{"id": "blockout", "acceptance": []}],+ "reviewHistory": [+ {"passId": "blockout", "action": "refine-code"},+ {"passId": "blockout", "action": "refine-spec"},+ ],+ }+ ),+ encoding="utf-8",+ )+ result = subprocess.run(+ [sys.executable, str(ROOT / "forge" / "next.py"), "--state", str(state_path)],+ capture_output=True,+ text=True,+ )+ self.assertEqual(result.returncode, 3, result.stderr)+ self.assertIn("STOP: max-correction-loops-reached", result.stdout)++ def test_skill_router_keeps_mandatory_state_and_reference_gates_visible(self):+ skill = (ROOT / "SKILL.md").read_text(encoding="utf-8")+ self.assertIn("forge/next.py --state .img2threejs/state.json", skill)+ self.assertIn("MUST read `grimoire/intake/cs2_intake_contract.md` completely", skill)+ self.assertIn("MUST read\n `grimoire/review/gates_reference.md`", skill)+ self.assertIn("forge/stage4_review/diagnose_render.py", skill)+ self.assertIn("forge/stage4_review/diagnose_render_multi_angle.py", skill)+ self.assertIn("forge/stage4_review/check_part_coverage.py", skill)++ def test_all_direct_router_references_exist(self):+ for relative in (+ "grimoire/intake/cs2_intake_contract.md",+ "grimoire/intake/local_spec_search.md",+ "grimoire/review/gates_reference.md",+ "grimoire/review/self_correction.md",+ ):+ self.assertTrue((ROOT / relative).is_file(), relative)+++if __name__ == "__main__":+ unittest.main()diff --git a/grimoire/intake/cs2_intake_contract.md b/grimoire/intake/cs2_intake_contract.mdnew file mode 100644index 0000000..f05cd9e--- /dev/null+++ b/grimoire/intake/cs2_intake_contract.md@@ -0,0 +1,80 @@+# CS2 Intake Contract++Read this reference completely for every CS2 request before creating `cs2-intake.json` or running+pre-spec assessment. Do not advance the local checklist until its classification and manifest+requirements are satisfied.++For a CS2 item, the target is observable agreement between the supplied image and the rendered+item: silhouette, proportions, edge profile, hardware layout, coating colour, pattern placement,+wear, roughness response, and camera framing. Every decision must be traceable to evidence or be+labelled as an approximation.++The initial CS2 family boundary is **knife only**. Pistol, rifle, SMG, sniper, heavy, glove, and+unknown knife subtypes must stop with `unsupported-family` or `unsupported-subtype`; they must not+receive the knife component tree as a generic fallback.++## When to build `cs2-intake.json`++For a CS2 request, create and validate `cs2-intake.json` before pre-spec authoring. Run admission+and probing for every source view, record the heuristic signal as non-authoritative evidence,+attach the classification record, resolve the supported family, and choose `route` independently+from `exactnessTier`. Missing classification, insufficient coverage, or a contradictory+high-confidence class is `request-input`; unsupported families do not continue into spec+generation.++## Layer contract++Pass these records between layers. Do not copy an informal vision description into the next stage:++| Layer | Owns | Must emit | Must not decide alone |+| --- | --- | --- | --- |+| Intake | view validity and technical evidence | role, path/hash, resolution, coverage, duplicate status, admission verdict | item identity from aspect ratio or filename |+| Classification | semantic identity | family, subtype, confidence, evidence refs, provider/version, timeout state | geometry or finish parameters |+| Identity | skin/name/paint metadata | precedence, resolved values, ambiguity candidates, provenance | guessed paint index, float, or seed |+| Surface evidence | pixels and texture sources | de-lit reference, PBR channels, map provenance, colour space, UV orientation, confidence | albedo reused as roughness/normal/AO |+| Geometry adapter | family-specific form | component tree, topology, dimensions, edge/spine, hardware relationships, painted regions | hidden geometry without confidence notes |+| Spec/route | evidence-backed implementation choice | route, exactness tier, assumptions, feature targets, camera contract | exact-texture claim without exact evidence |+| Build/review | rendered observables | fixed view, two non-degenerate orbit views, per-region results, failed gates, next action | overriding a failed critical feature with a global score |++The canonical hand-off is `cs2-intake.json` (`schemaVersion: 1`). Its state is one of+`proceed`, `request-input`, `fallback`, `rejected`, `unsupported-family`, or+`unsupported-subtype`. Write it atomically and preserve unknown provider fields under+`extensions`; a fallback must never erase prior evidence.++## CS2 intake order++1. Admit and technically probe every view. Reject undecodable, empty, tiny, fragmented, or+ duplicate references before classification.+2. Record the heuristic CS2 signal only as a routing hint. `detect_cs2.py` is never authoritative+ identity evidence.+3. Require a classification record before selecting a family adapter. If classification is absent,+ timed out, or contradicts a high-confidence objectness result, return `request-input`.+4. Resolve identity in this order: explicit user metadata, uniquely resolved metadata, then the+ authoritative classification record. Preserve ambiguity rather than guessing.+5. Select route and exactness independently:+ - `reference-projection`: default for matching a specific patterned image;+ - `authored-texture`: only when independent texture maps are supplied or legally acquired;+ - `procedural-finish`: fallback when projection evidence is unavailable or live response is the+ stated priority.+ Exactness is `image-only`, `metadata-assisted`, or `exact-texture`; changing route must not+ silently upgrade or downgrade the evidence tier.+6. Select the knife adapter only after family/subtype validation. Record painted regions, unpainted+ substrate, visible hardware, hidden-region confidence, and every approximation in the spec.+7. For projection, solve the camera and de-light the source first. Projected pixels provide colour+ evidence, not automatic geometry truth; geometry still comes from the adapter and silhouette+ review.++## Surface and review rule++For a specific CS2 reference, preserve the reference's own colour/pattern pixels whenever legal and+technically possible. Procedural Doppler/Fade/Gamma/Marble patterns are not equivalent to the input+image and may only be used with an explicit `procedural-finish` route and approximation warning.+Keep albedo, roughness, metalness, normal/height, AO, mask, and wear as independent channels. Record+channel source, colour space, UV orientation, dimensions, packed-channel decoding, and missing-channel+derivation. A low-confidence PBR inference is a refine-input signal, not proof of exact material.++Single-view reconstruction may proceed only when visible identity features are sufficiently covered;+hidden blade sides, underside, and back hardware must carry inference confidence and may trigger+`request-input`. Review the fixed camera plus two meaningful orbit views. Report what changed, which+evidence caused it, what still differs, and choose exactly one next action:+`continue`, `refine-spec`, `refine-code`, `request-input`, or `stop`.diff --git a/grimoire/intake/local_spec_search.md b/grimoire/intake/local_spec_search.mdnew file mode 100644index 0000000..3725d5f--- /dev/null+++ b/grimoire/intake/local_spec_search.md@@ -0,0 +1,29 @@+# Local Spec Search++After image analysis and before writing or refining a spec, local evidence is a pipeline stage,+not an optional memory lookup, whenever the request needs domain-specific anatomy, PBR, wear,+geometry, runtime, or physics specifications.++The pre-spec command automatically runs BM25, chooses `cs2` for CS2 targets and `core_3d`+otherwise, and writes a `localSpecSearch` evidence bundle into the assessment:++```+python3 forge/stage2_spec/new_pre_spec_assessment.py "Name" --image <img> --out assessment.json+```++Add observed terms with repeatable `--spec-query "<term>"`; use `--collection <collection>` only+when the automatic collection choice is insufficient. `new_sculpt_spec.py --assessment` carries+that bundle into the final spec, including snippets, `source_refs`, and `evidence_refs`.++For extra focused retrieval, the direct CLI remains available:++```+python3 forge/stage1_intake/search_specs.py "<query>" --collection <collection> --limit 3 --snippet-chars 250 --json+```++For CS2, include English/Vietnamese variants, for example `--spec-query "safety ring vòng ngón"`+or `search_specs.py "roughness độ nhám" --collection cs2`. Expand queries with object names,+component names, material/finish terms, behavior terms, and bilingual aliases; retry focused+alternatives when the first result is incomplete. Build the spec from returned evidence and do+not invent domain specs when local evidence exists. Search caches are local/generated only;+preserve JSONL records and source provenance rather than replacing them with cache output.diff --git a/grimoire/review/gates_reference.md b/grimoire/review/gates_reference.mdnew file mode 100644index 0000000..e2bb541--- /dev/null+++ b/grimoire/review/gates_reference.md@@ -0,0 +1,66 @@+# Gates Reference (full contract)++Read this reference completely before any visual review or `continue` decision. `SKILL.md` keeps+only the executable order and one-line summary; this file defines the mandatory gate behavior.++- **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.+- **CS2 knife review contract**: `forge/stage4_review/cs2_review.py` consumes the manifest and+ versioned scene fixture, then blocks wrong family identity, missing projection coverage,+ painted-region mismatch, critical identity-detail failure, finish/material response failure,+ and degenerate orbit form. It records exactness tier, hidden-region confidence, per-region+ confidence, approximation notes, camera, environment hash, exposure, tone mapping, resolution,+ background, and renderer version.+- **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.+ Details + per-layer scorecard: `grimoire/feedback/render_capture.md`.+- **Action-ready**: build a runtime hierarchy (pivots, sockets, colliders, destruction groups),+ never an inert lump; expose `root.userData.sculptRuntime`. `grimoire/readiness/action_rigging.md`.+- **Assembly gate (structure, not pixels) — every model ships explodable AND clickable**: this is+ a build requirement, not a per-project extra. Name every mesh; flag surface relief+ `userData.explodeWithParent` so it rides its shell; let a named group of *anonymous* meshes be one+ part while a named group of *named* parts stays a container. Explode and part-picking must share+ one definition of "a part" — if they disagree, both are wrong. Separate parts by SCALING the+ layout about the model centre, never by pushing every part the same distance (that translates the+ arrangement without opening any gap). Then run+ `forge/stage4_review/check_part_coverage.py --spec <spec> --manifest <parts.json>`: it FAILS on a+ specified component that was never built and on two components fused onto one mesh; it warns on+ inventoried details that never reached the spec and on meshes belonging to no named part. This is+ the only gate that scores STRUCTURE — every other one scores pixels, and a single fused mesh+ wearing a projected photo passes all of those. Its limit is honest and must be stated when+ reporting: it proves you built what you specified, never that you specified enough.+ Full contract + the two rules it took a wrong pass to learn: `grimoire/build/geometry_patterns.md`.+- **Attachment**: child appendages (branches/limbs/handles/tubes) need `attachment.parentSocket`,+ `localStart`, `localEnd`, `contactType`, `embedDepth`/`overlap`, `gapTolerance` — no mid-air parts.+ `grimoire/readiness/joint_attachment.md`.+- **Material/lighting**: `grimoire/feedback/shading_realism.md` — independent PBR channels+ (never alias albedo into roughness/normal/AO), macro/meso/micro frequency bands, real lights.+- **Detail inventory**: for `moderate`+ subjects strict-quality blocks code gen until the+ `detailInventory` reaches `targetMinDetails` and every detail maps to a real component/material+ entry (gloss needs low-roughness/clearcoat; fasteners need instancing/micro parts).+- **Character track**: when `primaryDomain` is `character`/`hybrid` (or `--character`), the spec+ author auto-builds a stylized humanoid template (head/neck/torso/arms + hair, glasses,+ headphones, face features), flattened to world space under a hidden root, with per-part+ character materials and character build passes (`proportion-lock`, `feature-placement`).+ strict-quality requires a filled `anatomy` block (head-units, proportions, face landmarks) and+ character feature targets. Suitability routing for humans: `grimoire/intake/validation_rubric.md`+ (stylized vs maximum-likeness). Stylized bust, not a face-copy; refine positions per reference.diff --git a/grimoire/review/self_correction.md b/grimoire/review/self_correction.mdindex 6b9a582..1a05ccd 100644--- a/grimoire/review/self_correction.md+++ b/grimoire/review/self_correction.md@@ -2,6 +2,20 @@Use this reference when a model construction pass has just finished.+## Transparency and Process Debugging (Critical — from Bowie Knife reconstruction)++**The problem:** When the user cannot tell what was done or where something went wrong, they cannot debug the process. Over-claiming (reporting success when features still don't match) destroys trust and makes iterative improvement impossible.++**Rule:** Be transparent + don't over-claim. State exactly what changed each pass, with evidence, and name what still doesn't match:+- After each pass, explicitly list what changed: "Updated guard shape to extend left edge from -0.56 to -0.48 for handle overlap"+- Provide evidence: reference the specific values, coordinates, or parameters that changed+- Name what still doesn't match: "Handle silhouette traced but still flat plane (no Z palm-swell), procedural crosshatch not reference's exact dot-grid knurl"+- Explain why a change was made: "Extended guard left edge because handle ends at X=-0.42 and guard ended at X=-0.20, causing visual gap"+- Never claim a feature is "done" when it's only "improved" — use precise language+- When a gate passes but visual inspection shows issues, explain the limitation: "2D gate passed (fidelity 0.83) but three-quarter render shows blade reads as toy (no grind wedge) — 2D gates are blind to 3D realism"++**The user needs to be able to debug the process, not just the output.** If something is wrong, they should be able to trace which decision led to the error and correct it. Opaque processes force restarts; transparent processes enable refinement.+## Review Order1. Capture or collect a rendered screenshot for the current browser view.diff --git a/grimoire/scripts.md b/grimoire/scripts.mdindex 745415c..54fc512 100644--- a/grimoire/scripts.md+++ b/grimoire/scripts.md@@ -7,6 +7,29 @@ paths resolve as `forge/<name>.py`. Non-zero exit = a gate failed; read the prinDivision of labor: **scripts enforce structure and package evidence; they never score visuals.**The acceptance score always comes from the agent's own vision inspecting the comparison sheet.+## state.py and next.py++- `state.py init --state .img2threejs/state.json --reference IMG [--profile generic|cs2|character]`+ creates the local mandatory checklist. It refuses to overwrite existing state.+- `state.py status --state .img2threejs/state.json [--json]` reports the current step and loop limits.+- `state.py mark STEP... --state .img2threejs/state.json --evidence PATH` records completed evidence.+ Use `--status skipped --reason "..."` only when a step is genuinely not applicable.+- `next.py --state .img2threejs/state.json [spec.json]` is the mandatory start/resume gate. It+ derives correction counts from `reviewHistory` and exits 3 at the per-pass or total hard ceiling.++Defaults are 3 `refine-spec`/`refine-code` decisions per pass and 6 total. These are safety limits,+not targets; stop earlier on success, repeated defects, oscillation, or plateau.++The pass checklist is executable in dependency order: generate, render, Tier 1, multi-angle,+`orchestrate_passes.py check`, profile-specific review, AI review, then sync. The CS2 profile runs:++`stage4_review/cs2_review.py --manifest cs2-intake.json --metrics cs2-review-inputs.json --scene forge/tests/fixtures/knife_review_scene.json --out cs2-review.json`++The character profile requires the reconstruction/likeness contracts, landmark evidence, and an+explicit stylized-versus-projection route decision before pre-spec authoring.+Every profile also records a reference-suitability verdict, a projection-route decision, and a+material/PBR evidence decision. A non-applicable conditional gate must be skipped with a reason.+## stage1_intake/probe_image.py`stage1_intake/probe_image.py <image>` — image type, dimensions, aspect ratio, obvious technicalissues. Metadata only; not a substitute for visual inspection.@@ -44,6 +67,9 @@ threshold (default 0.7), and every critical feature ≥ its own threshold.Emits a TypeScript Three.js `Group` factory for the **current unlocked pass only**. Passing afuture `--pass-id` fails until earlier passes are reviewed `continue`. Output exposes`root.userData.sculptRuntime` (nodes/meshes/sockets/colliders/destructionGroups) — hand-refine it.+Use `--force` for the next pass only after preserving valid hand refinements in the spec.+Do not regenerate after `refine-code`; edit the existing artifact. Regenerate with `--force` after+`refine-spec` or when advancing to a new pass.## stage4_review/make_comparison_sheet.py`stage4_review/make_comparison_sheet.py --reference IMG --render SHOT --out cmp.png [--panel-width N] [--panel-height N] [--gutter N] [--json]`