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
feat!: publish admission and probe as artifacts; the base names no CS2 file
kokorolx92ef1ee3a5aa
diff --git a/forge/_shared/workflow_state.py b/forge/_shared/workflow_state.pyindex 4724a2d..bb21db5 100644--- a/forge/_shared/workflow_state.py+++ b/forge/_shared/workflow_state.py@@ -25,7 +25,9 @@ SETUP_STEPS: Final = ("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}"),+ ("reference-admission",+ "python3 forge/stage1_intake/check_reference_admission.py {reference}"+ " --out admission.json --probe-out probe.json"),("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"),diff --git a/forge/stage1_intake/check_reference_admission.py b/forge/stage1_intake/check_reference_admission.pyindex 947dfe7..e5b6d72 100644--- a/forge/stage1_intake/check_reference_admission.py+++ b/forge/stage1_intake/check_reference_admission.py@@ -21,6 +21,7 @@ from typing import Anysys.path.insert(0, str(Path(__file__).resolve().parent))from extract_pbr_evidence import build_foreground_mask, load_image # noqa: E402+from probe_image import probe # noqa: E402sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))from image_hash import hamming, phash_from_image # noqa: E402@@ -172,6 +173,13 @@ def main(argv: list[str]) -> int: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")+ # --out publishes the verdict as a workspace artifact so a later step -- including one+ # contributed by a domain plugin -- can consume it instead of recomputing admission.+ parser.add_argument("--out", type=Path, help="also write the verdict JSON here")+ # This step is where the base pipeline establishes the technical facts about a reference, so it+ # publishes the probe alongside its verdict. A later step -- including one contributed by a+ # domain plugin, which may not import forge.* -- consumes these instead of re-deriving them.+ parser.add_argument("--probe-out", type=Path, help="also write the image probe JSON here")args = parser.parse_args(argv)against: list[int] = []@@ -189,6 +197,11 @@ def main(argv: list[str]) -> int:print(f"error: {exc}", file=sys.stderr)return 2+ for target, payload in ((args.out, verdict), (args.probe_out, probe(args.image.expanduser().resolve()) if args.probe_out else None)):+ if target is None:+ continue+ target.expanduser().parent.mkdir(parents=True, exist_ok=True)+ target.expanduser().write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")if args.json:print(json.dumps(verdict, indent=2, ensure_ascii=False))else:diff --git a/forge/stage1_intake/cs2_foundation.py b/forge/stage1_intake/cs2_foundation.pydeleted file mode 100644index 117a6d5..0000000--- a/forge/stage1_intake/cs2_foundation.py+++ /dev/null@@ -1,139 +0,0 @@-#!/usr/bin/env python3-from __future__ import annotations--from pathlib import Path-from typing import Any---def resolve_identity(- explicit: dict[str, Any] | None,- resolved: dict[str, Any] | None,- classification: dict[str, Any] | None,-) -> dict[str, Any]:- if explicit:- return {"status": "resolved", "identity": dict(explicit), "provenance": "explicit-user-metadata"}- if resolved and resolved.get("status") == "ambiguous":- return {"status": "ambiguous", "candidates": list(resolved.get("candidates", []))}- if resolved and resolved.get("status") == "no-match":- return {"status": "no-match", "reason": resolved.get("reason", "metadata lookup found no match")}- if resolved and resolved.get("status") in {None, "resolved"}:- return {"status": "resolved", "identity": dict(resolved), "provenance": "resolved-metadata"}- if classification and classification.get("itemFamily"):- return {"status": "resolved", "identity": dict(classification), "provenance": "classification-record"}- return {"status": "request-input", "reason": "authoritative identity evidence is unavailable"}---def normalize_cs2_metadata(metadata: dict[str, Any]) -> dict[str, Any]:- float_value = metadata.get("float", metadata.get("floatValue"))- paint_seed = metadata.get("paintSeed", metadata.get("paint_seed"))- hidden_confidence = metadata.get("hiddenRegionConfidence")- if not isinstance(hidden_confidence, (int, float)):- hidden_confidence = 0.25- return {- "identity": {- "name": metadata.get("name", metadata.get("itemName")),- "paintIndex": metadata.get("paintIndex", metadata.get("paint_index")),- "rarity": metadata.get("rarity"),- "previewUrl": metadata.get("previewUrl", metadata.get("imageUrl")),- "floatRange": metadata.get("floatRange", {"min": metadata.get("minFloat"), "max": metadata.get("maxFloat")}),- },- "float": float_value,- "paintSeed": paint_seed,- "finishStyle": metadata.get("finishStyle"),- "approximations": {- "float": {"value": float_value, "approximated": float_value is None, "confidence": 0.0 if float_value is None else 1.0},- "paintSeed": {"value": paint_seed, "approximated": paint_seed is None, "confidence": 0.0 if paint_seed is None else 1.0},- "hiddenRegions": {"confidence": float(hidden_confidence), "approximated": True},- "finishStyle": {"value": metadata.get("finishStyle"), "approximated": metadata.get("finishStyle") is None},- },- }---def enrich_manifest_with_metadata(manifest: dict[str, Any], resolution: dict[str, Any]) -> dict[str, Any]:- result = dict(manifest)- result["metadataResolution"] = dict(resolution)- result.setdefault("warnings", [])- warnings = list(result["warnings"])- if resolution.get("status") in {"no-match", "ambiguous"}:- if "metadata-unavailable" not in warnings:- warnings.append("metadata-unavailable")- result["exactnessTier"] = result.get("exactnessTier", "image-only")- elif resolution.get("status") == "resolved":- result["metadata"] = normalize_cs2_metadata(resolution.get("identity", resolution))- if result.get("exactnessTier") == "image-only":- result["exactnessTier"] = "metadata-assisted"- result["warnings"] = warnings- return result---def classify_map_path(path: Path) -> dict[str, Any]:- name = path.name.lower()- if any(token in name for token in ("_orm", "_mrao", "_packed")):- return {"mapClass": "packed", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard", "packedChannels": {"roughness": "r", "metalness": "g", "ao": "b"}}- if any(token in name for token in ("_normal", "_nrm", "_bump")):- return {"mapClass": "normal", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}- if any(token in name for token in ("_rough", "_roughness")):- return {"mapClass": "roughness", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}- if any(token in name for token in ("_metal", "_metalness")):- return {"mapClass": "metalness", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}- if any(token in name for token in ("_ao", "_occlusion")):- return {"mapClass": "ao", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}- if any(token in name for token in ("_height", "_displacement")):- return {"mapClass": "height", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}- if any(token in name for token in ("_mask", "_wear", "_pattern")):- return {"mapClass": "mask", "path": str(path), "colorSpace": "linear", "uvOrientation": "standard"}- return {"mapClass": "albedo", "path": str(path), "colorSpace": "srgb", "uvOrientation": "standard"}---def adapt_texture_result(extraction: dict[str, Any], output_dir: Path) -> dict[str, Any]:- if extraction.get("status") != "ok":- return {"status": "fallback", "textureSource": "image-only", "reason": extraction.get("reason", "texture extraction unavailable")}- records: list[dict[str, Any]] = []- for path in sorted(output_dir.rglob("*")):- if path.is_file():- record = classify_map_path(path)- record.update({"source": "local-vpk", "ipBoundary": "local-user-install-not-redistributable"})- records.append(record)- return {"status": "ok", "textureSource": "local-vpk", "assets": records}---def map_assets_to_reference_pbr(records: list[dict[str, Any]]) -> dict[str, Any]:- channels: dict[str, dict[str, Any]] = {}- for record in records:- map_class = record.get("mapClass")- if map_class in {"albedo", "normal", "roughness", "metalness", "height", "ao", "mask"}:- channels.setdefault(str(map_class), dict(record))- elif map_class == "packed":- for channel, packed_channel in record.get("packedChannels", {}).items():- channels.setdefault(channel, {"path": record.get("path"), "source": record.get("source", "local-vpk"), "derived": True, "packedChannel": packed_channel, "colorSpace": "linear", "uvOrientation": record.get("uvOrientation", "standard")})- missing = [channel for channel in ("albedo", "normal", "roughness", "metalness") if channel not in channels]- if "ao" not in channels:- channels["ao"] = {"derived": True, "from": "normal-or-geometry", "confidence": 0.25}- return {"maps": channels, "missingRequired": missing, "complete": not missing}---def validate_route_requirements(manifest: dict[str, Any], *, allow_fallback: bool = False) -> dict[str, Any]:- result = dict(manifest)- route = result.get("route")- tier = result.get("exactnessTier")- if route == "reference-projection":- camera = result.get("camera", {})- projection = result.get("projection", {})- has_camera = camera.get("status") == "solved" or bool(camera.get("referenceCamera"))- has_delit = bool(result.get("deLitAlbedo") or projection.get("deLitSource"))- if not (has_camera and has_delit):- if allow_fallback:- result["route"] = "procedural-finish"- result["state"] = "fallback"- result.setdefault("warnings", []).append("projection-evidence-unavailable; procedural fallback selected")- else:- result["state"] = "request-input"- return result- if route == "authored-texture":- assets = result.get("assets", {}).get("records", []) if isinstance(result.get("assets"), dict) else []- channels = {item.get("mapClass") for item in assets if isinstance(item, dict)}- if not {"albedo", "normal"}.issubset(channels) or not ({"roughness", "packed"} & channels):- result["state"] = "request-input" if tier == "exact-texture" else "fallback"- if tier == "exact-texture" and route != "authored-texture":- result["state"] = "request-input"- return resultdiff --git a/forge/stage1_intake/cs2_manifest.py b/forge/stage1_intake/cs2_manifest.pydeleted file mode 100644index 591c0c5..0000000--- a/forge/stage1_intake/cs2_manifest.py+++ /dev/null@@ -1,230 +0,0 @@-#!/usr/bin/env python3-from __future__ import annotations--import argparse-import json-import os-import sys-import tempfile-from pathlib import Path-from typing import Any, Final--from forge.stage1_intake.check_reference_admission import check_admission-from forge.stage1_intake.cs2_foundation import enrich_manifest_with_metadata, normalize_cs2_metadata, resolve_identity-from forge.stage1_intake.cs2_review_contract import build_review_scene-from forge.stage1_intake.detect_cs2 import detect_cs2_signals-from forge.stage1_intake.probe_image import probe--SCHEMA_VERSION: Final[int] = 1-SUPPORTED_FAMILIES: Final[frozenset[str]] = frozenset({"knife"})-UNSUPPORTED_FAMILIES: Final[frozenset[str]] = frozenset(- {"pistol", "rifle", "smg", "sniper", "heavy", "glove"}-)-# Knife subtypes that have a dedicated geometry adapter. A subtype absent here is-# `unsupported-subtype`, never silently routed through another subtype's tree.-KNIFE_SUBTYPES: Final[frozenset[str]] = frozenset(- {"karambit", "butterfly", "bayonet", "m9", "flip", "gut", "falchion", "bowie", "navaja",- "talon", "classic"}-)-ROUTES: Final[frozenset[str]] = frozenset(- {"reference-projection", "authored-texture", "procedural-finish"}-)-TIERS: Final[frozenset[str]] = frozenset(- {"image-only", "metadata-assisted", "exact-texture"}-)-STATES: Final[frozenset[str]] = frozenset(- {"proceed", "request-input", "fallback", "rejected", "unsupported-family", "unsupported-subtype"}-)---def build_classification_record(- item_family: str,- subtype: str | None,- confidence: float,- evidence_refs: list[str],- *,- provider: str = "offline-fixture",- version: str = "1",- timeout: bool = False,-) -> dict[str, Any]:- if item_family not in SUPPORTED_FAMILIES | UNSUPPORTED_FAMILIES:- raise ValueError(f"unsupported item family label: {item_family}")- if not 0.0 <= confidence <= 1.0:- raise ValueError("classification confidence must be between 0 and 1")- return {- "itemFamily": item_family,- "subtype": subtype,- "confidence": round(confidence, 4),- "evidenceRefs": list(evidence_refs),- "provider": provider,- "version": version,- "timedOut": timeout,- }---def _classification_error(record: Any) -> str | None:- if not isinstance(record, dict):- return "authoritative classification record is required"- family = record.get("itemFamily")- confidence = record.get("confidence")- refs = record.get("evidenceRefs")- if not isinstance(family, str) or family not in SUPPORTED_FAMILIES | UNSUPPORTED_FAMILIES:- return "classification itemFamily is missing or invalid"- if not isinstance(confidence, (int, float)) or isinstance(confidence, bool) or not 0 <= confidence <= 1:- return "classification confidence is missing or invalid"- if not isinstance(refs, list) or not refs or not all(isinstance(item, str) and item for item in refs):- return "classification evidenceRefs must contain at least one reference"- if not isinstance(record.get("provider"), str) or not isinstance(record.get("version"), str):- return "classification provider/version are required"- return None---def _heuristic_signal(reference: Path) -> dict[str, Any]:- try:- return detect_cs2_signals(reference)- except (OSError, ValueError) as exc:- return {"is_cs2_candidate": False, "confidence": 0.0, "signals": [], "error": str(exc)}---def build_manifest(- reference: Path,- classification: dict[str, Any] | None,- *,- route: str = "reference-projection",- exactness_tier: str = "image-only",- metadata: dict[str, Any] | None = None,- texture_source: str = "image-only",- explicit_identity: dict[str, Any] | None = None,-) -> dict[str, Any]:- resolved = reference.expanduser().resolve()- technical: dict[str, Any] = probe(resolved) if resolved.exists() else {"path": str(resolved), "warnings": ["file does not exist"]}- admission: dict[str, Any] = check_admission(resolved) if resolved.exists() else {"admitted": False, "reasons": ["reference does not exist"]}- heuristic = _heuristic_signal(resolved) if resolved.exists() else {"is_cs2_candidate": False, "confidence": 0.0, "signals": []}- warnings: list[str] = []- if heuristic.get("is_cs2_candidate"):- warnings.append("heuristicSignal")- if technical.get("warnings"):- warnings.extend(str(item) for item in technical["warnings"])- if route not in ROUTES:- raise ValueError(f"unknown route {route!r}")- if exactness_tier not in TIERS:- raise ValueError(f"unknown exactness tier {exactness_tier!r}")- manifest: dict[str, Any] = {- "schemaVersion": SCHEMA_VERSION,- "state": "rejected" if not admission.get("admitted") else "request-input",- "sourceViews": [{- "role": "reference",- "path": str(resolved),- "hash": admission.get("provenance", {}).get("pHash"),- "width": technical.get("width"),- "height": technical.get("height"),- "coverage": admission.get("provenance", {}).get("foregroundCoverage"),- "duplicate": admission.get("provenance", {}).get("duplicateOfHash") is not None,- }],- "admission": admission,- "probe": technical,- "heuristicSignal": heuristic,- "exactnessTier": exactness_tier,- "route": route,- "textureSource": texture_source,- "identity": {"provenance": "unknown", "confidence": 0.0},- "finish": {"provenance": "visual-observation", "confidence": 0.0},- "assets": {"source": texture_source, "records": []},- "camera": {"status": "unknown", "provenance": "not-supplied"},- "provenance": {"reference": "user-supplied", "metadata": "not-supplied"},- "assumptions": {"float": "unknown", "paintSeed": "unknown", "hiddenRegions": "inferred"},- "confidence": {"overall": 0.0, "hiddenRegions": 0.25},- "warnings": warnings,- "extensions": {},- "reviewScene": build_review_scene("not-supplied"),- }- if not admission.get("admitted"):- manifest["rejectionReasons"] = admission.get("reasons", ["reference failed admission"])- return manifest- error = _classification_error(classification)- if error:- manifest["warnings"].append(error)- return manifest- assert isinstance(classification, dict)- family = classification["itemFamily"]- subtype = classification.get("subtype")- manifest["classification"] = classification- manifest["itemFamily"] = family- manifest["subtype"] = subtype- manifest["identity"] = {"provenance": "classification-record", "confidence": classification["confidence"]}- manifest["confidence"] = {"overall": classification["confidence"], "hiddenRegions": 0.25}- manifest["identity"] = resolve_identity(explicit_identity, metadata, classification)- if family not in SUPPORTED_FAMILIES:- manifest["state"] = "unsupported-family"- manifest["unsupportedReason"] = f"no adapter registered for {family}"- elif subtype and subtype not in KNIFE_SUBTYPES:- manifest["state"] = "unsupported-subtype"- manifest["unsupportedReason"] = f"no knife adapter fixture for {subtype}"- else:- manifest["state"] = "proceed"- manifest["componentAdapter"] = "cs2-knife-v1"- if metadata:- manifest = enrich_manifest_with_metadata(manifest, {"status": "resolved", "identity": metadata})- manifest["metadata"] = normalize_cs2_metadata(metadata)- manifest["provenance"]["metadata"] = metadata.get("source", "provided")- return manifest---def validate_manifest(manifest: dict[str, Any]) -> bool:- required = {"schemaVersion", "state", "sourceViews", "admission", "exactnessTier", "route", "warnings"}- if not required.issubset(manifest):- return False- if manifest["schemaVersion"] != SCHEMA_VERSION or manifest["state"] not in STATES:- return False- if manifest["route"] not in ROUTES or manifest["exactnessTier"] not in TIERS:- return False- if not isinstance(manifest["sourceViews"], list) or not isinstance(manifest["warnings"], list):- return False- if manifest["state"] == "proceed" and manifest.get("itemFamily") != "knife":- return False- return True---def persist_manifest(manifest: dict[str, Any], output: Path) -> None:- if not validate_manifest(manifest):- raise ValueError("refusing to persist invalid cs2-intake manifest")- output = output.expanduser().resolve()- output.parent.mkdir(parents=True, exist_ok=True)- fd, temp_name = tempfile.mkstemp(prefix=f".{output.name}.", suffix=".tmp", dir=output.parent)- try:- with os.fdopen(fd, "w", encoding="utf-8") as handle:- json.dump(manifest, handle, indent=2, ensure_ascii=False)- handle.write("\n")- handle.flush()- os.fsync(handle.fileno())- os.replace(temp_name, output)- finally:- if os.path.exists(temp_name):- os.unlink(temp_name)---def main(argv: list[str]) -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("reference", type=Path)- parser.add_argument("--classification", type=Path, help="offline authoritative classification JSON")- parser.add_argument("--out", type=Path, required=True)- parser.add_argument("--route", choices=sorted(ROUTES), default="reference-projection")- parser.add_argument("--exactness-tier", choices=sorted(TIERS), default="image-only")- parser.add_argument("--cs2-pipeline", choices=("legacy", "manifest-v1"), default="manifest-v1")- parser.add_argument("--resume", action="store_true", help="reuse a valid existing manifest at --out")- args = parser.parse_args(argv)- if args.resume and args.out.exists():- existing = json.loads(args.out.read_text(encoding="utf-8"))- if isinstance(existing, dict) and validate_manifest(existing):- print(json.dumps({"state": existing["state"], "out": str(args.out.resolve()), "resumed": True}, ensure_ascii=False))- return 0- classification = json.loads(args.classification.read_text(encoding="utf-8")) if args.classification else None- manifest = build_manifest(args.reference, classification, route=args.route, exactness_tier=args.exactness_tier)- manifest["extensions"]["compatibilityMode"] = args.cs2_pipeline- persist_manifest(manifest, args.out)- print(json.dumps({"state": manifest["state"], "out": str(args.out.resolve())}, ensure_ascii=False))- return 0 if manifest["state"] in {"proceed", "request-input", "fallback"} else 2---if __name__ == "__main__":- raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/cs2_review_contract.py b/forge/stage1_intake/cs2_review_contract.pydeleted file mode 100644index a18bfe8..0000000--- a/forge/stage1_intake/cs2_review_contract.py+++ /dev/null@@ -1,42 +0,0 @@-#!/usr/bin/env python3-from __future__ import annotations--from typing import Any--GOLDEN_THRESHOLDS = {- "silhouetteIoU": 0.85,- "aspectRatioDelta": 0.05,- "scaleDelta": 0.08,- "paintedRegionMask": 0.85,- "colorRegion": 0.80,- "patternRegion": 0.75,- "wearRegion": 0.70,-}---def build_review_scene(environment_hash: str) -> dict[str, Any]:- return {- "version": "cs2-knife-review-v1",- "camera": {"fovDegrees": 40.0, "position": [0.0, 0.0, 3.0], "target": [0.0, 0.0, 0.0]},- "objectTransform": {"position": [0.0, 0.0, 0.0], "rotation": [0.0, 0.0, 0.0], "scale": [1.0, 1.0, 1.0]},- "environmentHash": environment_hash,- "exposure": 1.0,- "toneMapping": "ACESFilmic",- "resolution": [1024, 1024],- "background": "#20242a",- "rendererVersion": "three-r170",- "thresholds": dict(GOLDEN_THRESHOLDS),- "orbitViewpoints": [{"yaw": 35.0, "pitch": 8.0}, {"yaw": -35.0, "pitch": 8.0}],- }---def validate_review_scene(scene: dict[str, Any]) -> list[str]:- required = {"version", "camera", "objectTransform", "environmentHash", "exposure", "toneMapping", "resolution", "background", "rendererVersion", "thresholds", "orbitViewpoints"}- errors = [f"missing {field}" for field in sorted(required - set(scene))]- if scene.get("version") != "cs2-knife-review-v1":- errors.append("unsupported review scene version")- if scene.get("thresholds") != GOLDEN_THRESHOLDS:- errors.append("golden thresholds do not match the frozen fixture contract")- if len(scene.get("orbitViewpoints", [])) != 2:- errors.append("exactly two orbit viewpoints are required")- return errorsdiff --git a/forge/stage1_intake/detect_cs2.py b/forge/stage1_intake/detect_cs2.pydeleted file mode 100644index 56995d8..0000000--- a/forge/stage1_intake/detect_cs2.py+++ /dev/null@@ -1,276 +0,0 @@-#!/usr/bin/env python3-"""Detect whether a reference image depicts a CS2 weapon/item.--This is a pre-analysis guard that runs BEFORE visual analysis. It uses-heuristic signals (aspect ratio, color distribution, known CS2 weapon-silhouette ratios) to route the pipeline to the CS2-specific track.--This script does NOT do visual analysis — it only reads file metadata-and performs basic image statistics. The agent's vision layer does the-real CS2 identification later in the pipeline.--Usage:- python3 detect_cs2.py <image_path> [--threshold 0.3]- python3 detect_cs2.py <image_path> --json-"""--from __future__ import annotations--import argparse-import json-import math-import struct-import sys-from pathlib import Path---# ----------------------------------------------------------------------------# Image format readers (pure stdlib, no PIL)-# -----------------------------------------------------------------------------def _png_dimensions(data: bytes) -> tuple[int, int] | None:- if data.startswith(b"\x89PNG\r\n\x1a\n") and len(data) >= 24:- return struct.unpack(">II", data[16:24])- return None---def _jpeg_dimensions(data: bytes) -> tuple[int, int] | None:- if not data.startswith(b"\xff\xd8"):- return None- idx = 2- while idx + 9 < len(data):- if data[idx] != 0xFF:- idx += 1- continue- marker = data[idx + 1]- idx += 2- if marker in {0xD8, 0xD9}:- continue- if idx + 2 > len(data):- return None- length = struct.unpack(">H", data[idx : idx + 2])[0]- if length < 2 or idx + length > len(data):- return None- if marker in {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}:- if length >= 7:- height, width = struct.unpack(">HH", data[idx + 3 : idx + 7])- return width, height- idx += length- return None---def _gif_dimensions(data: bytes) -> tuple[int, int] | None:- if data[:6] in {b"GIF87a", b"GIF89a"} and len(data) >= 10:- return struct.unpack("<HH", data[6:10])- return None---def _webp_dimensions(data: bytes) -> tuple[int, int] | None:- if len(data) < 30 or data[:4] != b"RIFF" or data[8:12] != b"WEBP":- return None- chunk = data[12:16]- if chunk == b"VP8X" and len(data) >= 30:- width = 1 + int.from_bytes(data[24:27], "little")- height = 1 + int.from_bytes(data[27:30], "little")- return width, height- if chunk == b"VP8 " and len(data) >= 30:- start = data.find(b"\x9d\x01\x2a")- if start != -1 and start + 7 <= len(data):- width, height = struct.unpack("<HH", data[start + 3 : start + 7])- return width, height- return None---def _read_dimensions(data: bytes) -> tuple[int, int] | None:- return (- _png_dimensions(data)- or _jpeg_dimensions(data)- or _gif_dimensions(data)- or _webp_dimensions(data)- )---# ----------------------------------------------------------------------------# CS2 detection heuristics-# -----------------------------------------------------------------------------# Known CS2 weapon aspect ratios (width / height) from inventory icons and-# standard workshop reference poses. These are *approximate* — a real CS2-# detection needs the agent vision layer, but these ratios help the guard-# route early.-CS2_WEAPON_ASPECT_RATIOS: dict[str, tuple[float, float]] = {- # knives — typically shown at ~15-45° angle- "knife_long": (1.8, 4.0), # Bowie, M9, Bayonet, Falchion- "knife_curved": (0.8, 1.5), # Karambit, Talon- "knife_folder": (1.2, 2.5), # Flip, Gut, Navaja- "knife_butterfly": (0.6, 1.2),# Butterfly (open)- # rifles — shown horizontally or at slight angle- "rifle_horizontal": (2.5, 5.0), # AK-47, M4A4, AWP- # pistols — shown at ~20-45° angle- "pistol_angle": (1.0, 2.0), # Glock, USP, Deagle, AK pistol- # gloves — shown as pair or single- "gloves": (0.8, 1.5),-}---def _aspect_in_cs2_ranges(aspect: float) -> list[str]:- """Return list of CS2 weapon categories whose aspect ratio matches."""- matches = []- for category, (lo, hi) in CS2_WEAPON_ASPECT_RATIOS.items():- if lo <= aspect <= hi:- matches.append(category)- return matches---def _color_energy(data: bytes, sample_points: int = 200) -> dict[str, float]:- """Sample raw byte energy at evenly-spaced points to detect dominant color ranges.-- This is a VERY rough heuristic — it reads raw file bytes, not decoded- pixels. For real detection, the agent vision layer handles this.- """- if len(data) < sample_points * 4:- return {"dominant_range": "unknown", "energy": 0.0}-- step = len(data) // sample_points- r_sum = g_sum = b_sum = 0- for i in range(sample_points):- offset = i * step- if offset + 3 < len(data):- r_sum += data[offset]- g_sum += data[offset + 1]- b_sum += data[offset + 2]-- r_avg = r_sum / sample_points- g_avg = g_sum / sample_points- b_avg = b_sum / sample_points-- # Detect common CS2 backgrounds: white/grey workshop renders- if r_avg > 200 and g_avg > 200 and b_avg > 200:- dominant = "light_background"- elif r_avg < 50 and g_avg < 50 and b_avg < 50:- dominant = "dark_background"- elif abs(r_avg - g_avg) < 20 and abs(g_avg - b_avg) < 20:- dominant = "neutral_grey"- else:- dominant = "colored"-- energy = math.sqrt(r_avg**2 + g_avg**2 + b_avg**2)- return {"dominant_range": dominant, "energy": round(energy, 2)}---def detect_cs2_signals(path: Path) -> dict:- """Analyze a reference image for CS2 weapon/item detection signals.-- Returns a dict with:- - is_cs2_candidate: bool- - confidence: 0.0-1.0- - signals: list of detected signal descriptions- - weapon_categories: possible CS2 weapon categories- - dimensions: {width, height, aspectRatio}- - color_profile: dominant color range info- - note: explanation of detection limits- """- data = path.read_bytes()- dims = _read_dimensions(data)- signals: list[str] = []- score = 0.0-- # Signal 1: Aspect ratio matches known CS2 weapon profiles- if dims:- width, height = dims- aspect = width / height if height else 1.0- categories = _aspect_in_cs2_ranges(aspect)- if categories:- score += 0.3- signals.append(f"aspect_ratio_matches:{','.join(categories)}")- else:- aspect = None- categories = []-- # Signal 2: Image dimensions suggest inventory/workshop render- if dims:- w, h = dims- # CS2 inventory icons are typically 512×512 or 256×256- if w == h and w in {256, 512, 1024}:- score += 0.2- signals.append("square_format_inventory_icon")- # Workshop renders are often wide format- elif w > h and w >= 512:- score += 0.1- signals.append("wide_format_workshop_render")-- # Signal 3: Color profile suggests workshop render- color = _color_energy(data)- if color["dominant_range"] == "light_background":- score += 0.15- signals.append("light_background_workshop_style")- elif color["dominant_range"] == "neutral_grey":- score += 0.1- signals.append("neutral_background_steam_style")-- # Signal 4: File size suggests rendered image (not photo)- file_size = len(data)- if 50_000 < file_size < 5_000_000:- score += 0.05- signals.append("typical_render_file_size")-- is_cs2_candidate = score >= 0.3-- return {- "path": str(path),- "is_cs2_candidate": is_cs2_candidate,- "confidence": min(round(score, 2), 1.0),- "signals": signals,- "weapon_categories": categories,- "dimensions": {- "width": dims[0] if dims else None,- "height": dims[1] if dims else None,- "aspectRatio": round(aspect, 3) if aspect else None,- },- "color_profile": color,- "note": (- "This is a heuristic pre-analysis guard using file metadata and "- "basic byte statistics. It does NOT perform visual analysis. "- "The agent's vision layer (Step 1) performs definitive CS2 "- "identification using the M.C.M.T framework in "- "grimoire/intake/cs2_technical_analysis.md"- ),- }---# ----------------------------------------------------------------------------# CLI-# -----------------------------------------------------------------------------def main(argv: list[str]) -> int:- parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)- parser.add_argument("image", type=Path, help="Path to reference image")- parser.add_argument("--json", action="store_true", help="Output raw JSON")- parser.add_argument("--threshold", type=float, default=0.3, help="CS2 candidate threshold (default: 0.3)")- args = parser.parse_args(argv)-- if not args.image.exists():- print(json.dumps({"error": f"File not found: {args.image}"}))- return 1-- result = detect_cs2_signals(args.image)-- if args.json:- print(json.dumps(result, indent=2))- else:- status = "CS2_CANDIDATE" if result["is_cs2_candidate"] else "NON_CS2"- print(f"Status: {status}")- print(f"Confidence: {result['confidence']}")- print(f"Signals: {', '.join(result['signals']) or 'none'}")- if result["weapon_categories"]:- print(f"Weapon categories: {', '.join(result['weapon_categories'])}")- dims = result["dimensions"]- if dims["width"]:- print(f"Dimensions: {dims['width']}×{dims['height']} (aspect {dims['aspectRatio']})")- print(f"\n{result['note']}")-- return 0---if __name__ == "__main__":- sys.exit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/extract_cs2_textures.py b/forge/stage1_intake/extract_cs2_textures.pydeleted file mode 100644index 4367d53..0000000--- a/forge/stage1_intake/extract_cs2_textures.py+++ /dev/null@@ -1,126 +0,0 @@-#!/usr/bin/env python3-"""Optional exactness upgrade: extract a CS2 skin's authored paint textures from the user's own-legal install using Source2Viewer-CLI, then classify the output maps by convention. Degrades-gracefully -- every failure (no VPK, no extractor binary, subprocess error, non-zero exit) returns-a {"status": "fallback", "reason": ...} result so the pipeline can fall back to the image-only-path, never a wrong render. Extracted pixels are Valve IP: they stay in the gitignored cs2_textures/-workspace and are never committed. See grimoire/intake/cs2_texture_acquisition.md and openspec-add-cs2-item-reconstruction tasks 5.4/5.5.-"""--from __future__ import annotations--import argparse-import json-import shutil-import subprocess-import sys-from pathlib import Path--sys.path.insert(0, str(Path(__file__).resolve().parent))-import locate_cs2_vpk # noqa: E402 (sibling module, resolved via the path insert above)-from cs2_foundation import classify_map_path # noqa: E402--SOURCE2VIEWER_BINARY = "Source2Viewer-CLI"--# Filename-convention buckets for Source 2 material maps. A map that matches nothing lands in-# "other" rather than being dropped, so an unexpected naming convention is visible, not silent.-_MAP_CLASSIFIERS = (- ("color", ("_color", "_albedo", "_basecolor", "_diffuse")),- ("normal", ("_normal", "_bump", "_nrm")),- ("roughness_metalness", ("_rough", "_metal", "_orm", "_mrao", "_packed")),- ("mask", ("_mask", "_ao", "_occlusion", "_pattern", "_wear")),-)---def source2viewer_available() -> bool:- """True when the Source2Viewer-CLI binary is on PATH (it needs the .NET runtime to run)."""- return shutil.which(SOURCE2VIEWER_BINARY) is not None---def run_source2viewer(vpk: Path, out_dir: Path, filter_glob: str | None = None) -> subprocess.CompletedProcess:- """Wrap the Source2Viewer-CLI extraction call. Raises FileNotFoundError if the binary is- absent; returns the CompletedProcess otherwise (caller inspects returncode)."""- cmd = [SOURCE2VIEWER_BINARY, "-i", str(vpk), "-o", str(out_dir), "-d", "-e", "vtex_c"]- if filter_glob:- cmd += ["-f", filter_glob]- return subprocess.run(cmd, capture_output=True, text=True)---def classify_extracted_maps(out_dir: Path) -> dict[str, list[str]]:- """Bucket the files under out_dir into color / normal / roughness_metalness / mask / other by- filename convention."""- buckets: dict[str, list[str]] = {name: [] for name, _ in _MAP_CLASSIFIERS}- buckets["other"] = []- if not out_dir.is_dir():- return buckets- for path in sorted(out_dir.rglob("*")):- if not path.is_file():- continue- lower = path.name.lower()- for name, suffixes in _MAP_CLASSIFIERS:- if any(token in lower for token in suffixes):- buckets[name].append(str(path))- break- else:- buckets["other"].append(str(path))- return buckets---def build_asset_records(out_dir: Path) -> list[dict]:- records = []- for path in sorted(out_dir.rglob("*")):- if path.is_file():- record = classify_map_path(path)- record.update({"source": "local-vpk", "ipBoundary": "local-user-install-not-redistributable"})- records.append(record)- return records---def extract(out_dir: Path, vpk: Path | None, roots: list[Path] | None, filter_glob: str | None) -> dict:- if vpk is None:- vpk = locate_cs2_vpk.locate_vpk(roots)- if vpk is None:- return {"status": "fallback",- "reason": "no local CS2 VPK found; falling back to image-only reconstruction "- "(exact texture likeness unavailable)"}- if not source2viewer_available():- return {"status": "fallback",- "reason": f"{SOURCE2VIEWER_BINARY} not found on PATH; falling back to image-only "- "reconstruction (exact texture likeness unavailable)"}- out_dir.mkdir(parents=True, exist_ok=True)- try:- result = run_source2viewer(vpk, out_dir, filter_glob)- except OSError as exc:- return {"status": "fallback", "reason": f"{SOURCE2VIEWER_BINARY} failed to run ({exc}); "- "falling back to image-only reconstruction"}- if result.returncode != 0:- return {"status": "fallback",- "reason": f"{SOURCE2VIEWER_BINARY} exited {result.returncode}: "- f"{(result.stderr or '').strip()[:200]}; falling back to image-only"}- return {"status": "ok", "vpk": str(vpk), "outDir": str(out_dir),- "maps": classify_extracted_maps(out_dir), "assets": build_asset_records(out_dir)}---def main(argv: list[str]) -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--out", type=Path, required=True, help="Output directory (gitignored cs2_textures/)")- parser.add_argument("--vpk", type=Path, help="Explicit pak01_dir.vpk path (skips locating)")- parser.add_argument("--root", type=Path, action="append", dest="roots",- help="Steam root to search when --vpk is omitted (repeatable)")- parser.add_argument("--filter", dest="filter_glob", help="Source2Viewer -f filter, e.g. a paint kit name")- parser.add_argument("--json", action="store_true", help="Emit a JSON result object")- args = parser.parse_args(argv)-- result = extract(args.out.expanduser(), args.vpk, args.roots, args.filter_glob)- if args.json:- print(json.dumps(result, indent=2))- elif result["status"] == "ok":- print(f"extracted to {result['outDir']}")- else:- print(result["reason"], file=sys.stderr)- return 0 if result["status"] == "ok" else 1---if __name__ == "__main__":- raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/fetch_cs2_metadata.py b/forge/stage1_intake/fetch_cs2_metadata.pydeleted file mode 100644index a9e7cd0..0000000--- a/forge/stage1_intake/fetch_cs2_metadata.py+++ /dev/null@@ -1,147 +0,0 @@-#!/usr/bin/env python3-"""Resolve CS2 skin metadata (paint index, float range, rarity, CDN image) from the CSGO-API-skins index -- an optional exactness upgrade over the image-only default. Never guesses: a-no-match or an ambiguous multi-match is an error, not a silent pick. See-grimoire/intake/cs2_texture_acquisition.md and openspec add-cs2-item-reconstruction task 5.2.--The index is the public CSGO-API `skins.json` shape: a list of records like- {"name": "Karambit | Doppler (Phase 2)", "weapon": {"name": "Karambit"},- "paint_index": 419, "min_float": 0.0, "max_float": 0.08,- "rarity": {"name": "Covert"}, "image": "https://.../419.png"}-Load it locally with --index-file (no network) or fetch it with --index-url.-"""--from __future__ import annotations--import argparse-import json-import sys-import urllib.request-from pathlib import Path---def load_index(index_file: Path | None, index_url: str | None) -> list[dict]:- if index_file is not None:- data = json.loads(index_file.expanduser().read_text(encoding="utf-8"))- elif index_url is not None:- with urllib.request.urlopen(index_url, timeout=30) as response: # noqa: S310 (user-supplied trusted URL)- data = json.loads(response.read().decode("utf-8"))- else:- raise ValueError("provide --index-file or --index-url")- if isinstance(data, dict): # some CSGO-API mirrors key by id- data = list(data.values())- if not isinstance(data, list):- raise ValueError("index must be a JSON list (or id-keyed object) of skin records")- return [record for record in data if isinstance(record, dict)]---def _weapon_name(record: dict) -> str:- weapon = record.get("weapon")- if isinstance(weapon, dict):- return str(weapon.get("name") or "")- return str(weapon or "")---def _rarity_name(record: dict) -> str:- rarity = record.get("rarity")- if isinstance(rarity, dict):- return str(rarity.get("name") or "")- return str(rarity or "")---def match_records(records: list[dict], weapon: str, skin: str, phase: str | None,- paint_index: int | None = None) -> list[dict]:- weapon_l, skin_l = weapon.lower(), skin.lower()- phase_l = phase.lower() if phase else None- matches = []- for record in records:- name_l = str(record.get("name") or "").lower()- if _weapon_name(record).lower() != weapon_l:- continue- if skin_l not in name_l:- continue- if phase_l is not None and phase_l not in name_l:- continue- if paint_index is not None and str(record.get("paint_index")) != str(paint_index):- continue- matches.append(record)- return matches---def to_metadata(record: dict, source: str | None = None) -> dict:- metadata = {- "name": record.get("name"),- "weapon": _weapon_name(record),- "paintIndex": record.get("paint_index"),- "minFloat": record.get("min_float"),- "maxFloat": record.get("max_float"),- "floatRange": {"min": record.get("min_float"), "max": record.get("max_float")},- "rarity": _rarity_name(record),- "imageUrl": record.get("image"),- }- if source:- metadata["source"] = source- metadata["provenance"] = {"kind": "metadata-index", "source": source or "unspecified"}- return metadata---def main(argv: list[str]) -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--weapon", required=True, help="Weapon name, e.g. 'Karambit'")- parser.add_argument("--skin", required=True, help="Skin/paint kit name substring, e.g. 'Doppler'")- parser.add_argument("--phase", help="Disambiguating phase substring, e.g. 'Phase 2' or 'Emerald'")- parser.add_argument("--paint-index", type=int, dest="paint_index",- help="Exact paint_index to disambiguate when names collide (e.g. CSGO-API lists "- "every Doppler phase as the same name; --paint-index 419 picks Phase 2).")- parser.add_argument("--index-file", type=Path, help="Local CSGO-API skins JSON")- parser.add_argument("--index-url", help="Remote CSGO-API skins JSON URL")- parser.add_argument("--out", type=Path, help="Write the resolved metadata JSON here")- parser.add_argument("--force", action="store_true", help="Overwrite --out if it exists")- parser.add_argument("--download-image", type=Path,- help="Directory to download the resolved CDN image into (optional)")- args = parser.parse_args(argv)-- try:- records = load_index(args.index_file, args.index_url)- except (ValueError, OSError, json.JSONDecodeError) as exc:- print(f"error: could not load skin index: {exc}", file=sys.stderr)- return 2-- matches = match_records(records, args.weapon, args.skin, args.phase, args.paint_index)- if not matches:- print(f"error: no match for weapon={args.weapon!r} skin={args.skin!r} "- f"phase={args.phase!r}; refine the query (nothing guessed)", file=sys.stderr)- return 2- if len(matches) > 1:- names = "; ".join(f"{m.get('name')} (paint_index={m.get('paint_index')})" for m in matches)- print(f"error: ambiguous match ({len(matches)}): {names}. Add --phase or --paint-index to "- "disambiguate (nothing guessed).", file=sys.stderr)- return 2-- source = str(args.index_file.expanduser().resolve()) if args.index_file else args.index_url- metadata = to_metadata(matches[0], source)-- if args.download_image and metadata.get("imageUrl"):- args.download_image.expanduser().mkdir(parents=True, exist_ok=True)- target = args.download_image.expanduser() / f"{metadata.get('paintIndex')}.png"- try:- urllib.request.urlretrieve(metadata["imageUrl"], target) # noqa: S310- metadata["imagePath"] = str(target)- except OSError as exc:- print(f"warning: image download failed ({exc}); metadata still resolved", file=sys.stderr)-- payload = json.dumps(metadata, indent=2, ensure_ascii=False) + "\n"- if args.out:- output = args.out.expanduser().resolve()- if output.exists() and not args.force:- print(f"error: {output} exists (use --force)", file=sys.stderr)- return 2- output.write_text(payload, encoding="utf-8")- print(f"wrote {output}")- else:- sys.stdout.write(payload)- return 0---if __name__ == "__main__":- raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/locate_cs2_vpk.py b/forge/stage1_intake/locate_cs2_vpk.pydeleted file mode 100644index b82be6d..0000000--- a/forge/stage1_intake/locate_cs2_vpk.py+++ /dev/null@@ -1,73 +0,0 @@-#!/usr/bin/env python3-"""Locate a local CS2 install's paks VPK (`pak01_dir.vpk`) so the optional exact-texture upgrade-can extract Valve's authored paint textures from the user's own legal copy. Best-effort and-non-fatal: returns None / {"found": false} when nothing is located, never raises -- the pipeline-falls back to the image-only path. See grimoire/intake/cs2_texture_acquisition.md and openspec-add-cs2-item-reconstruction task 5.3.-"""--from __future__ import annotations--import argparse-import json-import sys-from pathlib import Path--# CS2 (Source 2) ships the paints under game/csgo relative to the install dir.-_VPK_RELATIVE = Path("steamapps/common/Counter-Strike Global Offensive/game/csgo/pak01_dir.vpk")---def default_steam_roots() -> list[Path]:- """Per-OS default Steam library roots. Missing paths are harmless -- they just don't match."""- home = Path.home()- if sys.platform == "darwin":- return [home / "Library/Application Support/Steam"]- if sys.platform.startswith("win"):- return [Path("C:/Program Files (x86)/Steam"), Path("C:/Program Files/Steam")]- # linux / other- return [- home / ".steam/steam",- home / ".local/share/Steam",- home / ".steam/root",- ]---def locate_vpk(roots: list[Path] | None = None) -> Path | None:- """Return the first existing pak01_dir.vpk across the given (or default) Steam roots.- Dependency-injectable `roots` keeps this testable offline."""- search_roots = list(roots) if roots else default_steam_roots()- seen: set[Path] = set()- for root in search_roots:- root = Path(root)- if root in seen:- continue- seen.add(root)- vpk = root / _VPK_RELATIVE- if vpk.is_file():- return vpk- return None---def main(argv: list[str]) -> int:- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--root", type=Path, action="append", dest="roots",- help="Steam root to search (repeatable); defaults to per-OS Steam locations")- parser.add_argument("--json", action="store_true", help="Emit a JSON result object")- args = parser.parse_args(argv)-- vpk = locate_vpk(args.roots)- found = vpk is not None- if args.json:- result = {"found": found, "path": str(vpk) if vpk else None}- if not found:- result["reason"] = "no local CS2 VPK found in the searched Steam roots"- print(json.dumps(result, indent=2))- elif found:- print(str(vpk))- else:- print("no local CS2 VPK found", file=sys.stderr)- return 0 if found else 1---if __name__ == "__main__":- raise SystemExit(main(sys.argv[1:]))diff --git a/forge/stage1_intake/probe_image.py b/forge/stage1_intake/probe_image.pyindex b550184..a823a59 100755--- a/forge/stage1_intake/probe_image.py+++ b/forge/stage1_intake/probe_image.py@@ -156,11 +156,17 @@ def probe(path: Path) -> dict:def main(argv: list[str]) -> int:parser = argparse.ArgumentParser(description=__doc__)parser.add_argument("image", type=Path)+ # --out lets a later step consume this as an artifact instead of re-probing the image itself.+ parser.add_argument("--out", type=Path, help="also write the probe JSON here")args = parser.parse_args(argv)path = args.image.expanduser().resolve()if not path.exists():parser.error(f"{path} does not exist")- print(json.dumps(probe(path), indent=2, ensure_ascii=False))+ payload = json.dumps(probe(path), indent=2, ensure_ascii=False)+ if args.out:+ args.out.expanduser().parent.mkdir(parents=True, exist_ok=True)+ args.out.expanduser().write_text(payload + "\n", encoding="utf-8")+ print(payload)return 0diff --git a/forge/stage2_spec/cs2_adapters.py b/forge/stage2_spec/cs2_adapters.pydeleted file mode 100644index 502f887..0000000--- a/forge/stage2_spec/cs2_adapters.py+++ /dev/null@@ -1,62 +0,0 @@-#!/usr/bin/env python3-from __future__ import annotations--from dataclasses import dataclass, replace-from typing import Any---@dataclass(frozen=True, slots=True)-class FamilyAdapter:- family: str- subtype: str- topology: tuple[str, ...]- painted_regions: tuple[str, ...]- material_assignments: tuple[str, ...]- feature_targets: tuple[str, ...]- attachment_rules: tuple[str, ...]- review_viewpoints: tuple[str, ...]-- def component_tree_contract(self) -> dict[str, Any]:- return {"family": self.family, "subtype": self.subtype, "topology": self.topology, "paintedRegions": self.painted_regions, "materialAssignments": self.material_assignments, "featureTargets": self.feature_targets, "attachmentRules": self.attachment_rules, "reviewViewpoints": self.review_viewpoints}---_KNIFE = FamilyAdapter(- "knife", "generic-supported", ("ground-blade", "curve-sweep", "extrude", "assembled-solid"),- ("blade-painted", "grip-painted", "guard-bare-metal", "pommel-bare-metal"),- ("skin-finish", "substrate"),- ("silhouette", "blade-edge-spine", "grip", "guard-quillon", "fastener", "pommel"),- ("guard-to-blade", "grip-to-guard", "pommel-to-grip"),- ("reference", "orbit-left", "orbit-right"),-)-SUPPORTED_KNIFE_SUBTYPES = frozenset({"karambit", "butterfly", "bayonet", "m9", "flip", "gut", "falchion", "bowie", "navaja", "talon", "classic"})--# A pistol is not a knife with different proportions: it is a two-body assembly (slide riding a-# frame) with a through-hole in the trigger guard, an internal mechanism the shell may reveal,-# and controls that stand proud of the broad faces. It gets its own tree rather than the knife-# tree with renamed parts.-_PISTOL = FamilyAdapter(- "pistol", "generic-supported",- ("extrude-traced-outline", "outline-with-hole", "assembled-solid", "revolve"),- ("slide-painted", "frame-painted", "magazine-painted", "grip-panel-painted",- "breech-bare-metal", "barrel-bare-metal", "controls-bare-polymer"),- ("skin-finish", "substrate", "translucent-shell", "internal-mechanism"),- ("silhouette", "slide-frame-parting-line", "ejection-port", "sights",- "trigger-and-safety-blade", "trigger-guard-loop", "grip-rake-and-panel",- "magazine-extension", "pin-and-control-placement", "muzzle-and-barrel"),- ("slide-to-frame", "magazine-to-magwell", "trigger-to-pin",- "grip-panel-to-frame", "internals-inside-shell"),- ("reference", "orbit-left", "orbit-right", "muzzle-on", "top-down"),-)-SUPPORTED_PISTOL_SUBTYPES = frozenset({"glock-18"})--_ADAPTERS = {"knife": (_KNIFE, SUPPORTED_KNIFE_SUBTYPES), "pistol": (_PISTOL, SUPPORTED_PISTOL_SUBTYPES)}---def get_family_adapter(family: str, subtype: str | None = None) -> FamilyAdapter:- entry = _ADAPTERS.get(family)- if entry is None:- raise ValueError(f"unsupported-family: {family}")- adapter, supported = entry- if subtype and subtype not in supported:- raise ValueError(f"unsupported-subtype: {subtype}")- return adapter if subtype is None else replace(adapter, subtype=subtype)diff --git a/forge/tests/test_cs2_foundation.py b/forge/tests/test_cs2_foundation.pydeleted file mode 100644index 5f34411..0000000--- a/forge/tests/test_cs2_foundation.py+++ /dev/null@@ -1,134 +0,0 @@-from __future__ import annotations--import unittest-from pathlib import Path--from forge.stage1_intake.cs2_foundation import (- classify_map_path,- enrich_manifest_with_metadata,- normalize_cs2_metadata,- map_assets_to_reference_pbr,- resolve_identity,- validate_route_requirements,-)-from forge.stage1_intake.cs2_review_contract import (- GOLDEN_THRESHOLDS,- build_review_scene,- validate_review_scene,-)-from forge.stage2_spec.cs2_adapters import get_family_adapter-from forge.stage2_spec.new_pre_spec_assessment import make_payload-from forge.stage2_spec.new_sculpt_spec import apply_cs2_manifest_evidence, apply_cs2_template, make_spec-from forge.stage2_spec.validate_sculpt_spec import validate_cs2_contract---class IdentityFoundationTests(unittest.TestCase):- def test_explicit_metadata_wins_over_resolved_and_classification(self) -> None:- result = resolve_identity(- {"itemName": "Karambit | Fade", "source": "user"},- {"itemName": "Karambit | Doppler", "source": "index"},- {"itemFamily": "knife", "subtype": "karambit", "confidence": 0.9},- )- self.assertEqual(result["status"], "resolved")- self.assertEqual(result["identity"]["itemName"], "Karambit | Fade")- self.assertEqual(result["provenance"], "explicit-user-metadata")-- def test_ambiguous_metadata_preserves_candidates(self) -> None:- result = resolve_identity(- None,- {"status": "ambiguous", "candidates": [{"name": "A"}, {"name": "B"}]},- {"itemFamily": "knife", "confidence": 0.9},- )- self.assertEqual(result["status"], "ambiguous")- self.assertEqual(len(result["candidates"]), 2)-- def test_missing_float_seed_and_hidden_view_are_explicit_approximations(self) -> None:- normalized = normalize_cs2_metadata({"name": "Karambit | Fade"})- self.assertTrue(normalized["approximations"]["float"]["approximated"])- self.assertTrue(normalized["approximations"]["paintSeed"]["approximated"])- self.assertEqual(normalized["approximations"]["hiddenRegions"]["confidence"], 0.25)-- def test_manifest_enrichment_keeps_image_only_tier(self) -> None:- manifest = {"exactnessTier": "image-only", "provenance": {}, "warnings": []}- enriched = enrich_manifest_with_metadata(manifest, {"status": "no-match"})- self.assertEqual(enriched["exactnessTier"], "image-only")- self.assertEqual(enriched["metadataResolution"]["status"], "no-match")- self.assertIn("metadata-unavailable", enriched["warnings"])---class TextureFoundationTests(unittest.TestCase):- def test_map_classifier_maps_independent_channels(self) -> None:- self.assertEqual(classify_map_path(Path("knife_color.png"))["mapClass"], "albedo")- self.assertEqual(classify_map_path(Path("knife_normal.png"))["mapClass"], "normal")- packed = classify_map_path(Path("knife_orm.png"))- self.assertEqual(packed["mapClass"], "packed")- self.assertEqual(packed["packedChannels"], {"roughness": "r", "metalness": "g", "ao": "b"})-- def test_packed_and_direct_assets_map_to_independent_pbr_channels(self) -> None:- result = map_assets_to_reference_pbr([- {"mapClass": "albedo", "path": "a.png"},- {"mapClass": "normal", "path": "n.png"},- {"mapClass": "packed", "path": "orm.png", "packedChannels": {"roughness": "r", "metalness": "g", "ao": "b"}},- ])- self.assertTrue(result["complete"])- self.assertTrue(result["maps"]["roughness"]["derived"])- self.assertEqual(result["maps"]["metalness"]["packedChannel"], "g")-- def test_projection_requires_camera_and_delit_unless_fallback(self) -> None:- missing = validate_route_requirements(- {"route": "reference-projection", "exactnessTier": "image-only"}- )- self.assertEqual(missing["state"], "request-input")- fallback = validate_route_requirements(- {"route": "reference-projection", "exactnessTier": "image-only"},- allow_fallback=True,- )- self.assertEqual(fallback["route"], "procedural-finish")- self.assertEqual(fallback["exactnessTier"], "image-only")---class AdapterAndReviewTests(unittest.TestCase):- def test_only_knife_adapter_is_registered(self) -> None:- self.assertEqual(get_family_adapter("knife", "karambit").family, "knife")- with self.assertRaises(ValueError):- get_family_adapter("rifle", "ak47")-- def test_review_scene_is_versioned_and_thresholds_are_frozen(self) -> None:- scene = build_review_scene("fixture-sha256")- self.assertEqual(scene["version"], "cs2-knife-review-v1")- self.assertEqual(scene["environmentHash"], "fixture-sha256")- self.assertEqual(GOLDEN_THRESHOLDS["silhouetteIoU"], 0.85)- self.assertEqual(validate_review_scene(scene), [])-- def test_manifest_evidence_reaches_assessment_and_spec(self) -> None:- manifest = {- "schemaVersion": 1,- "state": "proceed",- "itemFamily": "knife",- "subtype": "karambit",- "route": "procedural-finish",- "exactnessTier": "metadata-assisted",- "confidence": {"overall": 0.9},- "provenance": {"reference": "fixture"},- "warnings": ["paintSeed-approximated"],- }- assessment = make_payload("Karambit | Fade", None, "ultra-complex", True, manifest)- self.assertEqual(assessment["preSpecAssessment"]["objectClass"]["itemFamily"], "knife")- spec = make_spec("Karambit | Fade", None)- apply_cs2_template(spec)- apply_cs2_manifest_evidence(spec, manifest)- self.assertEqual(spec["cs2Intake"]["exactnessTier"], "metadata-assisted")- self.assertEqual(spec["materials"][0]["route"], "procedural-finish")-- def test_validator_rejects_invalid_exactness_route_pair(self) -> None:- errors: list[str] = []- validate_cs2_contract(- {"cs2Intake": {"itemFamily": "knife", "route": "procedural-finish", "exactnessTier": "exact-texture"}},- errors,- [],- )- self.assertTrue(any("cannot claim exact-texture" in error for error in errors))---if __name__ == "__main__":- unittest.main()diff --git a/forge/tests/test_cs2_manifest.py b/forge/tests/test_cs2_manifest.pydeleted file mode 100644index a351ccd..0000000--- a/forge/tests/test_cs2_manifest.py+++ /dev/null@@ -1,81 +0,0 @@-from __future__ import annotations--import json-import struct-import tempfile-import unittest-import zlib-from pathlib import Path--from forge.stage1_intake.cs2_manifest import (- build_classification_record,- build_manifest,- persist_manifest,- validate_manifest,-)---def write_png(path: Path, width: int = 128, height: int = 128) -> None:- rows = []- for y in range(height):- row = bytearray()- for x in range(width):- value = 40 if 28 <= x < 100 and 12 <= y < 116 else 240- row.extend((value, value, value))- rows.append(b"\x00" + bytes(row))- raw = b"".join(rows)-- def chunk(kind: bytes, payload: bytes) -> bytes:- return struct.pack(">I", len(payload)) + kind + payload + struct.pack(">I", zlib.crc32(kind + payload) & 0xFFFFFFFF)-- payload = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)- path.write_bytes(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", payload) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))---class Cs2ManifestTests(unittest.TestCase):- def test_image_only_knife_manifest_requires_authoritative_classification(self) -> None:- with tempfile.TemporaryDirectory() as directory:- reference = Path(directory) / "knife.png"- write_png(reference)- manifest = build_manifest(reference, None)- self.assertEqual(manifest["state"], "request-input")- self.assertEqual(manifest["exactnessTier"], "image-only")- self.assertTrue(validate_manifest(manifest))-- def test_classified_knife_proceeds_and_preserves_heuristic_signal(self) -> None:- with tempfile.TemporaryDirectory() as directory:- reference = Path(directory) / "knife.png"- write_png(reference)- classification = build_classification_record(- "knife", "karambit", 0.98, ["view:front:subject"], provider="offline-fixture"- )- manifest = build_manifest(reference, classification)- self.assertEqual(manifest["state"], "proceed")- self.assertEqual(manifest["itemFamily"], "knife")- self.assertEqual(manifest["route"], "reference-projection")- self.assertIn("heuristicSignal", manifest["warnings"])- self.assertTrue(validate_manifest(manifest))-- def test_unsupported_family_never_receives_knife_adapter(self) -> None:- with tempfile.TemporaryDirectory() as directory:- reference = Path(directory) / "rifle.png"- write_png(reference)- classification = build_classification_record("rifle", "ak47", 0.99, ["view:front:subject"])- manifest = build_manifest(reference, classification)- self.assertEqual(manifest["state"], "unsupported-family")- self.assertNotIn("componentAdapter", manifest)-- def test_manifest_write_is_atomic_and_round_trips(self) -> None:- with tempfile.TemporaryDirectory() as directory:- reference = Path(directory) / "knife.png"- output = Path(directory) / "cs2-intake.json"- write_png(reference)- classification = build_classification_record("knife", "karambit", 0.9, ["view:front:subject"])- manifest = build_manifest(reference, classification)- persist_manifest(manifest, output)- self.assertEqual(json.loads(output.read_text())["schemaVersion"], 1)- self.assertFalse(output.with_suffix(".json.tmp").exists())---if __name__ == "__main__":- unittest.main()diff --git a/forge/tests/test_domain_spec_contract.py b/forge/tests/test_domain_spec_contract.pynew file mode 100644index 0000000..fa9f270--- /dev/null+++ b/forge/tests/test_domain_spec_contract.py@@ -0,0 +1,79 @@+"""Base-side behaviour that a domain plugin's intake feeds into.++These two assertions used to live in forge/tests/test_cs2_foundation.py, which moved to the CS2+plugin. They stayed behind because they exercise *base* code -- `apply_cs2_template`,+`apply_cs2_manifest_evidence` and `validate_cs2_contract` are still in this checkout, pending the+raise-only spec-augmentation artifact that will let them leave. Fixtures are inline dicts rather than+built by the plugin's `cs2_foundation`, so this suite needs nothing from the plugin.+"""++from __future__ import annotations++import sys+import unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "_shared"))+sys.path.insert(0, str(ROOT / "stage2_spec"))++from new_pre_spec_assessment import make_payload # noqa: E402+from new_sculpt_spec import apply_cs2_manifest_evidence, apply_cs2_template, make_spec # noqa: E402+from validate_sculpt_spec import validate_cs2_contract # noqa: E402++# Shaped like a manifest an installed domain plugin publishes. Inline on purpose: the base must be+# testable without the plugin that normally produces this.+MANIFEST = {+ "schemaVersion": 1,+ "state": "proceed",+ "exactnessTier": "image-only",+ "route": "reference-projection",+ "identity": {"family": "knife", "subtype": "talon"},+ "sourceViews": [{"viewpoint": "reference", "hash": 1234567890, "width": 128, "height": 128}],+ "admission": {"admitted": True, "reasons": []},+ "warnings": [],+}+++class DomainEvidenceReachesTheSpec(unittest.TestCase):+ def test_manifest_evidence_reaches_the_assessment_and_the_spec(self) -> None:+ payload = make_payload("Talon Doppler", "ref.png", "ultra-complex", True, MANIFEST, False)+ assessment = payload["preSpecAssessment"]+ self.assertEqual(assessment["objectClass"]["domain"], "cs2")++ spec = make_spec("Talon Doppler", "ref.png", payload)+ apply_cs2_template(spec)+ apply_cs2_manifest_evidence(spec, MANIFEST)+ contract = spec.get("qualityContract", {})+ # The domain raises the base's floors. Slice 4 moves this to a pulled artifact with a+ # raise-only merge; until then it is an in-repo post-processor and this pins its effect.+ self.assertEqual(contract.get("qualityBar"), "ultra-complex")+ self.assertEqual(spec["preSpecAssessment"]["detailInventory"]["targetMinDetails"], 16)+++class DomainContractValidation(unittest.TestCase):+ def test_validator_rejects_an_invalid_exactness_and_route_pair(self) -> None:+ spec = {+ "cs2Intake": {+ "schemaVersion": 1,+ "state": "proceed",+ "exactnessTier": "exact-texture",+ "route": "procedural-approximation",+ "sourceViews": [],+ "admission": {"admitted": True},+ "warnings": [],+ }+ }+ errors: list[str] = []+ validate_cs2_contract(spec, errors, [])+ self.assertTrue(errors, "an exact-texture tier on a procedural route must be refused")++ def test_a_spec_with_no_domain_intake_is_left_alone(self) -> None:+ # The guard clause that keeps this validator off every generic run.+ errors: list[str] = []+ validate_cs2_contract({"preSpecAssessment": {}}, errors, [])+ self.assertEqual(errors, [])+++if __name__ == "__main__":+ unittest.main()diff --git a/forge/tests/test_pipeline.py b/forge/tests/test_pipeline.pyindex 77b6f92..24b6205 100644--- a/forge/tests/test_pipeline.py+++ b/forge/tests/test_pipeline.py@@ -954,67 +954,6 @@ class PipelineTest(unittest.TestCase):self.assertNotEqual(r.returncode, 0)self.assertIn("environment", r.stdout.lower())- def test_fetch_cs2_metadata_resolves_and_flags_ambiguity(self):- index = self.dir / "skins.json"- index.write_text(json.dumps([- {"name": "Karambit | Doppler (Phase 1)", "weapon": {"name": "Karambit"}, "paint_index": 415,- "min_float": 0.0, "max_float": 0.08, "rarity": {"name": "Covert"}, "image": "https://example.test/1.png"},- {"name": "Karambit | Doppler (Phase 2)", "weapon": {"name": "Karambit"}, "paint_index": 419,- "min_float": 0.0, "max_float": 0.08, "rarity": {"name": "Covert"}, "image": "https://example.test/2.png"},- ]))- # ambiguous without --phase- r = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",- "--index-file", index)- self.assertNotEqual(r.returncode, 0)- self.assertIn("ambiguous", r.stderr.lower())- # disambiguated with --phase- out = self.dir / "metadata.json"- r = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",- "--phase", "Phase 2", "--index-file", index, "--out", out)- self.assertEqual(r.returncode, 0, r.stderr)- record = json.loads(out.read_text())- self.assertEqual(record["paintIndex"], 419)-- def test_fetch_cs2_metadata_paint_index_disambiguates_identical_names(self):- # The real CSGO-API lists every Doppler phase under the SAME name, differing only by- # paint_index -- so --phase (a name substring) cannot pick one, but --paint-index can.- index = self.dir / "skins.json"- # paint_index is a STRING in the real CSGO-API dataset -- match must handle that- index.write_text(json.dumps([- {"name": "★ Karambit | Doppler", "weapon": {"name": "Karambit"}, "paint_index": "418",- "min_float": 0.0, "max_float": 0.08, "rarity": {"name": "Covert"}, "image": "https://example.test/418.png"},- {"name": "★ Karambit | Doppler", "weapon": {"name": "Karambit"}, "paint_index": "419",- "min_float": 0.0, "max_float": 0.08, "rarity": {"name": "Covert"}, "image": "https://example.test/419.png"},- ]))- # --phase "Phase 2" is not in these identical names at all -> no match, cannot help here- no_match = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",- "--phase", "Phase 2", "--index-file", index)- self.assertNotEqual(no_match.returncode, 0)- self.assertIn("no match", no_match.stderr.lower())- # without --phase the two collide -> ambiguous, and the error lists each paint_index to pick from- amb = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",- "--index-file", index)- self.assertNotEqual(amb.returncode, 0)- self.assertIn("paint_index=419", amb.stderr)- # --paint-index picks exactly one- out = self.dir / "meta.json"- r = run("stage1_intake/fetch_cs2_metadata.py", "--weapon", "Karambit", "--skin", "Doppler",- "--paint-index", "419", "--index-file", index, "--out", out)- self.assertEqual(r.returncode, 0, r.stderr)- self.assertEqual(str(json.loads(out.read_text())["paintIndex"]), "419")-- def test_locate_cs2_vpk_returns_not_found_when_absent(self):- r = run("stage1_intake/locate_cs2_vpk.py", "--root", self.dir, "--json")- self.assertEqual(r.returncode, 1)- self.assertFalse(json.loads(r.stdout)["found"])-- def test_extract_cs2_textures_falls_back_without_vpk_or_binary(self):- r = run("stage1_intake/extract_cs2_textures.py", "--out", self.dir / "cs2_textures", "--json")- self.assertEqual(r.returncode, 1)- result = json.loads(r.stdout)- self.assertEqual(result["status"], "fallback")- self.assertIn("no local CS2 VPK", result["reason"])-def test_cs2_textures_gitignored_and_never_tracked(self):gitignore = (SKILL / ".gitignore").read_text()self.assertIn("cs2_textures/", gitignore)diff --git a/forge/tests/test_suite_integrity.py b/forge/tests/test_suite_integrity.pyindex dbbae11..35c36a8 100644--- a/forge/tests/test_suite_integrity.py+++ b/forge/tests/test_suite_integrity.py@@ -25,12 +25,12 @@ TESTS_DIR = Path(__file__).resolve().parent# Raise this deliberately when tests are added; never lower it to make a red suite green. A drop# means tests stopped being collected, which is the failure this file exists to catch.#-# Lowered once, deliberately and with accounting: 1134 -> 1125 when the CS2 domain moved to its own-# plugin. Nine tests left this suite: 2 oracle-replay and 5 cs2_review unit tests now run in the-# plugin's standalone suite, 1 asserted a profile collection the plugin owns, and 1 needed both the-# base's append_review and the plugin's cs2_review so it could live on neither side. Relocated, not-# lost -- and the import guard above is what caught test_cs2_foundation going dark during the move.-COLLECTED_FLOOR = 1125+# Lowered deliberately, with accounting, when the CS2 domain moved to its own plugin: 1134 -> 1109.+# Everything in the gap now runs in the plugin's own suite (24 tests, standalone) except two that+# could live on neither side and were rewritten as base-side tests in test_domain_spec_contract.py.+# The import guard above is what caught test_cs2_foundation going dark mid-move -- reported as a+# synthetic loader error rather than a quietly smaller suite.+COLLECTED_FLOOR = 1109REPO_ROOT = TESTS_DIR.parents[1]