Skip to content

Rebuild the object in a reference image as a code-only, procedural, quality-gated, animation-ready Three.js model. Token-efficient image-to-3D.

feat!: pull a domain's spec recipe instead of shipping one

kokorolx28d9a907bad9
diff --git a/forge/_shared/spec_augmentation.py b/forge/_shared/spec_augmentation.py
new file mode 100644
index 0000000..86cc623
--- /dev/null
+++ b/forge/_shared/spec_augmentation.py
@@ -0,0 +1,122 @@
+"""Pull a domain's spec augmentation into a base-authored spec.
+
+The base pipeline authors a skeleton and lets the agent infer the shape from the reference. When a
+domain plugin is installed, it publishes an authoritative recipe as a workspace artifact and the base
+merges it here. The base PULLS; a plugin never writes into the base's spec (PLUGIN_CONTRACT.md §14).
+
+Three partitions, three different rules, because they carry different kinds of authority:
+
+ specSections domain-authored content. Accepted opaquely -- the base cannot validate a finish
+ recipe or a rig -- but refused for any key the base owns.
+ assessmentPatch merged into preSpecAssessment. The resolved-domain marker is refused: that is set
+ by domain resolution, never proposed by the artifact that resolution selected.
+ qualityFloors merged RAISE-ONLY. This is the security property of the whole mechanism: a plugin
+ must never be able to lower the bar it was installed to raise.
+
+BASE_OWNED is a deny-list on purpose. An allow-list would have to name every domain's sections, and
+the base naming its domains is exactly what this design exists to stop.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Final
+
+ARTIFACT_KIND: Final = "spec-augmentation-v1"
+
+BASE_OWNED: Final = frozenset({"qualityContract", "preSpecAssessment", "pipelineRouting", "sourceImage", "targetName", "localSpecSearch"})
+
+# Ordered loosest to strictest. A domain may move a tier stricter, never looser.
+TIER_ORDER: Final = ("simple", "moderate", "complex", "ultra-complex")
+
+
+class SpecAugmentationError(ValueError):
+ pass
+
+
+def _stricter_tier(current: Any, proposed: Any) -> Any:
+ if proposed not in TIER_ORDER:
+ raise SpecAugmentationError(f"unknown quality tier {proposed!r}; expected one of {', '.join(TIER_ORDER)}")
+ if current not in TIER_ORDER:
+ return proposed
+ return proposed if TIER_ORDER.index(proposed) > TIER_ORDER.index(current) else current
+
+
+def _raise_only_number(path: str, current: Any, proposed: Any, clamped: list[str]) -> Any:
+ if not isinstance(proposed, (int, float)) or isinstance(proposed, bool):
+ raise SpecAugmentationError(f"{path} must be a number, got {proposed!r}")
+ if isinstance(current, (int, float)) and not isinstance(current, bool) and proposed < current:
+ clamped.append(f"{path}: kept {current} over proposed {proposed}")
+ return current
+ return proposed
+
+
+def merge_spec_augmentation(spec: dict[str, Any], artifact: Any, *, domain_id: str | None = None) -> dict[str, Any]:
+ """Merge `artifact` into `spec` in place and return the record of what happened."""
+ if not isinstance(artifact, dict):
+ raise SpecAugmentationError("spec augmentation artifact must be a JSON object")
+ kind = artifact.get("kind")
+ if kind != ARTIFACT_KIND:
+ raise SpecAugmentationError(f"unsupported spec augmentation kind {kind!r}; this harness reads {ARTIFACT_KIND}")
+ provenance = artifact.get("provenance")
+ if not isinstance(provenance, dict) or not provenance.get("provider") or not provenance.get("version"):
+ raise SpecAugmentationError("spec augmentation must declare provenance {provider, version}")
+
+ unknown = sorted(set(artifact) - {"kind", "provenance", "specSections", "assessmentPatch", "qualityFloors"})
+ if unknown:
+ # Refused, not ignored: a typo'd partition would otherwise contribute nothing in silence.
+ raise SpecAugmentationError(f"spec augmentation has unknown key(s) {unknown}")
+
+ clamped: list[str] = []
+
+ sections = artifact.get("specSections") or {}
+ if not isinstance(sections, dict):
+ raise SpecAugmentationError("specSections must be an object")
+ for key, value in sections.items():
+ if key in BASE_OWNED:
+ raise SpecAugmentationError(f"specSections may not set the base-owned key {key!r}")
+ spec[key] = value
+
+ patch = artifact.get("assessmentPatch") or {}
+ if not isinstance(patch, dict):
+ raise SpecAugmentationError("assessmentPatch must be an object")
+ pre = spec.setdefault("preSpecAssessment", {})
+ for key, value in patch.items():
+ if key == "objectClass" and isinstance(value, dict):
+ if "domain" in value:
+ raise SpecAugmentationError("assessmentPatch may not set objectClass.domain; the base sets it from domain resolution")
+ pre.setdefault("objectClass", {}).update(value)
+ elif isinstance(value, dict):
+ pre.setdefault(key, {}).update(value)
+ else:
+ pre[key] = value
+ if domain_id:
+ pre.setdefault("objectClass", {})["domain"] = domain_id
+
+ floors = artifact.get("qualityFloors") or {}
+ if not isinstance(floors, dict):
+ raise SpecAugmentationError("qualityFloors must be an object")
+ contract = spec.setdefault("qualityContract", {})
+ for key, value in floors.items():
+ if key == "qualityBar":
+ contract["qualityBar"] = _stricter_tier(contract.get("qualityBar"), value)
+ elif key == "targetMinDetails":
+ inv = pre.setdefault("detailInventory", {})
+ inv["targetMinDetails"] = _raise_only_number("targetMinDetails", inv.get("targetMinDetails"), value, clamped)
+ elif key == "minimumSpecDepth":
+ if not isinstance(value, dict):
+ raise SpecAugmentationError("qualityFloors.minimumSpecDepth must be an object")
+ depth = contract.setdefault("minimumSpecDepth", {})
+ for sub, proposed in value.items():
+ depth[sub] = _raise_only_number(f"minimumSpecDepth.{sub}", depth.get(sub), proposed, clamped)
+ else:
+ raise SpecAugmentationError(f"qualityFloors has unknown key {key!r}")
+
+ record = {
+ "kind": kind,
+ "provider": provenance["provider"],
+ "version": provenance["version"],
+ "sections": sorted(sections),
+ "clamped": clamped,
+ }
+ spec["specAugmentation"] = record
+ return record
diff --git a/forge/_shared/workflow_state.py b/forge/_shared/workflow_state.py
index bb21db5..800e68f 100644
--- a/forge/_shared/workflow_state.py
+++ b/forge/_shared/workflow_state.py
@@ -35,7 +35,9 @@ SETUP_STEPS: Final = (
"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"),
+ ("spec-authoring",
+ "python3 forge/stage2_spec/new_sculpt_spec.py \"<name>\" --image {reference} --assessment assessment.json"
+ " --augmentation spec-augmentation.json --domain {profile} --out object-sculpt-spec.json"),
(
"material-evidence",
"python3 forge/stage1_intake/material_region_analysis.py --manifest material-regions.json --out-dir material-evidence --out material-analysis.json"
@@ -115,7 +117,7 @@ def new_state(
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]
+ setup = [_step(sid, cmd.replace("{profile}", profile), scope="setup") for sid, cmd in SETUP_STEPS]
pass_steps = list(PASS_STEPS)
if domain is not None:
setup = _splice(setup, domain.get("setupSteps"), domain.get("setupAnchorBefore"), profile, scope="setup")
diff --git a/forge/stage2_spec/new_sculpt_spec.py b/forge/stage2_spec/new_sculpt_spec.py
index d42ecfb..a44ce71 100755
--- a/forge/stage2_spec/new_sculpt_spec.py
+++ b/forge/stage2_spec/new_sculpt_spec.py
@@ -10,6 +10,7 @@ import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "_shared"))
+from spec_augmentation import SpecAugmentationError, merge_spec_augmentation
from pipeline_routing import resolve_pipeline_routing
from status_banner import emit_status
@@ -1168,423 +1169,36 @@ def apply_character_template(
return spec
-# --- CS2 weapon-skin finish profile (image-first Tier 1) ---------------------
-# Each finish style maps to a PBR recipe. View-dependent finishes (anodized /
-# anodized-multicolored, e.g. Doppler) need a low roughness + high metalness +
-# strong environment reflection or they render muddy; see
-# grimoire/build/cs2_finishes.md and grimoire/intake/cs2_texture_acquisition.md.
-CS2_DOMAIN_ID = "cs2"
-CS2_FINISH_STYLES = [
- "solid", "hydrographic", "anodized", "spray-paint",
- "anodized-multicolored", "custom-paint-job", "patina", "gunsmith",
-]
-CS2_FINISH_PROFILES = {
- "solid": {"baseColor": "#7a4b2b", "metalness": 0.15, "roughness": 0.55, "clearcoat": 0.0, "env": 0.9, "viewDependent": False,
- "pattern": "flat", "bands": [
- {"id": "macro", "frequency": 1.0, "amplitude": 0.05, "role": "near-uniform lacquer color"},
- {"id": "meso", "frequency": 8.0, "amplitude": 0.03, "role": "faint brush-out streaks"},
- {"id": "micro", "frequency": 40.0, "amplitude": 0.02, "role": "edge-wear scratches under grazing light"},
- ]},
- "hydrographic": {"baseColor": "#5b6357", "metalness": 0.20, "roughness": 0.50, "clearcoat": 0.10, "env": 1.0, "viewDependent": False,
- "pattern": "swirl", "bands": [
- {"id": "macro", "frequency": 3.0, "amplitude": 0.5, "role": "dip-film swirl distortion"},
- {"id": "meso", "frequency": 10.0, "amplitude": 0.15, "role": "print-pattern fine detail"},
- {"id": "micro", "frequency": 50.0, "amplitude": 0.05, "role": "edge-wear scratches under grazing light"},
- ]},
- "anodized": {"baseColor": "#3a4a9a", "metalness": 0.92, "roughness": 0.12, "clearcoat": 0.30, "env": 1.8, "viewDependent": True,
- "pattern": "brushed", "bands": [
- {"id": "macro", "frequency": 1.5, "amplitude": 0.1, "role": "dyed-metal color breakup"},
- {"id": "meso", "frequency": 20.0, "amplitude": 0.1, "role": "directional brushed-metal streaks"},
- {"id": "micro", "frequency": 70.0, "amplitude": 0.05, "role": "edge-wear scratches under grazing light"},
- ]},
- "spray-paint": {"baseColor": "#6a6a6a", "metalness": 0.10, "roughness": 0.60, "clearcoat": 0.0, "env": 0.9, "viewDependent": False,
- "pattern": "speckle", "bands": [
- {"id": "macro", "frequency": 1.0, "amplitude": 0.05, "role": "matte overspray base"},
- {"id": "meso", "frequency": 30.0, "amplitude": 0.25, "role": "overspray speckle clusters"},
- {"id": "micro", "frequency": 90.0, "amplitude": 0.1, "role": "edge-wear scratches under grazing light"},
- ]},
- "anodized-multicolored": {"baseColor": "#b0417a", "metalness": 0.95, "roughness": 0.08, "clearcoat": 0.60, "env": 2.0, "viewDependent": True,
- "pattern": "marble", "bands": [
- {"id": "macro", "frequency": 2.0, "amplitude": 0.4, "role": "broad pattern/color breakup"},
- {"id": "meso", "frequency": 14.0, "amplitude": 0.2, "role": "brushed grain / marble swirl relief"},
- {"id": "micro", "frequency": 60.0, "amplitude": 0.07, "role": "edge-wear scratches under grazing light"},
- ]},
- "custom-paint-job": {"baseColor": "#9a2b2b", "metalness": 0.20, "roughness": 0.45, "clearcoat": 0.20, "env": 1.1, "viewDependent": False,
- "pattern": "illustrative", "bands": [
- {"id": "macro", "frequency": 0.8, "amplitude": 0.6, "role": "large non-tiled artwork blocks"},
- {"id": "meso", "frequency": 6.0, "amplitude": 0.1, "role": "artwork edge detail"},
- {"id": "micro", "frequency": 40.0, "amplitude": 0.04, "role": "peel-wear scratches under grazing light"},
- ]},
- "patina": {"baseColor": "#7a6a3a", "metalness": 0.60, "roughness": 0.40, "clearcoat": 0.0, "env": 1.2, "viewDependent": False,
- "pattern": "blotch", "bands": [
- {"id": "macro", "frequency": 1.2, "amplitude": 0.35, "role": "oxidation blotch breakup"},
- {"id": "meso", "frequency": 9.0, "amplitude": 0.25, "role": "hue-shift oxidation detail"},
- {"id": "micro", "frequency": 45.0, "amplitude": 0.1, "role": "darkened edge wear under grazing light"},
- ]},
- "gunsmith": {"baseColor": "#8a7a5a", "metalness": 0.70, "roughness": 0.35, "clearcoat": 0.10, "env": 1.3, "viewDependent": False,
- "pattern": "mask-blend", "bands": [
- {"id": "macro", "frequency": 1.5, "amplitude": 0.3, "role": "custom-paint/patina mask blend"},
- {"id": "meso", "frequency": 12.0, "amplitude": 0.2, "role": "peel + oxidize transition detail"},
- {"id": "micro", "frequency": 55.0, "amplitude": 0.09, "role": "edge-wear scratches under grazing light"},
- ]},
-}
-def _cs2_wear_mask(float_value: float | None) -> dict:
- """Map a CS2 float (0.0 Factory New .. 1.0 Battle-Scarred) to wear-mask parameters. With no
- float (image-only default) approximate a light-moderate condition from the visible reference
- instead of silently guessing -- see grimoire/build/cs2_finishes.md ('Float -> wear')."""
- if float_value is None:
- return {
- "edgeWear": 0.35, "scratches": ["approximated-light-edge-scratch"], "chips": [],
- "alphaCurve": "curvature-weighted", "aoBias": 0.3, "approximated": True,
- "notes": "No float supplied: estimated apparent condition from the reference image.",
- }
- clamped = max(0.0, min(1.0, float_value))
- return {
- "edgeWear": round(0.1 + clamped * 0.8, 3),
- "scratches": ["edge-scratch"] if clamped > 0.15 else [],
- "chips": ["edge-chip"] if clamped > 0.55 else [],
- "alphaCurve": "curvature-weighted",
- "aoBias": round(0.15 + clamped * 0.25, 3),
- "approximated": False,
- "notes": f"Wear mask derived from float={clamped}.",
- }
-def _cs2_pattern_affine(paint_seed: int | None) -> dict:
- """Deterministic T2*R*S*T1 affine placement for the pattern layer, seeded by paintSeed. With
- no paintSeed (image-only default) use a fixed centered placement and report it approximated --
- never claim it matches a specific item's actual pattern (see grimoire/build/cs2_finishes.md)."""
- if paint_seed is None:
- return {
- "paintSeed": None, "affine": "T2*R*S*T1",
- "translation": [0.5, 0.5], "rotation": 0.0, "scale": [1.0, 1.0],
- "matrix": [1.0, 0.0, 0.0, 1.0, 0.5, 0.5],
- "approximated": True,
- "notes": "No paintSeed in image-first mode: deterministic default placement, reported approximated.",
- }
- rng = paint_seed & 0xFFFFFFFF
- angle = ((rng % 360) / 360.0) * 2 * math.pi
- tx = ((rng >> 8) % 1000) / 1000.0
- ty = ((rng >> 16) % 1000) / 1000.0
- scale = 0.85 + ((rng >> 24) % 30) / 100.0
- cos_a, sin_a = math.cos(angle), math.sin(angle)
- return {
- "paintSeed": paint_seed, "affine": "T2*R*S*T1",
- "translation": [round(tx, 4), round(ty, 4)], "rotation": round(angle, 4),
- "scale": [round(scale, 4), round(scale, 4)],
- "matrix": [round(cos_a * scale, 4), round(sin_a * scale, 4),
- round(-sin_a * scale, 4), round(cos_a * scale, 4),
- round(tx, 4), round(ty, 4)],
- "approximated": False,
- "notes": f"Deterministic placement from paintSeed={paint_seed}.",
- }
-# Minimal skin-name -> finish-style hints for the identity precedence resolver. Not exhaustive
-# (thousands of CS2 skins exist); a name that doesn't match falls through to vision/default.
-SKIN_NAME_FINISH_HINTS = {
- "doppler": "anodized-multicolored", "gamma doppler": "anodized-multicolored",
- "marble fade": "anodized-multicolored", "fade": "anodized",
- "damascus": "patina", "case hardened": "patina",
- "hydrographic": "hydrographic", "hydro dip": "hydrographic",
- "urban": "spray-paint", "spray": "spray-paint",
- "custom": "custom-paint-job", "gunsmith": "gunsmith",
-}
-def infer_finish_style_from_skin_name(skin_name: str) -> str | None:
- lowered = skin_name.lower()
- for keyword, style in SKIN_NAME_FINISH_HINTS.items():
- if keyword in lowered:
- return style
- return None
-
-
-def resolve_cs2_finish_style(
- descriptor_finish_style: str | None,
- skin_name: str | None,
- vision_finish_style: str | None,
- vision_confidence: float | None = None,
- vision_confidence_threshold: float = 0.55,
-) -> tuple[str, list[str]]:
- """Identity precedence: explicit descriptor > skin name (parsed) > vision inference > default.
- A low-confidence vision read is still used (never silently dropped) but flagged. Disagreements
- between sources are reported, never silently overwritten -- see design.md 'Vision inference'."""
- conflicts: list[str] = []
- skin_inferred = infer_finish_style_from_skin_name(skin_name) if skin_name else None
- candidates: list[tuple[str, str]] = []
- if descriptor_finish_style:
- candidates.append(("descriptor", descriptor_finish_style))
- if skin_inferred:
- candidates.append(("skin name", skin_inferred))
- if vision_finish_style and (vision_confidence is None or vision_confidence >= vision_confidence_threshold):
- candidates.append(("vision", vision_finish_style))
- if len(candidates) >= 2 and len({style for _, style in candidates}) > 1:
- sources = ", ".join(f"{source}={style}" for source, style in candidates)
- conflicts.append(
- f"CS2 finish style conflict: {sources} disagree; using {candidates[0][1]!r} "
- f"({candidates[0][0]} takes precedence). Confirm before implementation."
- )
- if candidates:
- return candidates[0][1], conflicts
- if vision_finish_style:
- conflicts.append(
- f"CS2 finish style {vision_finish_style!r} inferred by vision below confidence "
- f"threshold ({vision_confidence}); confirm before implementation."
- )
- return vision_finish_style, conflicts
- return "anodized-multicolored", conflicts
-def _cs2_finish_material(finish_style: str, float_value: float | None = None, paint_seed: int | None = None) -> dict:
- profile = CS2_FINISH_PROFILES[finish_style]
- base = profile["baseColor"]
- shade = _shade_hex(base, 0.8)
- bands = profile["bands"]
- return {
- "id": "skin-finish", "name": f"CS2 {finish_style} finish", "type": "standard",
- "shaderModel": "MeshPhysicalMaterial / metallic-roughness PBR",
- "baseColor": base, "color": base,
- "albedo": {"dominant": base, "secondary": [shade],
- "samplingNotes": "Image-first: estimate from the reference; report as approximated (not the exact Valve paint texture)."},
- "colorVariation": {"palette": [base, shade], "pattern": profile["pattern"], "amplitude": bands[0]["amplitude"], "heightCorrelation": 0.25},
- "textureResolution": 1024,
- "textureProjection": {"mode": "uv", "repeat": [1.0, 1.0], "anisotropy": 8,
- "texelDensityIntent": "Preserve stable blade-scale detail; do not stretch pattern with component scale."},
- "surfaceFrequencyBands": bands,
- "roughness": {"base": profile["roughness"], "variation": 0.06, "map": "independent-procedural-field",
- "localResponse": "lower roughness on worn edges, higher in recesses"},
- "metalness": {"base": profile["metalness"], "variation": 0.03},
- "clearcoat": {"base": profile["clearcoat"]},
- "clearcoatRoughness": {"base": 0.12},
- "normal": {"pattern": "derived-from-independent-height-field", "strength": 0.3, "scale": 28.0, "space": "tangent"},
- "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.35,
- "notes": "Darken guard/pommel seams and engraving recesses."},
- "wear": _cs2_wear_mask(float_value),
- "envMapIntensity": profile["env"],
- "finishStyle": finish_style,
- "viewDependent": profile["viewDependent"],
- "needsEnvironment": profile["viewDependent"],
- "patternPlacement": _cs2_pattern_affine(paint_seed),
- "shaderNotes": [
- "Use MeshPhysicalMaterial: metallic-roughness with independent map channels.",
- "View-dependent finishes require scene.environment (code-generated default is fine) + ACESFilmic tonemapping in sRGB.",
- "Never bake lighting/pattern into a single flat albedo.",
- ],
- "notes": f"{finish_style} finish recipe; see grimoire/build/cs2_finishes.md.",
- }
-_CS2_SUBSTRATE_BANDS = [
- {"id": "macro", "frequency": 2.0, "amplitude": 0.4, "role": "broad pattern/color breakup"},
- {"id": "meso", "frequency": 14.0, "amplitude": 0.2, "role": "brushed grain relief"},
- {"id": "micro", "frequency": 60.0, "amplitude": 0.07, "role": "edge-wear scratches under grazing light"},
-]
-def _cs2_substrate_material() -> dict:
- return {
- "id": "substrate", "name": "Bare metal substrate", "type": "standard",
- "shaderModel": "MeshPhysicalMaterial / metallic-roughness PBR",
- "baseColor": "#3b3b40", "color": "#3b3b40",
- "colorVariation": {"palette": ["#3b3b40", "#2b2b30"], "pattern": "flat", "amplitude": 0.05, "heightCorrelation": 0.0},
- "textureResolution": 1024,
- "textureProjection": {"mode": "uv", "repeat": [2.0, 2.0], "anisotropy": 8,
- "texelDensityIntent": "Preserve stable metal-scale detail on exposed substrate."},
- "surfaceFrequencyBands": _CS2_SUBSTRATE_BANDS,
- "roughness": {"base": 0.34, "variation": 0.08, "map": "independent-procedural-field"},
- "metalness": {"base": 1.0, "variation": 0.0},
- "ambientOcclusion": {"cavityStrength": 0.3, "contactShadowBias": 0.35},
- "envMapIntensity": 1.4,
- "notes": "Exposed metal revealed by wear on painted/anodized finishes.",
- }
-def _cs2_hidden_material() -> dict:
- """Invisible material (opacity 0) for the organizing root group -- same trick as the
- character template's 'hidden' material, so the root component's mesh never renders."""
- return {
- "id": "hidden", "name": "Hidden (root group)", "type": "standard",
- "baseColor": "#000000", "color": "#000000",
- "colorVariation": {"palette": ["#000000", "#000000"], "pattern": "flat", "amplitude": 0.0, "heightCorrelation": 0.0},
- "albedo": {"dominant": "#000000", "secondary": ["#000000"]},
- "roughness": {"base": 1.0, "variation": 0.0},
- "opacity": {"base": 0.0},
- "notes": "Root organizing group only; not a visible surface.",
- }
-def _cs2node(cid, name, primitive, position, scale, material, role, level,
- importance=0.7, local_features=None):
- """Weapon-part node. All parts parent to root with safe (non-attachment) primitives
- and names so strict-quality does not demand attachment contracts."""
- return _cnode(cid, name, primitive, "root", position, scale, material=material,
- role=role, level=level, importance=importance,
- local_features=local_features or [], evidence=["full-object"])
-CS2_KNIFE_SUBTYPES = frozenset(
- {"karambit", "butterfly", "bayonet", "m9", "flip", "gut", "falchion", "bowie", "navaja",
- "talon", "classic"}
-)
-def make_cs2_component_tree(item_family: str = "knife", subtype: str | None = None) -> list:
- if item_family != "knife":
- raise ValueError(f"unsupported CS2 family {item_family!r}; only knife is implemented")
- if subtype and subtype not in CS2_KNIFE_SUBTYPES:
- raise ValueError(f"unsupported CS2 knife subtype {subtype!r}")
- # Root is an organizing group only: use the invisible 'hidden' material (opacity 0) exactly
- # like the character template, so the generator's per-component mesh for root never renders as
- # a stray box over the weapon -- no generic generator change needed.
- root = _cnode("root", "Weapon (root)", "box", None, (0, 0, 0), (1, 1, 1),
- material="hidden", role="body", level="macro", importance=1.0, anim_role="root")
- parts = [
- _cs2node("blade", "Blade", "ground-blade", (0, 0.55, 0), (1.0, 1.0, 1.0), "skin-finish", "blade", "macro", 1.0,
- ["edge bevel highlight", "engraved pattern swirl"]),
- _cs2node("grip", "Grip", "curve-sweep", (0, -0.55, 0), (1.0, 1.0, 1.0), "skin-finish", "grip", "macro", 0.9,
- ["checkered grip relief"]),
- _cs2node("guard", "Guard", "extrude", (0, 0.0, 0), (1.0, 1.0, 1.0), "substrate", "guard", "meso", 0.7),
- _cs2node("pommel", "Pommel", "sphere", (0, -0.95, 0), (0.2, 0.2, 0.2), "substrate", "pommel", "meso", 0.6),
- _cs2node("bolster", "Bolster", "box", (0, 0.02, 0), (0.2, 0.18, 0.26), "substrate", "bolster", "meso", 0.6),
- ]
- return [root, *parts]
-def make_cs2_feature_targets() -> list:
- return [
- {"id": "cs2-silhouette", "name": "Weapon silhouette and proportions", "tier": "critical",
- "passIds": ["blockout"], "minimumScore": 0.8, "mustPass": True,
- "componentRefs": ["root", "blade", "grip"], "evidenceRefs": ["full-object"]},
- {"id": "cs2-finish-style-read", "name": "Finish style reads correctly", "tier": "critical",
- "passIds": ["material-pass"], "minimumScore": 0.75, "mustPass": True,
- "componentRefs": ["blade"], "evidenceRefs": ["full-object"]},
- {"id": "cs2-metal-response", "name": "Metal / anodized environment response", "tier": "critical",
- "passIds": ["lighting-pass"], "minimumScore": 0.75, "mustPass": True,
- "componentRefs": ["blade", "guard"], "evidenceRefs": ["full-object"]},
- {"id": "cs2-pattern-placement", "name": "Pattern placement (approximated)", "tier": "important",
- "passIds": ["material-pass"], "minimumScore": 0.65, "mustPass": False,
- "componentRefs": ["blade"], "evidenceRefs": ["full-object"]},
- {"id": "cs2-wear-read", "name": "Wear / float reads plausibly", "tier": "important",
- "passIds": ["surface-pass"], "minimumScore": 0.65, "mustPass": False,
- "componentRefs": ["blade", "grip"], "evidenceRefs": ["full-object"]},
- ]
-def apply_cs2_template(
- spec: dict,
- finish_style: str | None = None,
- *,
- skin_name: str | None = None,
- vision_finish_style: str | None = None,
- vision_confidence: float | None = None,
- float_value: float | None = None,
- paint_seed: int | None = None,
- environment_available: bool = True,
- item_family: str = "knife",
- subtype: str | None = None,
-) -> dict:
- """Seed a self-consistent image-first CS2 weapon-skin spec. Object geometry reuses the
- hard-surface path (primaryDomain=object); only the finish/material recipe is CS2-specific.
- Leaves object specs untouched unless invoked. `finish_style` is treated as the explicit
- descriptor tier; resolve_cs2_finish_style() applies identity precedence against skin_name /
- vision when finish_style is not itself given."""
- resolved_style, conflicts = resolve_cs2_finish_style(
- finish_style, skin_name, vision_finish_style, vision_confidence
- )
- if resolved_style not in CS2_FINISH_PROFILES:
- raise ValueError(f"unknown finish style {resolved_style!r}; expected one of: {', '.join(CS2_FINISH_STYLES)}")
- profile = CS2_FINISH_PROFILES[resolved_style]
- spec["componentTree"] = make_cs2_component_tree(item_family, subtype)
- spec["materials"] = [_cs2_finish_material(resolved_style, float_value, paint_seed), _cs2_substrate_material(), _cs2_hidden_material()]
- spec["featureReviewTargets"] = make_cs2_feature_targets()
- # top-level signal for the pre-render environment gate (mirrors the material value)
- spec["envMapIntensity"] = profile["env"]
- spec["cs2Finish"] = {"finishStyle": resolved_style, "viewDependent": profile["viewDependent"],
- "environment": "code-generated-default (RoomEnvironment->PMREM); user HDRI optional",
- "environmentAvailable": environment_available,
- "tier": "image-first"}
- # fill the assessment/contract so a normal validate passes; CS2 is held to the ultra-complex
- # bar, so strict-quality still requires the agent to enumerate the CS2 detail inventory first.
- pre = spec.setdefault("preSpecAssessment", {})
- if conflicts:
- unknowns = pre.setdefault("unknownsToResolveBeforeImplementation", [])
- unknowns.extend(conflict for conflict in conflicts if conflict not in unknowns)
- oc = pre.setdefault("objectClass", {})
- oc["primaryType"] = "weapon-skin"
- oc["primaryDomain"] = "object"
- oc["formLanguage"] = ["hard-surface", "bladed"]
- oc["structureKind"] = ["blade", "grip", "guard"]
- oc["motionPotential"] = ["static", "inspect-orbit"]
- oc["materialFamilies"] = ["metal", "anodized-coat" if profile["viewDependent"] else "painted-coat"]
- oc["domain"] = CS2_DOMAIN_ID
- complexity = pre.setdefault("complexity", {})
- complexity["tier"] = "ultra-complex"
- decision = pre.setdefault("specDepthDecision", {})
- decision["requiredDepth"] = "ultra-complex"
- decision["needsRepetitionSystems"] = True
- decision["needsMaterialLocalOverrides"] = True
- decision["minimumComponentLevels"] = ["macro", "meso", "micro"]
- inv = pre.setdefault("detailInventory", {})
- # CS2 skins are treated as ultra-complex: the finish/wear/hardware IS the item, so the detail
- # gate demands the ultra count (16). strict-quality then blocks code-gen until the agent
- # enumerates the identity-defining details -- it does not pass on the bare seed.
- inv["targetMinDetails"] = 16
- contract = spec.setdefault("qualityContract", {})
- contract["qualityBar"] = "ultra-complex"
- contract.setdefault("minimumSpecDepth", {}).update(
- {"macroComponents": 5, "mesoComponents": 16, "microFeatureGroups": 8,
- "materialLayers": 4, "repetitionSystems": 2, "reviewViewpoints": 5}
- )
- return spec
-def apply_cs2_manifest_evidence(spec: dict, manifest: dict) -> dict:
- intake = {
- "schemaVersion": manifest.get("schemaVersion"),
- "state": manifest.get("state"),
- "itemFamily": manifest.get("itemFamily"),
- "subtype": manifest.get("subtype"),
- "route": manifest.get("route"),
- "exactnessTier": manifest.get("exactnessTier"),
- "identity": manifest.get("identity", {}),
- "finish": manifest.get("finish", {}),
- "paintedRegions": manifest.get("paintedRegions", []),
- "unpaintedRegions": manifest.get("unpaintedRegions", []),
- "assets": manifest.get("assets", {}),
- "camera": manifest.get("camera", {}),
- "assumptions": manifest.get("assumptions", {}),
- "confidence": manifest.get("confidence", {}),
- "provenance": manifest.get("provenance", {}),
- "warnings": manifest.get("warnings", []),
- }
- spec["cs2Intake"] = intake
- spec["exactnessTier"] = manifest.get("exactnessTier")
- if isinstance(manifest.get("camera"), dict) and manifest["camera"].get("referenceCamera"):
- spec["referenceCamera"] = manifest["camera"]["referenceCamera"]
- materials = spec.get("materials", [])
- skin = next((item for item in materials if isinstance(item, dict) and item.get("id") == "skin-finish"), None)
- if isinstance(skin, dict):
- route = manifest.get("route")
- projection = skin.setdefault("textureProjection", {})
- if route == "reference-projection":
- projection["mode"] = "projective"
- projection["source"] = manifest.get("deLitAlbedo") or manifest.get("sourceImage")
- elif route == "authored-texture":
- projection["mode"] = "uv"
- reference_pbr = manifest.get("referencePbr")
- if isinstance(reference_pbr, dict):
- skin["referencePbr"] = reference_pbr
- elif route == "procedural-finish":
- projection["mode"] = "procedural"
- skin["route"] = route
- skin["exactnessTier"] = manifest.get("exactnessTier")
- skin["paintedRegions"] = manifest.get("paintedRegions", [])
- skin["unpaintedRegions"] = manifest.get("unpaintedRegions", [])
- return spec
+
def make_spec(target_name: str, image: str | None, assessment_payload: dict | None = None) -> dict:
@@ -2284,96 +1898,51 @@ def main(argv: list[str]) -> int:
parser.add_argument("target_name", help="Human-readable object name")
parser.add_argument("--image", help="Reference image path or URL")
parser.add_argument("--assessment", type=Path, help="Pre-spec assessment JSON from stage2_spec/new_pre_spec_assessment.py")
- parser.add_argument("--manifest", type=Path, help="Validated cs2-intake.json produced by stage1 intake")
parser.add_argument("--out", type=Path, help="Output JSON path")
+ parser.add_argument("--augmentation", type=Path,
+ help="spec augmentation artifact published by an installed domain plugin")
+ parser.add_argument("--domain", default=None,
+ help="resolved domain id recorded on objectClass; set by domain resolution, not by the artifact")
parser.add_argument("--force", action="store_true", help="Overwrite output file")
parser.add_argument("--character", action="store_true",
help="Use the humanoid character template (auto-enabled when the assessment primaryDomain is character/hybrid)")
parser.add_argument("--accessories", action="store_true",
help="Character template only: add the opt-in accessory set (glasses, headphones, chest "
"decal). Off by default so the baseline humanoid carries no reference-person traits.")
- parser.add_argument("--cs2", action="store_true",
- help="Use the CS2 weapon-skin finish profile (image-first; auto-enabled when the assessment objectClass.cs2 is true)")
- parser.add_argument("--finish-style", choices=CS2_FINISH_STYLES, default=None,
- help="CS2 finish style descriptor (explicit; takes precedence over --skin-name/--vision-finish-style). "
- "Falls back to anodized-multicolored if nothing else resolves it.")
- parser.add_argument("--skin-name", help="CS2 skin name, e.g. 'Karambit | Doppler' (used to infer finish style)")
- parser.add_argument("--vision-finish-style", choices=CS2_FINISH_STYLES,
- help="Finish style inferred by vision from the reference image (image-only mode)")
- parser.add_argument("--vision-confidence", type=float,
- help="Confidence (0-1) of --vision-finish-style; below threshold it is still used but flagged")
- parser.add_argument("--float", dest="cs2_float", type=float,
- help="CS2 item float (0.0 Factory New .. 1.0 Battle-Scarred); approximated from the image if omitted")
- parser.add_argument("--paint-seed", type=int, help="CS2 paint seed; deterministic default placement if omitted")
- parser.add_argument("--no-environment", action="store_true",
- help="Mark the code-generated default environment as unavailable (testing/last-resort only) "
- "-- validate_sculpt_spec.py blocks view-dependent finishes when set")
args = parser.parse_args(argv)
emit_status(None, next_command="forge/stage2_spec/new_sculpt_spec.py")
assessment = load_assessment(args.assessment)
- manifest = None
- if args.manifest:
- manifest = json.loads(args.manifest.read_text(encoding="utf-8"))
- if not isinstance(manifest, dict):
- parser.error("CS2 intake manifest must be a JSON object")
- if manifest.get("state") != "proceed":
- parser.error(f"CS2 intake is not ready for spec authoring: {manifest.get('state', 'unknown')}")
- if manifest.get("itemFamily") != "knife":
- parser.error("CS2 spec authoring currently supports only the knife family")
spec = make_spec(args.target_name, args.image, assessment)
domain = None
- cs2_marker = False
if isinstance(assessment, dict):
pre = assessment.get("preSpecAssessment", {})
oc = pre.get("objectClass", {}) if isinstance(pre, dict) else {}
domain = oc.get("primaryDomain") if isinstance(oc, dict) else None
- cs2_marker = oc.get("domain") == CS2_DOMAIN_ID if isinstance(oc, dict) else False
incoming_routing = assessment.get("pipelineRouting") if isinstance(assessment, dict) else None
incoming_classification = incoming_routing.get("classification") if isinstance(incoming_routing, dict) else None
explicit_track = "character-v1.5" if args.character or domain in {"character", "hybrid"} else None
- if explicit_track is None and (args.cs2 or cs2_marker):
- explicit_track = "weapon-v1.4"
- legacy_cs2 = manifest is not None and not isinstance(manifest.get("pipelineRouting"), dict)
- if manifest is not None and isinstance(manifest.get("pipelineRouting"), dict):
- incoming_classification = manifest["pipelineRouting"].get("classification")
- if args.character and (args.cs2 or manifest is not None) and incoming_classification is None:
- incoming_classification = {
- "kind": "weapon",
- "confidence": 1.0,
- "evidenceRefs": ["pipeline-routing:explicit:weapon-v1.4"],
- "provider": "pipeline-routing-cli",
- "version": "1",
- }
routing = None
- if explicit_track is not None or incoming_classification is not None or legacy_cs2:
+ if explicit_track is not None or incoming_classification is not None:
routing = resolve_pipeline_routing(
explicit_track=explicit_track,
classification=incoming_classification,
- legacy_cs2=legacy_cs2,
)
spec["pipelineRouting"] = routing
if routing["status"] != "resolved":
parser.error("pipeline routing requires input: " + "; ".join(routing["conflicts"]))
- if routing is not None and routing["track"] == "weapon-v1.4":
- finish_style = args.finish_style
- if finish_style is None and isinstance(assessment, dict):
- oc = assessment.get("preSpecAssessment", {}).get("objectClass", {})
- if isinstance(oc, dict) and oc.get("finishStyle") in CS2_FINISH_PROFILES:
- finish_style = oc["finishStyle"]
- apply_cs2_template(
- spec, finish_style,
- skin_name=args.skin_name,
- vision_finish_style=args.vision_finish_style,
- vision_confidence=args.vision_confidence,
- float_value=args.cs2_float,
- paint_seed=args.paint_seed,
- environment_available=not args.no_environment,
- item_family=str(manifest.get("itemFamily", "knife")) if manifest else "knife",
- subtype=str(manifest["subtype"]) if manifest and manifest.get("subtype") else None,
- )
- if manifest:
- apply_cs2_manifest_evidence(spec, manifest)
+ # A domain plugin publishes an authoritative recipe as a workspace artifact; the base pulls it
+ # here. With none installed the spec keeps the skeleton this pipeline authored and the agent
+ # infers the shape from the reference, which is what a run without a domain plugin has always
+ # done for any other object.
+ if args.augmentation is not None and args.augmentation.expanduser().is_file():
+ try:
+ artifact = json.loads(args.augmentation.expanduser().read_text(encoding="utf-8"))
+ merge_spec_augmentation(spec, artifact, domain_id=args.domain)
+ except (OSError, json.JSONDecodeError) as exc:
+ parser.error(f"cannot read spec augmentation {args.augmentation}: {exc}")
+ except SpecAugmentationError as exc:
+ parser.error(str(exc))
elif routing is not None and routing["track"] == "character-v1.5":
anatomy = None
if isinstance(assessment, dict) and isinstance(assessment.get("preSpecAssessment"), dict):
diff --git a/forge/tests/test_domain_spec_contract.py b/forge/tests/test_domain_spec_contract.py
index fa9f270..e9b140b 100644
--- a/forge/tests/test_domain_spec_contract.py
+++ b/forge/tests/test_domain_spec_contract.py
@@ -1,10 +1,12 @@
-"""Base-side behaviour that a domain plugin's intake feeds into.
+"""The base's side of the domain contract: pulling a domain's spec augmentation.
-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.
+The base authors a skeleton and lets the agent infer the shape from the reference. An installed
+domain plugin publishes an authoritative recipe as a workspace artifact, and the base merges it here.
+These tests pin the base's rules for that merge; the recipe itself belongs to whichever plugin
+publishes it, and is tested there.
+
+The rule that matters most is raise-only. A plugin is installed to raise the bar, so the merge must
+make it structurally unable to lower one.
"""
from __future__ import annotations
@@ -15,64 +17,89 @@ 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, [])
+
+from spec_augmentation import SpecAugmentationError, merge_spec_augmentation # noqa: E402
+
+
+def artifact(**parts):
+ base = {"kind": "spec-augmentation-v1", "provenance": {"provider": "testdomain", "version": "1.0.0"}}
+ base.update(parts)
+ return base
+
+
+class RaiseOnly(unittest.TestCase):
+ """A plugin may raise a floor and may never lower one."""
+
+ def test_a_lower_numeric_floor_is_clamped_not_applied(self) -> None:
+ spec = {"qualityContract": {"minimumSpecDepth": {"macroComponents": 8}}}
+ record = merge_spec_augmentation(spec, artifact(qualityFloors={"minimumSpecDepth": {"macroComponents": 5}}))
+ self.assertEqual(spec["qualityContract"]["minimumSpecDepth"]["macroComponents"], 8)
+ self.assertTrue(record["clamped"], "a clamped floor must be recorded, not silently applied")
+
+ def test_a_lower_target_min_details_is_clamped(self) -> None:
+ spec = {"preSpecAssessment": {"detailInventory": {"targetMinDetails": 20}}}
+ merge_spec_augmentation(spec, artifact(qualityFloors={"targetMinDetails": 16}))
+ self.assertEqual(spec["preSpecAssessment"]["detailInventory"]["targetMinDetails"], 20)
+
+ def test_a_looser_quality_tier_is_refused(self) -> None:
+ spec = {"qualityContract": {"qualityBar": "complex"}}
+ merge_spec_augmentation(spec, artifact(qualityFloors={"qualityBar": "moderate"}))
+ self.assertEqual(spec["qualityContract"]["qualityBar"], "complex")
+
+ def test_raising_is_allowed(self) -> None:
+ spec = {"qualityContract": {"qualityBar": "moderate", "minimumSpecDepth": {"macroComponents": 2}}}
+ merge_spec_augmentation(spec, artifact(qualityFloors={
+ "qualityBar": "ultra-complex", "minimumSpecDepth": {"macroComponents": 5}}))
+ self.assertEqual(spec["qualityContract"]["qualityBar"], "ultra-complex")
+ self.assertEqual(spec["qualityContract"]["minimumSpecDepth"]["macroComponents"], 5)
+
+
+class WhatAnArtifactMayNotDo(unittest.TestCase):
+ def test_it_may_not_set_a_base_owned_section(self) -> None:
+ with self.assertRaises(SpecAugmentationError) as ctx:
+ merge_spec_augmentation({}, artifact(specSections={"qualityContract": {"qualityBar": "simple"}}))
+ self.assertIn("base-owned", str(ctx.exception))
+
+ def test_it_may_not_set_the_resolved_domain_marker(self) -> None:
+ # The marker records which provider the base resolved. An artifact claiming it would let a
+ # plugin relabel the run as some other domain.
+ with self.assertRaises(SpecAugmentationError) as ctx:
+ merge_spec_augmentation({}, artifact(assessmentPatch={"objectClass": {"domain": "somewhere-else"}}))
+ self.assertIn("domain resolution", str(ctx.exception))
+
+ def test_an_unknown_partition_is_refused_not_ignored(self) -> None:
+ with self.assertRaises(SpecAugmentationError):
+ merge_spec_augmentation({}, artifact(qualityFlrs={}))
+
+ def test_an_unknown_floor_key_is_refused(self) -> None:
+ with self.assertRaises(SpecAugmentationError):
+ merge_spec_augmentation({}, artifact(qualityFloors={"nope": 1}))
+
+ def test_an_unsupported_artifact_kind_is_refused(self) -> None:
+ with self.assertRaises(SpecAugmentationError):
+ merge_spec_augmentation({}, {"kind": "something-else", "provenance": {"provider": "p", "version": "1"}})
+
+ def test_provenance_is_required(self) -> None:
+ with self.assertRaises(SpecAugmentationError):
+ merge_spec_augmentation({}, {"kind": "spec-augmentation-v1"})
+
+
+class WhatAnArtifactMayDo(unittest.TestCase):
+ def test_domain_sections_are_accepted_opaquely(self) -> None:
+ # The base cannot validate a finish recipe or a rig, and does not try. It only refuses keys
+ # it owns -- a deny-list, so a domain nobody has written yet needs no base change.
+ spec = {}
+ merge_spec_augmentation(spec, artifact(specSections={
+ "componentTree": [{"id": "root"}], "somethingDomainSpecific": {"anything": True}}))
+ self.assertEqual(spec["componentTree"], [{"id": "root"}])
+ self.assertEqual(spec["somethingDomainSpecific"], {"anything": True})
+
+ def test_the_base_records_which_provider_augmented_the_spec(self) -> None:
+ spec = {}
+ merge_spec_augmentation(spec, artifact(specSections={"componentTree": []}), domain_id="testdomain")
+ self.assertEqual(spec["specAugmentation"]["provider"], "testdomain")
+ self.assertEqual(spec["specAugmentation"]["version"], "1.0.0")
+ self.assertEqual(spec["preSpecAssessment"]["objectClass"]["domain"], "testdomain")
if __name__ == "__main__":
diff --git a/forge/tests/test_pipeline.py b/forge/tests/test_pipeline.py
index 24b6205..0a2c6a5 100644
--- a/forge/tests/test_pipeline.py
+++ b/forge/tests/test_pipeline.py
@@ -864,28 +864,6 @@ class PipelineTest(unittest.TestCase):
self.assertIn("createPersonModel", ts)
self.assertIn('meshes["head"]', ts)
- def test_cs2_anodized_finish_and_environment(self):
- # Author a Doppler-style (anodized-multicolored) CS2 skin, image-first.
- run("stage2_spec/new_sculpt_spec.py", "Karambit Doppler", "--cs2",
- "--finish-style", "anodized-multicolored", "--out", self.spec)
- spec = json.loads(self.spec.read_text())
- finish = next(m for m in spec["materials"] if m["id"] == "skin-finish")
- # view-dependent PBR: high metalness, low roughness, strong environment
- self.assertGreaterEqual(finish["metalness"]["base"], 0.9)
- self.assertLessEqual(finish["roughness"]["base"], 0.15)
- self.assertGreaterEqual(spec["envMapIntensity"], 1.5)
- self.assertTrue(finish["needsEnvironment"])
- # authored CS2 seed is no worse than the object baseline: normal validate passes
- self.assertEqual(run("stage2_spec/validate_sculpt_spec.py", self.spec).returncode, 0)
- # factory generates and emits the code-generated environment helper
- out = self.dir / "createCs2Model.ts"
- r = run("stage3_build/generate_threejs_factory.py", self.spec, "--out", out)
- self.assertEqual(r.returncode, 0, r.stderr)
- ts = out.read_text()
- self.assertIn("Environment", ts)
- self.assertIn("RoomEnvironment", ts)
- self.assertIn("PMREMGenerator", ts)
-
def test_cs2_track_skipped_for_objects(self):
run("stage2_spec/new_sculpt_spec.py", "Crate", "--out", self.spec)
spec = json.loads(self.spec.read_text())
@@ -908,52 +886,6 @@ class PipelineTest(unittest.TestCase):
payload = json.loads(self.assessment.read_text())
self.assertEqual(payload["preSpecAssessment"]["objectClass"]["domain"], "cs2")
- def test_cs2_defaults_to_ultra_complex(self):
- # CS2 is held to the top fidelity bar: --cs2 defaults the tier to ultra-complex
- # (targetMinDetails 16) in both the assessment and the authored spec. The domain must be
- # declared -- it is no longer inferred from the target name.
- r = run("stage2_spec/new_pre_spec_assessment.py", "Karambit | Doppler", "--cs2", "--out", self.assessment)
- self.assertEqual(r.returncode, 0, r.stderr)
- pre = json.loads(self.assessment.read_text())["preSpecAssessment"]
- self.assertEqual(pre["complexity"]["tier"], "ultra-complex")
- self.assertEqual(pre["detailInventory"]["targetMinDetails"], 16)
- run("stage2_spec/new_sculpt_spec.py", "Karambit Doppler", "--cs2", "--out", self.spec)
- spec_pre = json.loads(self.spec.read_text())["preSpecAssessment"]
- self.assertEqual(spec_pre["complexity"]["tier"], "ultra-complex")
- self.assertEqual(spec_pre["detailInventory"]["targetMinDetails"], 16)
- # an explicit lower --complexity still honors the 9 detail floor
- r2 = run("stage2_spec/new_pre_spec_assessment.py", "Bayonet skin", "--cs2",
- "--complexity", "simple", "--out", self.assessment, "--force")
- self.assertEqual(r2.returncode, 0, r2.stderr)
- low = json.loads(self.assessment.read_text())["preSpecAssessment"]
- self.assertEqual(low["detailInventory"]["targetMinDetails"], 9)
-
- def test_cs2_identity_precedence_flags_conflict(self):
- # skin name implies anodized-multicolored (Doppler); vision disagrees with patina.
- run("stage2_spec/new_sculpt_spec.py", "Item", "--cs2", "--skin-name", "Karambit Doppler",
- "--vision-finish-style", "patina", "--vision-confidence", "0.9", "--out", self.spec)
- spec = json.loads(self.spec.read_text())
- self.assertEqual(spec["cs2Finish"]["finishStyle"], "anodized-multicolored")
- unknowns = spec["preSpecAssessment"]["unknownsToResolveBeforeImplementation"]
- self.assertTrue(any("conflict" in u.lower() for u in unknowns))
-
- def test_cs2_float_and_paint_seed_drive_wear_and_placement(self):
- run("stage2_spec/new_sculpt_spec.py", "Karambit", "--cs2", "--finish-style", "patina",
- "--float", "0.7", "--paint-seed", "12345", "--out", self.spec)
- spec = json.loads(self.spec.read_text())
- finish = next(m for m in spec["materials"] if m["id"] == "skin-finish")
- self.assertFalse(finish["wear"]["approximated"])
- self.assertGreater(finish["wear"]["edgeWear"], 0.5)
- self.assertEqual(finish["patternPlacement"]["paintSeed"], 12345)
- self.assertFalse(finish["patternPlacement"]["approximated"])
-
- def test_cs2_view_dependent_finish_blocked_without_environment(self):
- run("stage2_spec/new_sculpt_spec.py", "Karambit Doppler", "--cs2",
- "--finish-style", "anodized-multicolored", "--no-environment", "--out", self.spec)
- r = run("stage2_spec/validate_sculpt_spec.py", self.spec)
- self.assertNotEqual(r.returncode, 0)
- self.assertIn("environment", r.stdout.lower())
-
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_pipeline_routing.py b/forge/tests/test_pipeline_routing.py
index dd97b22..b3bf5dc 100644
--- a/forge/tests/test_pipeline_routing.py
+++ b/forge/tests/test_pipeline_routing.py
@@ -94,8 +94,12 @@ class PipelineRoutingTests(unittest.TestCase):
self.assertEqual(assessment["pipelineRouting"]["track"], "character-v1.5")
self.assertEqual(spec["pipelineRouting"], assessment["pipelineRouting"])
- def test_weapon_and_character_routing_select_their_own_templates(self) -> None:
- for kind, expected_component in (("weapon", "blade"), ("character", "head")):
+ def test_routing_selects_a_template_only_where_the_base_owns_one(self) -> None:
+ # The base ships a character template and, deliberately, no weapon template: a weapon with
+ # no domain plugin installed gets the skeleton and the agent infers the shape from the
+ # reference, exactly as any other object does. The CS2 plugin supplies the knife recipe
+ # through a spec-augmentation artifact instead.
+ for kind, expected_component in (("weapon", "root"), ("character", "head")):
with self.subTest(kind=kind), tempfile.TemporaryDirectory() as directory:
assessment_path = Path(directory) / "assessment.json"
spec_path = Path(directory) / "spec.json"
@@ -121,25 +125,6 @@ class PipelineRoutingTests(unittest.TestCase):
component_ids = {component["id"] for component in json.loads(spec_path.read_text())["componentTree"]}
self.assertIn(expected_component, component_ids)
- def test_conflicting_cs2_and_character_flags_do_not_select_a_template(self) -> None:
- with tempfile.TemporaryDirectory() as directory:
- result = subprocess.run(
- [
- sys.executable,
- str(SKILL_ROOT / "forge/stage2_spec/new_sculpt_spec.py"),
- "Target",
- "--cs2",
- "--character",
- "--out",
- str(Path(directory) / "spec.json"),
- ],
- capture_output=True,
- text=True,
- )
-
- self.assertNotEqual(result.returncode, 0)
- self.assertIn("pipeline routing requires input", result.stderr)
-
def test_validator_rejects_unresolved_or_wrong_template_routing(self) -> None:
spec = make_spec("Target", None)
spec["pipelineRouting"] = resolve_pipeline_routing(classification=classification("hybrid"))
diff --git a/forge/tests/test_suite_integrity.py b/forge/tests/test_suite_integrity.py
index 35c36a8..2c8464a 100644
--- a/forge/tests/test_suite_integrity.py
+++ b/forge/tests/test_suite_integrity.py
@@ -30,7 +30,7 @@ TESTS_DIR = Path(__file__).resolve().parent
# 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 = 1109
+COLLECTED_FLOOR = 1112
REPO_ROOT = TESTS_DIR.parents[1]