Skip to content

Official Codebase of 3DCodeVerse

Python

Fixed parts: project-seeded src/ files no session may rewrite, never planned, measured as declared

wang Qin9ffda4984cd1
diff --git a/eval/bench/run_bench.py b/eval/bench/run_bench.py
index 2e72271f..796b919d 100644
--- a/eval/bench/run_bench.py
+++ b/eval/bench/run_bench.py
@@ -53,7 +53,13 @@ from codeverse3d.addons import select # noqa: E402
from codeverse3d.config import get_settings # noqa: E402
from codeverse3d.contracts.common import TRACK_INFO, Backends, Budget, Language, Track # noqa: E402
from codeverse3d.contracts.run import RunRecord # noqa: E402
-from codeverse3d.contracts.spec import Constraints, ReferenceImage, RunOptions, Spec # noqa: E402
+from codeverse3d.contracts.spec import ( # noqa: E402
+ Constraints,
+ FixedPart,
+ ReferenceImage,
+ RunOptions,
+ Spec,
+)
from codeverse3d.cost import run_ledger # noqa: E402
from codeverse3d.proc import exclusive, install_stop_handlers # noqa: E402
from codeverse3d.record.record import load_record # noqa: E402
@@ -79,6 +85,11 @@ class BenchPrompt(BaseModel):
references: list[str] = Field(
default_factory=list,
description="reference image paths (relative to the battery file); bench/refs/<id>/*.png|jpg are added automatically")
+ # left out of a dumped battery while empty, so every existing battery serialises as before
+ fixed_parts: list[FixedPart] = Field(
+ default_factory=list, exclude_if=lambda v: not v,
+ description="project-seeded src/ files the run must keep (Spec.fixed_parts); the project seeds them into "
+ "runs/<id>/src/ before the battery runs")
class Battery(BaseModel):
@@ -191,6 +202,7 @@ def build_spec(
budget=Budget(max_rounds=rounds, max_minutes=max_minutes),
backends=backends, tags=[tag0, battery.name, item.tier, item.category, *extra_tags, *item.tags],
options=RunOptions(variant=variant),
+ fixed_parts=list(item.fixed_parts),
)
diff --git a/eval/tests/test_bench_shared.py b/eval/tests/test_bench_shared.py
index 6682ed4d..7ab60fb0 100644
--- a/eval/tests/test_bench_shared.py
+++ b/eval/tests/test_bench_shared.py
@@ -69,3 +69,24 @@ def test_a_run_that_scored_nothing_says_so_in_its_row(tmp_path: Path) -> None:
rec.rounds = [judged, rounds[1]]
row = result_from_record(item, rec, ws)
assert row.errors == "" and (row.score_picked, row.picked_round) == (0.6, 0) # one verdict is enough
+
+
+def test_a_battery_prompt_carries_fixed_parts_into_the_spec(tmp_path):
+ """A project seeds src/ files per prompt: build_spec must hand them to the run (it builds the Spec from the
+ battery even when the workspace already holds a spec.json), and a prompt without them must serialise exactly
+ as before."""
+ import yaml
+
+ from bench.run_bench import Battery, build_spec
+ from codeverse3d.contracts.common import Backends
+
+ path = tmp_path / "b.yaml"
+ path.write_text(yaml.safe_dump({"name": "b", "track": "static_object", "language": "threejs", "prompts": [
+ {"id": "house", "prompt": "a house", "tier": "hard",
+ "fixed_parts": [{"path": "src/parts/shell.js", "name": "Shell", "bbox_min": [-1, 0, -1], "bbox_max": [1, 2, 1]}]},
+ {"id": "plain", "prompt": "a chair", "tier": "easy"}]}))
+ b = Battery.load(path)
+ spec = build_spec(b, b.prompts[0], backends=Backends(), rounds=1, max_minutes=1, tag0="t")
+ assert [f.path for f in spec.fixed_parts] == ["src/parts/shell.js"]
+ plain = build_spec(b, b.prompts[1], backends=Backends(), rounds=1, max_minutes=1, tag0="t").model_dump(mode="json")
+ assert "fixed_parts" not in plain
diff --git a/harness/codeverse3d/contracts/spec.py b/harness/codeverse3d/contracts/spec.py
index 612e4b96..e04648a5 100644
--- a/harness/codeverse3d/contracts/spec.py
+++ b/harness/codeverse3d/contracts/spec.py
@@ -6,7 +6,7 @@ from datetime import UTC, datetime
from pydantic import BaseModel, Field, model_validator
-from codeverse3d.contracts.common import TRACK_LANGUAGES, Backends, Budget, Language, Track
+from codeverse3d.contracts.common import TRACK_LANGUAGES, Backends, Budget, Language, Track, Vec3
class ReferenceImage(BaseModel):
@@ -27,6 +27,21 @@ class Constraints(BaseModel):
must_not: list[str] = Field(default_factory=list)
+class FixedPart(BaseModel):
+ """A file the PROJECT seeds into ``src/`` that no session may rewrite: measured geometry (a survey shell), the
+ data it reads, a shared library. The planner is told it is given and does not plan it; the agent imports it
+ unchanged (an edit is reverted, like a language's ``HARNESS_OWNED_SRC``); the skeleton keeps it; and when it
+ builds a part, the ``contract_fixed`` gate measures that part against ``bbox_min``/``bbox_max``."""
+
+ path: str = Field(description="workspace-relative file under src/, e.g. 'src/parts/survey_shell.js'")
+ name: str = Field(default="", description="the GLB part it builds (a child of the root, e.g. 'SurveyShell'); "
+ "'' for a data or library file")
+ export: str = Field(default="", description="what the agent imports from it, e.g. 'buildSurveyShell'")
+ bbox_min: Vec3 | None = Field(default=None, description="the built part's box, GLB frame (Y-up, +Z front), m")
+ bbox_max: Vec3 | None = None
+ note: str = Field(default="", description="one line for the planner and the agent")
+
+
class RunOptions(BaseModel):
"""Run-shape options frozen on the spec (distinct from Budget and Backends).
@@ -47,6 +62,9 @@ class Spec(BaseModel):
prompt: str
references: list[ReferenceImage] = Field(default_factory=list)
constraints: Constraints = Field(default_factory=Constraints)
+ # left out of spec.json while empty, so every spec without one serialises exactly as before
+ fixed_parts: list[FixedPart] = Field(default_factory=list, exclude_if=lambda v: not v,
+ description="project-seeded files no session may rewrite (FixedPart)")
budget: Budget = Field(default_factory=Budget)
backends: Backends = Field(default_factory=Backends)
options: RunOptions = Field(default_factory=RunOptions)
@@ -54,6 +72,16 @@ class Spec(BaseModel):
tags: list[str] = Field(default_factory=list)
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
+ @model_validator(mode="after")
+ def _fixed_parts_are_sources(self) -> Spec:
+ for f in self.fixed_parts:
+ parts = f.path.replace("\\", "/").split("/")
+ if parts[0] != "src" or ".." in parts or len(parts) < 2:
+ raise ValueError(f"fixed part {f.path!r}: must be a file under src/")
+ if (f.bbox_min is None) != (f.bbox_max is None):
+ raise ValueError(f"fixed part {f.path!r}: give both bbox_min and bbox_max, or neither")
+ return self
+
@model_validator(mode="after")
def _language_fits_track(self) -> Spec:
allowed = TRACK_LANGUAGES[self.track]
diff --git a/harness/codeverse3d/judges/rubrics/reference.yaml b/harness/codeverse3d/judges/rubrics/reference.yaml
index a42c5592..93bb7d36 100644
--- a/harness/codeverse3d/judges/rubrics/reference.yaml
+++ b/harness/codeverse3d/judges/rubrics/reference.yaml
@@ -119,6 +119,14 @@ caps:
kinds: [penetrat, intersect, overlap, collision]
cap: 0.7
measures: [interpenetration]
+ # the project's fixed parts built as declared (Spec.fixed_parts, the contract_fixed gate): a part moved,
+ # scaled or edited past the declared box is the object built wrong, not a detail
+ - id: fixed_part_violation
+ when: gate
+ gate: "contract_fixed"
+ severity: error
+ cap: 0.6
+ note: a project-fixed part is missing or not as declared
- id: missing_must_acceptance
when: acceptance
cap: 0.6
diff --git a/harness/codeverse3d/spatial/contract.py b/harness/codeverse3d/spatial/contract.py
index 6b5e158b..168054e3 100644
--- a/harness/codeverse3d/spatial/contract.py
+++ b/harness/codeverse3d/spatial/contract.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import time
+from collections.abc import Sequence
from dataclasses import dataclass
import numpy as np
@@ -16,6 +17,7 @@ from codeverse3d.contracts.artifacts import (
Severity,
)
from codeverse3d.contracts.plan import BBox, PartPlan, Plan, StaticPlan
+from codeverse3d.contracts.spec import FixedPart
from codeverse3d.conventions import (
BBOX_TOLERANCE_M,
CONTACT_GAP_M,
@@ -335,3 +337,48 @@ def check_contract(measurement: Measurement, plan: StaticPlan, *, language: str,
if not findings:
findings.append(GateFinding(gate=GATE, severity=Severity.INFO, message="all plan parts present and within tolerance"))
return GateReport.of(GATE, findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+# --------------------------------------------------------------------------- fixed parts
+FIXED_GATE = "contract_fixed"
+#: a fixed part is built by code the agent may not change, so its box must come out as declared: any face of
+#: it further than this from the declared box is an ERROR
+FIXED_TOL_M = 0.05
+
+
+def check_fixed_parts(measurement: Measurement, fixed: Sequence[FixedPart]) -> GateReport:
+ """The spec's fixed parts (``Spec.fixed_parts``) that build a part, measured in the GLB: present under
+ their name, and inside ``FIXED_TOL_M`` of the declared box. The ``contract*`` cap applies to the
+ ERRORs and they become refine tasks; a part rescaled or moved in the entry file is caught here even
+ though the read-only file itself is untouched."""
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ by_name = {to_snake(p.name): p for p in measurement.parts}
+ for f in fixed:
+ if not f.name:
+ continue
+ row = by_name.get(to_snake(f.name))
+ if row is None:
+ findings.append(GateFinding(
+ gate=FIXED_GATE, severity=Severity.ERROR, target=f.name,
+ message=f"fixed part '{f.name}' ({f.path}) is missing from the GLB",
+ fix_hint=f"import {f.export or 'its builder'} from {f.path} and add what it returns to the root, unchanged",
+ data={"kind": "fixed_part_missing"}))
+ continue
+ if f.bbox_min is None or f.bbox_max is None:
+ continue
+ lo = np.subtract(row.bbox_min, f.bbox_min)
+ hi = np.subtract(row.bbox_max, f.bbox_max)
+ worst = float(np.max(np.abs(np.concatenate([lo, hi]))))
+ if worst > FIXED_TOL_M:
+ findings.append(GateFinding(
+ gate=FIXED_GATE, severity=Severity.ERROR, target=f.name,
+ message=(f"fixed part '{f.name}' measures {fmt_vec(row.bbox_min)}..{fmt_vec(row.bbox_max)}, declared "
+ f"{fmt_vec(f.bbox_min)}..{fmt_vec(f.bbox_max)} (off by {worst:.2f} m): it was moved, scaled or edited"),
+ fix_hint=f"add what {f.export or 'its builder'} returns to the root unchanged: no transform, no "
+ "post-processing of its children; dress beside it",
+ data={"kind": "fixed_part_bbox", "off_m": round(worst, 3)}))
+ if not findings:
+ findings.append(GateFinding(gate=FIXED_GATE, severity=Severity.INFO,
+ message="fixed parts present and as declared"))
+ return GateReport.of(FIXED_GATE, findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse3d/tracks/generation.py b/harness/codeverse3d/tracks/generation.py
index 5e6547cc..ba3e1c7a 100644
--- a/harness/codeverse3d/tracks/generation.py
+++ b/harness/codeverse3d/tracks/generation.py
@@ -446,7 +446,7 @@ def run_agent_task(
shared_tree=task.shared_tree,
effort=session_effort(task),
always_writable=_always_writable(language, task),
- read_only=_read_only(language),
+ read_only=_read_only(language, ws),
**({"max_turns": turns_cap} if turns_cap > 0 else {}),
)
acc = _SessionAcc(task=task, budget=budget)
@@ -596,18 +596,20 @@ def _always_writable(language: str, task: GenerationTask) -> list[str]:
def _envelope_scope(ws: Workspace, task: GenerationTask) -> tuple[set[str] | None, list[str]]:
"""The ``only`` set for ``write_files`` (an ``edit_only`` task's files plus the always-writable ones, else ``None``) and the frozen files."""
language, _ = _spec_lang_track(ws)
- frozen = _read_only(language)
+ frozen = _read_only(language, ws)
if not task.edit_only or not task.files_hint:
return None, frozen
return {f for f in task.files_hint if f} | set(_always_writable(language, task)), frozen
-def _read_only(language: str) -> list[str]:
- """The harness-owned files of the language (scene_threejs's ``src/lib/``): every session"""
+def _read_only(language: str, ws: Workspace) -> list[str]:
+ """The harness-owned files of the language (scene_threejs's ``src/lib/``) and the spec's fixed parts: every session"""
+ spec_d = read_json_or_none(ws.spec_path) or {}
+ fixed = [str(f.get("path", "")).replace("\\", "/") for f in spec_d.get("fixed_parts") or [] if f.get("path")]
try:
- return list(HARNESS_OWNED_SRC.get(Language(language), ()))
+ return list(HARNESS_OWNED_SRC.get(Language(language), ())) + fixed
except ValueError:
- return []
+ return fixed
def generate(
diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.py
index 515b434d..805b9d89 100644
--- a/harness/codeverse3d/tracks/lifecycle.py
+++ b/harness/codeverse3d/tracks/lifecycle.py
@@ -72,7 +72,7 @@ log = logging.getLogger(__name__)
def plan_stage_inputs(spec: Spec) -> dict[str, Any]:
"""Only the spec fields the PLAN depends on: hashing the whole Spec meant that"""
- return {
+ inputs: dict[str, Any] = {
"prompt": spec.prompt,
"track": spec.track.value,
"language": spec.language.value,
@@ -81,6 +81,9 @@ def plan_stage_inputs(spec: Spec) -> dict[str, Any]:
"planner": spec.backends.planner,
"seed": spec.seed,
}
+ if spec.fixed_parts: # only when set, so every existing run's plan key stays put
+ inputs["fixed_parts"] = spec.fixed_parts
+ return inputs
def plan_stage_key(spec: Spec, track: Track) -> dict[str, Any]:
@@ -145,7 +148,17 @@ def run_stages(track: BaseTrack, ctx: RunContext, runner: StageRunner, stages: S
def _skeleton(track: BaseTrack, ctx: RunContext) -> list[str]:
+ # the project's fixed parts (Spec.fixed_parts) were seeded before the run: a language whose skeleton
+ # rewrites src/ must not replace them, and a run whose seed is missing must stop here, not later
+ fixed = {f.path: ctx.ws.root / f.path for f in ctx.spec.fixed_parts}
+ missing = [p for p, f in fixed.items() if not f.is_file()]
+ if missing:
+ raise FileNotFoundError(f"fixed parts not seeded in the workspace: {missing}")
+ kept = {p: f.read_bytes() for p, f in fixed.items()}
paths = ctx.runtime.skeleton(ctx.ws, ctx.plan)
+ for p, data in kept.items():
+ if fixed[p].read_bytes() != data:
+ fixed[p].write_bytes(data)
ctx.ws.commit("skeleton")
return [str(Path(p).relative_to(ctx.ws.root)) if Path(p).is_absolute() else str(p) for p in paths]
diff --git a/harness/codeverse3d/tracks/planner.py b/harness/codeverse3d/tracks/planner.py
index 9998922c..2493a079 100644
--- a/harness/codeverse3d/tracks/planner.py
+++ b/harness/codeverse3d/tracks/planner.py
@@ -745,6 +745,9 @@ def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Works
raise ValueError(f"the plan echoes the schema's placeholders instead of describing the object: {echoed}. "
"Write the REAL plan: actual part names, real numbers, a unit axis for every joint.")
result = plan_model.model_validate(raw)
+ clash = fixed_part_clash(result, spec)
+ if clash:
+ raise ValueError(clash)
except (ValidationError, ValueError) as e:
last_error = str(e)[:4000]
_record_invalid(ws, attempt, raw, resp.text)
@@ -830,6 +833,20 @@ def build_system_prompt(spec: Spec, plan_model: type[BaseModel], *, budget: Plan
)
+def fixed_part_clash(plan_obj: BaseModel, spec: Spec) -> str:
+ """'' unless the plan lists one of the spec's fixed parts (``Spec.fixed_parts``) as a part of its own: the
+ project builds those, so a planned one invites the agent to author it — the re-ask says which."""
+ fixed = {to_snake(f.name): f for f in spec.fixed_parts if f.name}
+ if not fixed:
+ return ""
+ names = [p.name for p in getattr(plan_obj, "parts", None) or []]
+ hits = [n for n in names if to_snake(n) in fixed]
+ if not hits:
+ return ""
+ return (f"the plan lists fixed parts {hits} as its own parts: they are given by the project (FIXED PARTS) — "
+ "remove them from the plan and plan only the parts around them")
+
+
def build_user_prompt(spec: Spec, *, brief: Any | None = None, budget: PlanBudget | None = None,
unit: str = "parts") -> str:
lines = [f"REQUEST: {spec.prompt}", "", "CONSTRAINTS:", constraints_text(spec)]
diff --git a/harness/codeverse3d/tracks/prompting.py b/harness/codeverse3d/tracks/prompting.py
index 3eb58191..96b3e045 100644
--- a/harness/codeverse3d/tracks/prompting.py
+++ b/harness/codeverse3d/tracks/prompting.py
@@ -101,9 +101,37 @@ def constraints_text(spec: Any) -> str:
lines.append(f"MUST HAVE: {m}")
for m in c.must_not:
lines.append(f"MUST NOT: {m}")
+ lines += fixed_parts_lines(spec)
return "\n".join(lines) or "(none)"
+def fixed_parts_lines(spec: Any) -> list[str]:
+ """The spec's fixed parts (``FixedPart``) for the planner and the agent: given files, never planned, never
+ edited, imported as they are. Empty for a spec without any, so its prompts stay byte-identical."""
+ fixed = list(getattr(spec, "fixed_parts", None) or [])
+ if not fixed:
+ return []
+ out = ["FIXED PARTS (given by the project: never plan them as parts, never edit, move, scale, recolour or "
+ "rename them or what they return, never attach_to them, never assert their size in selfcheck; an edit "
+ "is reverted):"]
+ for f in fixed:
+ what = f"{f.path}"
+ if f.export:
+ what += f" exports {f.export}"
+ if f.name:
+ what += f", builds the part '{f.name}'"
+ if f.bbox_min is not None and f.bbox_max is not None:
+ (x0, y0, z0), (x1, y1, z1) = f.bbox_min, f.bbox_max
+ what += f" spanning x {x0:.2f}..{x1:.2f}, y {y0:.2f}..{y1:.2f}, z {z0:.2f}..{z1:.2f} m (GLB frame)"
+ out.append(f"- {what}" + (f": {f.note}" if f.note else ""))
+ return out
+
+
+def fixed_paths(spec: Any) -> list[str]:
+ """The workspace-relative paths of the spec's fixed parts (read-only for every session)."""
+ return [f.path.replace("\\", "/") for f in (getattr(spec, "fixed_parts", None) or [])]
+
+
def language_system_prompt(language: Language, *, role: str = "", tools: bool = True, **vars: Any) -> str:
"""The generator's system prompt: ``prompts/<dir>/system.md``, or a role template."""
base = render(language_prompt(language, "system.md"), tools=tools).strip()
@@ -238,7 +266,7 @@ def current_files(
ctx: RunContext, rels: Sequence[str], max_chars: int = MAX_SKELETON_CHARS
) -> dict[str, str]:
"""``{rel: text}`` for the files that exist, trimmed to ``max_chars`` in total. The"""
- owned = set(HARNESS_OWNED_SRC.get(ctx.language, ()))
+ owned = set(HARNESS_OWNED_SRC.get(ctx.language, ())) | set(fixed_paths(ctx.spec))
out: dict[str, str] = {}
total = 0
for rel in rels:
diff --git a/harness/codeverse3d/tracks/static_object.py b/harness/codeverse3d/tracks/static_object.py
index 65cd9615..7425ae3d 100644
--- a/harness/codeverse3d/tracks/static_object.py
+++ b/harness/codeverse3d/tracks/static_object.py
@@ -25,7 +25,7 @@ from codeverse3d.conventions import (
)
from codeverse3d.orchestrator import RefineTask, TaskGroup, compact_instructions
from codeverse3d.prompts import render
-from codeverse3d.spatial.contract import planned_joins
+from codeverse3d.spatial.contract import check_fixed_parts, planned_joins
from codeverse3d.spatial.silhouette import measure_reference
from codeverse3d.tracks.common import RunContext
from codeverse3d.tracks.depth import budget_gate, depth_budget
@@ -70,6 +70,9 @@ class ObjectPipeline:
)
# deterministic density check against the plan; the judge is never asked about detail
out.append(budget_gate(measurement, build, depth_budget(ctx.plan, ctx.settings.limits.build_timeout_s)))
+ if measurement is not None and ctx.spec.fixed_parts:
+ # the project's fixed parts (Spec.fixed_parts) built as declared: not moved, scaled or edited
+ out.append(check_fixed_parts(measurement, ctx.spec.fixed_parts))
return out
def render(
diff --git a/harness/tests/orchestrator_tracks/test_fixed_parts.py b/harness/tests/orchestrator_tracks/test_fixed_parts.py
new file mode 100644
index 00000000..3e583134
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_fixed_parts.py
@@ -0,0 +1,122 @@
+"""Spec.fixed_parts: project-seeded files no session may rewrite, never planned, measured as declared."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from codeverse3d.contracts.artifacts import Measurement, PartMeasure, Severity
+from codeverse3d.contracts.common import Language, Track
+from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan
+from codeverse3d.contracts.spec import FixedPart, Spec
+from codeverse3d.workspace import Workspace
+
+SHELL = FixedPart(path="src/parts/survey_shell.js", name="SurveyShell", export="buildSurveyShell",
+ bbox_min=(-7.0, 0.0, -7.5), bbox_max=(7.0, 24.3, 7.5), note="measured survey geometry")
+DATA = FixedPart(path="src/house.js", export="HOUSE")
+
+
+def _spec(*fixed: FixedPart) -> Spec:
+ return Spec(id="x", track=Track.STATIC_OBJECT, language=Language.THREEJS, prompt="a house",
+ fixed_parts=list(fixed))
+
+
+def test_fixed_parts_must_be_sources_with_a_whole_box() -> None:
+ with pytest.raises(ValueError, match="under src/"):
+ _spec(FixedPart(path="plan.json"))
+ with pytest.raises(ValueError, match="under src/"):
+ _spec(FixedPart(path="src/../spec.json"))
+ with pytest.raises(ValueError, match="both bbox_min and bbox_max"):
+ _spec(FixedPart(path="src/a.js", bbox_min=(0, 0, 0)))
+
+
+def test_the_plan_key_moves_only_when_a_spec_has_fixed_parts() -> None:
+ from codeverse3d.orchestrator import hash_inputs
+ from codeverse3d.tracks.lifecycle import plan_stage_inputs
+
+ plain = _spec()
+ assert "fixed_parts" not in plan_stage_inputs(plain) # every existing run's plan key stays put
+ assert hash_inputs(plan_stage_inputs(plain)) != hash_inputs(plan_stage_inputs(_spec(SHELL)))
+
+
+def test_the_planner_and_agent_are_told_and_plain_specs_are_unchanged() -> None:
+ from codeverse3d.tracks.prompting import constraints_text
+
+ assert constraints_text(_spec()) == "(none)"
+ text = constraints_text(_spec(SHELL, DATA))
+ assert "FIXED PARTS" in text and "never attach_to them" in text
+ assert "src/parts/survey_shell.js exports buildSurveyShell, builds the part 'SurveyShell'" in text
+ assert "x -7.00..7.00, y 0.00..24.30, z -7.50..7.50 m" in text
+ assert "- src/house.js exports HOUSE" in text
+
+
+def test_every_session_gets_the_fixed_parts_read_only(tmp_path: Path) -> None:
+ from codeverse3d.tracks.generation import _read_only
+
+ ws = Workspace(tmp_path / "run").create()
+ ws.write_json(ws.spec_path, _spec(SHELL, DATA))
+ assert _read_only("threejs", ws) == ["src/parts/survey_shell.js", "src/house.js"]
+ assert _read_only("scene_threejs", ws)[0] == "src/lib/" # the language's own stay first
+
+
+def _measured(*parts: PartMeasure) -> Measurement:
+ return Measurement(bbox_min=(-8, 0, -8), bbox_max=(8, 25, 8), extents=(16, 25, 16), center=(0, 12.5, 0),
+ tri_count=1000, n_meshes=len(parts), n_islands=len(parts), parts=list(parts))
+
+
+def test_the_gate_passes_a_part_built_as_declared_and_errs_on_a_moved_or_missing_one() -> None:
+ from codeverse3d.spatial.contract import FIXED_GATE, check_fixed_parts
+
+ as_declared = PartMeasure(name="SurveyShell", bbox_min=(-7.0, 0.0, -7.5), bbox_max=(7.0, 24.3, 7.51))
+ assert check_fixed_parts(_measured(as_declared), [SHELL, DATA]).passed
+
+ squashed = PartMeasure(name="SurveyShell", bbox_min=(-7.0, 0.0, -7.5), bbox_max=(7.0, 24.3, 6.6))
+ rep = check_fixed_parts(_measured(squashed), [SHELL])
+ assert not rep.passed and rep.gate == FIXED_GATE
+ assert rep.errors[0].data["kind"] == "fixed_part_bbox" and rep.errors[0].data["off_m"] == pytest.approx(0.9)
+
+ rep = check_fixed_parts(_measured(PartMeasure(name="Facade", bbox_min=(0, 0, 0), bbox_max=(1, 1, 1))), [SHELL])
+ assert [f.data["kind"] for f in rep.findings if f.severity is Severity.ERROR] == ["fixed_part_missing"]
+
+
+def test_a_moved_fixed_part_caps_the_reference_rubric() -> None:
+ from codeverse3d.contracts.artifacts import GateFinding, GateReport
+ from codeverse3d.judges.rubrics import apply_caps, load_rubric
+
+ gate = GateReport.of("contract_fixed", [GateFinding(gate="contract_fixed", severity=Severity.ERROR,
+ message="moved", data={"kind": "fixed_part_bbox"})])
+ assert apply_caps(load_rubric("reference"), 0.9, [gate], {}).overall == pytest.approx(0.6)
+
+
+def test_a_plan_that_claims_a_fixed_part_is_reasked() -> None:
+ from codeverse3d.tracks.planner import fixed_part_clash
+
+ box = BBox(center=(0, 1, 0), extents=(1, 2, 1))
+ plan = StaticPlan(object_name="House", summary="s", overall_bbox=box,
+ parts=[PartPlan(name="StreetFacade", role="facade", description="the street wall", bbox=box),
+ PartPlan(name="survey_shell", role="shell", description="the shell", bbox=box)])
+ assert "['survey_shell']" in fixed_part_clash(plan, _spec(SHELL))
+ assert fixed_part_clash(plan, _spec()) == ""
+
+
+def test_the_skeleton_keeps_a_fixed_part_and_stops_without_one(tmp_path: Path) -> None:
+ from codeverse3d.tracks.lifecycle import _skeleton
+
+ ws = Workspace(tmp_path / "run").create()
+ shell = ws.root / SHELL.path
+ shell.parent.mkdir(parents=True, exist_ok=True)
+ shell.write_text("export function buildSurveyShell() {}\n")
+
+ def overwrite(ws_: Workspace, plan: object) -> list[Path]: # a language whose skeleton rewrites src/
+ shell.write_text("// placeholder\n")
+ return [shell]
+
+ ctx = SimpleNamespace(ws=ws, plan=None, spec=_spec(SHELL), runtime=SimpleNamespace(skeleton=overwrite))
+ _skeleton(None, ctx) # type: ignore[arg-type]
+ assert shell.read_text() == "export function buildSurveyShell() {}\n"
+
+ ctx.spec = _spec(SHELL, FixedPart(path="src/missing.js"))
+ with pytest.raises(FileNotFoundError, match="src/missing.js"):
+ _skeleton(None, ctx) # type: ignore[arg-type]