Skip to content

Official Codebase of 3DCodeVerse

Python

D111: honest env stage, zone-root placement rows, probe timeouts judged by phase

gaoypengb39be4c68a11
diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.py
index c7de387e..5d6d7101 100644
--- a/harness/codeverse3d/agents/cli_common.py
+++ b/harness/codeverse3d/agents/cli_common.py
@@ -7,6 +7,7 @@ classification, and the tool-call trace. (``cli/`` is the harness's own ``3dcod
from __future__ import annotations
+import contextlib
import json
import logging
import os
@@ -135,8 +136,14 @@ class ActivityTracker:
def _latest_mtime(dirs: Iterable[Path]) -> float:
+ """Newest mtime under ``dirs`` — a directory is walked, a FILE is its own mtime (a
+ ``shared_tree`` session watches only its own files, D111)."""
latest = 0.0
for d in dirs:
+ if d.is_file():
+ with contextlib.suppress(OSError):
+ latest = max(latest, d.stat().st_mtime)
+ continue
if not d.is_dir():
continue
for root, subdirs, files in os.walk(d):
@@ -166,8 +173,8 @@ def run_with_watchdog(
"""Run ``cmd`` streaming output; kill the process group on idle/hard timeout.
``on_line(stream, line)`` is called for every line (stream is ``"stdout"``
- or ``"stderr"``). ``activity_dirs`` (default ``cwd/src``) are polled for
- mtime changes (every ``scan_s``) that also count as activity.
+ or ``"stderr"``). ``activity_dirs`` (default ``cwd/src``; a file is watched as itself)
+ are polled for mtime changes (every ``scan_s``) that also count as activity.
Since 2026-08-27 the process lifecycle lives in
:class:`codeverse3d.proc.ManagedProcess`; this function keeps only the clocks.
@@ -304,14 +311,22 @@ def _hinted(path: str, hints: frozenset[str]) -> bool:
return any(path == h or path.startswith(h.rstrip("/") + "/") for h in hints)
-def attribute_changes(files: list[FileChange], *, write_roots: list[str]) -> list[FileChange]:
+def attribute_changes(files: list[FileChange], *, write_roots: list[str],
+ only: Iterable[str] | None = None) -> list[FileChange]:
"""The subset of a whole-worktree git diff that belongs to ONE session: inside its
- ``write_roots`` and not harness-owned. (Sessions on one workspace are serialised —
- :data:`EXCLUSIVE_KINDS` — so there is no sibling to attribute against. An ``own_hints``
- parameter sat in this signature unread until 2026-08-30: the edit_only scope is enforced
- by :func:`_enforce_scope`, which REVERTS an out-of-scope write rather than hiding it from
- ``files_changed``, so narrowing here would only have lied about what the session did.)"""
+ ``write_roots`` and not harness-owned. (Agent sessions on one workspace are serialised —
+ :data:`EXCLUSIVE_KINDS` — so there is no sibling SESSION to attribute against; the
+ edit_only scope is enforced by :func:`_enforce_scope`, which REVERTS an out-of-scope write
+ rather than hiding it from ``files_changed``.)
+
+ ``only`` — a ``shared_tree`` job's ``files_hint`` (D111): harness writers that take no
+ session lock (the scene asset single-shots) change the same tree while the session runs,
+ and the diff cannot tell their files from the session's. The env session of iteration 4
+ (argon loop, 2026-10-15) wrote nothing in 12 of 15 runs and was credited with the asset
+ files every time, so its stage read ``ok``. Under ``only`` a path outside it is not the
+ session's."""
roots = tuple(r.strip("/") for r in write_roots if r.strip("/"))
+ own = _clean(only) if only is not None else None
out: list[FileChange] = []
for f in files:
parts = Path(f.path).parts
@@ -319,6 +334,8 @@ def attribute_changes(files: list[FileChange], *, write_roots: list[str]) -> lis
continue
if roots and not any(f.path == r or f.path.startswith(r + "/") for r in roots):
continue
+ if own is not None and not _hinted(f.path, own):
+ continue
out.append(f)
return out
@@ -490,7 +507,8 @@ def finish_session(
**extra: Any,
) -> AgentResult:
"""Commit the agent's work, compute ``files_changed`` via git (attributed to this
- session — see :func:`attribute_changes`), write result.json. ``turns`` is the
+ session — see :func:`attribute_changes`; a ``shared_tree`` job is credited with its
+ ``files_hint`` only), write result.json. ``turns`` is the
backend's own count (``AgentResult.turns``); ``transient`` / ``quota`` its typed
failure class and ``provider_wait_s`` the time its CLI lost to provider errors
(:func:`provider_wait`); ``effort`` what the backend passed its CLI (``AgentResult.effort``);
@@ -512,7 +530,8 @@ def finish_session(
errors.append(msg)
s.notes.append(msg)
s.ws.commit(f"agent:{s.label}")
- files = attribute_changes(s.ws.changed_files(s.head_before), write_roots=s.job.write_roots)
+ files = attribute_changes(s.ws.changed_files(s.head_before), write_roots=s.job.write_roots,
+ only=s.files_hint if s.job.shared_tree else None)
duration = round(time.monotonic() - s.t0, 3)
res = AgentResult(
ok=ok, exit_reason=exit_reason, text=text, files_changed=files,
@@ -573,7 +592,8 @@ def invoke(
One block every backend shares: the ``invoke`` transcript line, ``run_with_watchdog``
(workspace cwd, the job's soft timeout, ``IDLE_GRACE_S``, every output line into the
- transcript, ``src/`` + ``public/`` as activity dirs) and the stdout/stderr captures next to
+ transcript, ``src/`` + ``public/`` as activity dirs — a ``shared_tree`` job's own files only,
+ :func:`activity_paths`) and the stdout/stderr captures next to
the transcript. ``stdout_name`` sets the capture's name (codex streams JSONL →
``stdout.jsonl``); ``on_stdout`` / ``on_stderr`` also receive each line as it arrives (the
backends fold their event streams live). The ``invoke`` line records the prompt's size,
@@ -601,13 +621,24 @@ def invoke(
proc = run_with_watchdog(
argv, cwd=s.ws.root, env=env, soft_timeout_s=soft, hard_timeout_s=hard,
idle_grace_s=IDLE_GRACE_S, poll_s=POLL_S,
- on_line=on_line, stdin=prompt, activity_dirs=[s.ws.src, s.ws.public],
+ on_line=on_line, stdin=prompt, activity_dirs=activity_paths(s),
)
s.traj.write_text(stdout_name, proc.stdout)
s.traj.write_text("stderr.log", proc.stderr)
return proc
+def activity_paths(s: Session) -> list[Path]:
+ """What the watchdog polls as this session's activity: ``src/`` + ``public/``, or — a
+ ``shared_tree`` job (D111) — its ``files_hint`` paths alone. The asset single-shots
+ writing ``src/assets/`` beside the env session kept it "alive" until ~300 s after their
+ last write, so its kill time followed the asset stage (421-616 s on a 420 s window in the
+ 12 iteration-4 runs whose session wrote nothing) instead of its own work."""
+ if s.job.shared_tree:
+ return [s.ws.root / h for h in sorted(s.files_hint)]
+ return [s.ws.src, s.ws.public]
+
+
def watchdog_error(proc: CompletedProc) -> str:
"""The error line every CLI backend records when the watchdog killed its process."""
return f"killed by watchdog ({proc.killed_reason}) after {proc.duration_s:.0f}s"
diff --git a/harness/codeverse3d/contracts/agent.py b/harness/codeverse3d/contracts/agent.py
index ad1c538b..f3c69026 100644
--- a/harness/codeverse3d/contracts/agent.py
+++ b/harness/codeverse3d/contracts/agent.py
@@ -10,7 +10,7 @@ from __future__ import annotations
from typing import Literal
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, model_validator
from codeverse3d.contracts.common import Usage
@@ -86,10 +86,24 @@ class AgentJob(BaseModel):
"(src/lib/ for the scene languages: contracts.common.HARNESS_OWNED_SRC); enforced "
"post-session: a write to one is reverted and the session failed",
)
+ shared_tree: bool = Field(
+ default=False,
+ description="other harness writers change this workspace WHILE the session runs (the scene env stage "
+ "beside the asset single-shots, which take no session lock — D111): ``files_changed`` counts only "
+ "``files_hint`` and only a write to a ``files_hint`` path is watchdog activity. Needs a ``files_hint``; "
+ "never with ``edit_only`` (a sibling's write cannot be told from an out-of-scope one, so the scope "
+ "revert would undo the sibling's work)",
+ )
mcp_command: list[str] | None = Field(
default=None, description="override for the 3dcode MCP server command"
)
+ @model_validator(mode="after")
+ def _shared_tree_scope(self) -> AgentJob:
+ if self.shared_tree and (self.edit_only or not any(str(h).strip() for h in self.files_hint)):
+ raise ValueError("shared_tree needs a files_hint and excludes edit_only")
+ return self
+
class AgentResult(BaseModel):
ok: bool
diff --git a/harness/codeverse3d/conventions.py b/harness/codeverse3d/conventions.py
index a03899cd..a39da02f 100644
--- a/harness/codeverse3d/conventions.py
+++ b/harness/codeverse3d/conventions.py
@@ -263,6 +263,16 @@ def split_instance(name: str) -> tuple[str, str]:
#: (``spatial/joints_export``); ``spatial/measure`` merges them back into the link's part.
LINK_PIECE_SEP = "__"
+#: the harness's own mark on a scene's ZONE roots (D111): ``userData[ZONE_ROOT_KEY] = <zone name>`` in
+#: three.js, set by the assembler (``render_scene_js``'s ``addZone``), and the census GLB's zone node
+#: ``extras`` for scene_blender (``wrappers/_census_glb.py``, handed the key on argv — it cannot import
+#: this module), which GLTFLoader turns into the same ``userData``. The placement table reads it
+#: (``runtime_js/lib/host_placement.mjs`` ``ZONE_ROOT_KEY``; ``tests/scene_runtime/test_zone_roots.py``
+#: pins the two): only children of a marked root are placed assets — every other root (env scenery, a
+#: zone's stray ``scene.add``) is scenery, never a row. A key, never a name test: a zone may name its
+#: group anything, and an env group may be called anything too.
+ZONE_ROOT_KEY = "c3d_zone"
+
def part_key(node: str, plan_keys: Collection[str]) -> str | None:
"""The plan part (a snake key in ``plan_keys``) a GLB node belongs to, or None: the
diff --git a/harness/codeverse3d/languages/base.py b/harness/codeverse3d/languages/base.py
index 309f9bfa..72e49cb1 100644
--- a/harness/codeverse3d/languages/base.py
+++ b/harness/codeverse3d/languages/base.py
@@ -79,8 +79,9 @@ class SceneRuntime(LanguageRuntime, Protocol):
the result lands in ``artifacts/assemble.json``."""
...
- def probe(self, ws: Workspace, *, timeout_s: float = 60.0) -> SceneProbeResult:
- """Load the built scene headlessly: the ``scene_probe`` gate + the census (``census.json``)."""
+ def probe(self, ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:
+ """Load the built scene headlessly: the ``scene_probe`` gate + the census (``census.json``),
+ under the build's own budget by default (D111)."""
...
def render_scene(self, ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None = None, orbit: bool = True,
diff --git a/harness/codeverse3d/languages/scene_blender/__init__.py b/harness/codeverse3d/languages/scene_blender/__init__.py
index db23734f..43bce6b1 100644
--- a/harness/codeverse3d/languages/scene_blender/__init__.py
+++ b/harness/codeverse3d/languages/scene_blender/__init__.py
@@ -37,7 +37,14 @@ from codeverse3d.contracts.artifacts import (
)
from codeverse3d.contracts.common import ENTRY_FILE, Language
from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan, ScenePlan, ZonePlan
-from codeverse3d.conventions import fmt3, glb_basis, to_authoring_frame, to_pascal, to_snake
+from codeverse3d.conventions import (
+ ZONE_ROOT_KEY,
+ fmt3,
+ glb_basis,
+ to_authoring_frame,
+ to_pascal,
+ to_snake,
+)
from codeverse3d.languages._ast_lint import (
BASE_FORBIDDEN_IMPORTS,
check_imports,
@@ -761,7 +768,7 @@ class SceneBlenderRuntime:
out_dir.mkdir(parents=True, exist_ok=True)
basis = ",".join(f"{v:g}" for row in glb_basis(LANGUAGE.value) for v in row)
cmd = [self.blender_binary(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",
- "--scene", str(ws.root / ENTRY_REL), "--out", str(out_dir), "--basis", basis,
+ "--scene", str(ws.root / ENTRY_REL), "--out", str(out_dir), "--basis", basis, "--zone-key", ZONE_ROOT_KEY,
"--fps", str(FPS), "--frames", f"{frame_of(TIMES[0])},{frame_of(TIMES[-1])}",
"--rlimit-gb", str(self._settings.limits.bpy_rlimit_gb), "--seed", "0"]
if zones is not None:
@@ -834,7 +841,7 @@ class SceneBlenderRuntime:
ws.write_json(ws.artifacts / "build.json", res)
return res
- def probe(self, ws: Workspace, *, timeout_s: float = 60.0) -> SceneProbeResult:
+ def probe(self, ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:
"""The build's own measurement (Blender run + census-GLB probe), without touching
``build.json``: an offline scene has no cheaper way to load."""
from codeverse3d.spatial.probes import PROBE_GATE, probe_result
@@ -843,7 +850,7 @@ class SceneBlenderRuntime:
gate = GateReport.of(PROBE_GATE, [GateFinding(gate=PROBE_GATE, severity=Severity.ERROR, target=ENTRY_REL,
message=f"{ENTRY_REL} does not exist", fix_hint="re-run the assemble step")])
return probe_result(gate, {})
- run, gate, census = self._measure(ws, timeout_s=max(timeout_s, float(self._settings.limits.build_timeout_s)),
+ run, gate, census = self._measure(ws, timeout_s=max(timeout_s or 0.0, float(self._settings.limits.build_timeout_s)),
keep=("build.json",))
if gate is None:
r = run.result
diff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.py
index 8b3ae429..3f9974aa 100644
--- a/harness/codeverse3d/languages/scene_threejs/__init__.py
+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py
@@ -21,7 +21,7 @@ from codeverse3d.contracts.artifacts import (
)
from codeverse3d.contracts.common import ENTRY_FILE, Language
from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan, ScenePlan, ZonePlan
-from codeverse3d.conventions import OBJECT_VIEWS_QUICK, to_pascal, to_snake
+from codeverse3d.conventions import OBJECT_VIEWS_QUICK, ZONE_ROOT_KEY, to_pascal, to_snake
from codeverse3d.languages._common import line_of, missing_entry, target_file, target_line, ws_rel
from codeverse3d.languages._js_lint import (
ExportsCache,
@@ -586,6 +586,7 @@ export async function createScene({{ renderer, loaders }}) {{
if (!g || !g.isObject3D) throw new Error('build(ctx) did not return a THREE.Object3D');
const wrap = new THREE.Group();
wrap.name = '__zone__' + name;
+ g.userData['{ZONE_ROOT_KEY}'] = name; // as createScene marks it: the settle at boot moves zone assets only
wrap.add(g);
scene.add(wrap);
wraps.push(wrap);
@@ -737,6 +738,7 @@ export async function createScene({{ renderer, loaders }}) {{
const g = await build(ctx);
if (!g || !g.isObject3D) throw new Error(`zone ${{name}}: build(ctx) must return a THREE.Group`);
if (!g.name) g.name = name;
+ g.userData['{ZONE_ROOT_KEY}'] = name; // the harness's zone mark: the placement table measures its children
scene.add(g);
zones.push(g);
}};
@@ -828,7 +830,7 @@ class SceneThreeJsRuntime:
def assemble(self, ws: Workspace, plan: ScenePlan) -> AssembleResult:
return assemble(ws, plan, cameras="plan" if getattr(plan, "cameras", None) else "derive")
- def probe(self, ws: Workspace, *, timeout_s: float = 60.0) -> SceneProbeResult:
+ def probe(self, ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:
from codeverse3d.spatial.probes import probe_scene
return probe_scene(ws, timeout_s=timeout_s)
diff --git a/harness/codeverse3d/languages/wrappers/_census_glb.py b/harness/codeverse3d/languages/wrappers/_census_glb.py
index 2577ee92..3b0c1de8 100644
--- a/harness/codeverse3d/languages/wrappers/_census_glb.py
+++ b/harness/codeverse3d/languages/wrappers/_census_glb.py
@@ -11,7 +11,8 @@ Layout (what the census and the placement table read):
* root nodes = env objects (whatever is not in a zone collection), by object name — ``backdrop.mjs``
classifies ``Ground`` / ``Terrain`` / ``Water`` / ``Sky…`` by name, so names are carried verbatim;
-* one root node per ZONE collection, named for it; its children = the zone's root objects, their
+* one root node per ZONE collection, named for it and marked ``extras[zone_key]`` (D111: the
+ placement table's zone roots; env roots are scenery); its children = the zone's root objects, their
parent chains as child nodes (group nodes carry no transform: every mesh node holds its world
matrix, so an Empty's rotation can never be applied twice);
* a collection-instance Empty = a node whose children are one mesh node per instanced object, all
@@ -261,11 +262,13 @@ def _chain(obj: Any) -> list[Any]:
def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: dict[str, str],
- cameras: list[dict[str, Any]]) -> dict[str, Any]:
+ cameras: list[dict[str, Any]], zone_key: str) -> dict[str, Any]:
"""Write the census GLB of the current (t = 0) state to ``path``; return its stats.
``zones`` maps a zone COLLECTION name to itself for every zone the wrapper built (the node
- name); every object in one of them (recursively) hangs under that zone's node."""
+ name); every object in one of them (recursively) hangs under that zone's node, and that node's
+ ``extras`` carry ``{zone_key: <zone>}`` (``conventions.ZONE_ROOT_KEY``, D111) — the mark the
+ placement table measures the zone's children by; every other root is scenery."""
t0 = time.perf_counter()
w = _Writer(np.array(basis, np.float64))
zone_of: dict[str, str] = {}
@@ -296,7 +299,8 @@ def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: di
dg = bpy.context.evaluated_depsgraph_get()
clouds: dict[tuple[tuple[str, ...], Any], tuple[int | None, str, list[np.ndarray]]] = {}
for zone in zones: # an empty zone is still a group the census can see
- w.group((zone,), extras_of(bpy.data.collections[zone]) if zone in bpy.data.collections else None)
+ own = extras_of(bpy.data.collections[zone]) if zone in bpy.data.collections else {}
+ w.group((zone,), {**own, zone_key: zone})
# an object that hosts an instance cloud is its own group (its mesh + the cloud = one row)
hosts = {inst.parent.original.name for inst in dg.object_instances
if inst.is_instance and inst.parent is not None and inst.parent.original.instance_type != "COLLECTION"}
diff --git a/harness/codeverse3d/languages/wrappers/run_bpy_scene.py b/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
index 608b962c..9de5d22c 100644
--- a/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
+++ b/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
@@ -1,7 +1,7 @@
"""Blender SCENE build wrapper (scene_blender) — executed BY Blender, never imported by the harness.
blender -b --factory-startup --python run_bpy_scene.py -- \
- --scene /abs/src/scene.py --out /abs/artifacts --basis 1,0,0,0,0,1,0,-1,0 \
+ --scene /abs/src/scene.py --out /abs/artifacts --basis 1,0,0,0,0,1,0,-1,0 --zone-key c3d_zone \
[--fps 30] [--frames 1,46] [--rlimit-gb 12] [--seed 0] [--zones '{"a": "A"}'] [--no-blend]
What it does (in order), DESIGN §3.3:
@@ -75,6 +75,7 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
p.add_argument("--rlimit-gb", type=float, default=12.0)
p.add_argument("--seed", type=int, default=0)
p.add_argument("--zones", default=None, help='JSON {"snake": "Pascal"} that overrides ZONES')
+ p.add_argument("--zone-key", required=True, help="conventions.ZONE_ROOT_KEY: the census GLB's zone-node mark")
p.add_argument("--no-blend", action="store_true")
return p.parse_args(argv)
@@ -503,7 +504,8 @@ def main() -> int:
basis = [[float(v) for v in args.basis.split(",")[i * 3:i * 3 + 3]] for i in range(3)]
try:
facts["glb"] = write_census_glb(bpy, os.path.join(out_dir, GLB_NAME), basis=basis,
- zones={name: name for name in built.values()}, cameras=list(g.get("CAMERAS") or []))
+ zones={name: name for name in built.values()}, cameras=list(g.get("CAMERAS") or []),
+ zone_key=args.zone_key)
report["exported"]["glb"] = os.path.join(out_dir, GLB_NAME)
except Exception as e: # noqa: BLE001 — a writer failure is the harness's, reported as such
import traceback # noqa: PLC0415
diff --git a/harness/codeverse3d/orchestrator.py b/harness/codeverse3d/orchestrator.py
index 099b2b28..c037ac1d 100644
--- a/harness/codeverse3d/orchestrator.py
+++ b/harness/codeverse3d/orchestrator.py
@@ -262,14 +262,19 @@ def build_refine_instructions(
"""Gate ERRORS first (with fix hints) — a part still the skeleton's placeholder
(``PLACEHOLDER_PART``) ahead of every other gate ERROR —, then ``extra`` harness-derived tasks
(e.g. reference-silhouette mismatch), then failed *must* acceptance items,
- then the judge's improvement plan; de-duplicated by (target, kind), capped.
- Gate/acceptance/extra tasks are never dropped by the cap unless they alone exceed it."""
+ then the judge's improvement plan; de-duplicated by (target, kind, finding kind), capped.
+ Gate/acceptance/extra tasks are never dropped by the cap unless they alone exceed it.
+
+ The finding kind (``GateFinding.data["kind"]``) is part of a gate task's key (D111): with
+ (target, ``gate:<gate>``) alone every env ERROR of ``scene_placement`` collapsed into the
+ first, so ``no_fog`` hid ``no_background`` from the refine prompt (argon loop iteration 4,
+ r1_08 / r1_10). Two findings of one kind on one target are still one task."""
known = _known_targets(plan)
tasks: list[RefineTask] = []
- seen: set[tuple[str, str]] = set()
+ seen: set[tuple[str, str, str]] = set()
- def _add(t: RefineTask) -> None:
- key = (to_snake(t.target), t.kind)
+ def _add(t: RefineTask, finding_kind: str = "") -> None:
+ key = (to_snake(t.target), t.kind, finding_kind)
if key in seen:
return
seen.add(key)
@@ -282,7 +287,7 @@ def build_refine_instructions(
errors.sort(key=lambda gf: gf[1].data.get("kind") != PLACEHOLDER_PART) # stable: placeholders first
for g, f in errors:
_add(RefineTask(target=f.target or "overall", kind=f"gate:{g.gate}", instruction=f.as_line(),
- priority=0, source="gate"))
+ priority=0, source="gate"), str(f.data.get("kind") or ""))
for t in extra:
_add(t.model_copy())
for a in acceptance_failures:
diff --git a/harness/codeverse3d/spatial/probes.py b/harness/codeverse3d/spatial/probes.py
index ae43d529..aaf307e0 100644
--- a/harness/codeverse3d/spatial/probes.py
+++ b/harness/codeverse3d/spatial/probes.py
@@ -25,6 +25,7 @@ from pydantic import BaseModel, Field
from codeverse3d.config import get_settings
from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse3d.contracts.common import ENTRY_FILE, Language
from codeverse3d.conventions import DRAWS_WARN_SCENE, MAX_DRAWS_SCENE, MAX_TRIS_SCENE
from codeverse3d.spatial.render_scene import SceneRenderError, probe_env_args, run_scene_script
from codeverse3d.workspace import Workspace
@@ -85,8 +86,12 @@ def run_probe(ws: Workspace, *, compile: bool = False, timeout_s: float | None =
``compile`` also runs the shader preflight on the same page; without it — or when the
scene never boots — the preflight is a failed-empty gate. ``timeout_s`` defaults to
the build timeout, capped at 120 s. A driver that cannot run is a ``harness_failure``
- finding, never a raise. ``glb`` probes an offline scene's census GLB instead of
- ``src/scene.js`` (module docstring), ``facts`` its bpy census."""
+ finding, never a raise — except a driver whose own watchdog fired twice inside the scene's
+ own code (``SceneRenderError.scene_timed_out``): that is the scene's construction cost and an
+ ERROR against the code (:func:`timeout_finding`, D111). ``glb`` probes an offline scene's
+ census GLB instead of ``src/scene.js`` (module docstring), ``facts`` its bpy census; the GLB
+ is the harness's own export of a scene Blender already built, so a boot of it that never
+ finishes stays the harness's, like every other failure to boot it (:func:`offline_report`)."""
t0 = time.time()
timeout_s = min(float(timeout_s or get_settings().limits.build_timeout_s), 120.0)
args = ["--ws", str(ws.root), "--out", str(ws.artifacts / "scene_probe.json"), "--timeout-ms", str(int(timeout_s * 1000))]
@@ -104,8 +109,11 @@ def run_probe(ws: Workspace, *, compile: bool = False, timeout_s: float | None =
try:
res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)
except SceneRenderError as e:
- finding = _f(PROBE_GATE, Severity.ERROR, f"scene probe could not run: {e}"[:1500], target="src/scene.js",
- hint="this is a harness/driver failure, not your code; retry or report", harness_failure=True)
+ if e.scene_timed_out and glb is None:
+ finding = timeout_finding(timeout_s, phase=e.phase) # after run_scene_script's one retry
+ else:
+ finding = _f(PROBE_GATE, Severity.ERROR, f"scene probe could not run: {e}"[:1500], target="src/scene.js",
+ hint="this is a harness/driver failure, not your code; retry or report", harness_failure=True)
return GateReport.of(PROBE_GATE, [finding], duration_ms=int((time.time() - t0) * 1000)), no_preflight, {}
if glb is not None:
probe, census = offline_report(res.summary, facts or {}, duration_ms=int((time.time() - t0) * 1000))
@@ -117,8 +125,33 @@ def run_probe(ws: Workspace, *, compile: bool = False, timeout_s: float | None =
return probe, shader_report(rep, duration_ms=int(rep.get("duration_ms") or 0)), census
-def probe_scene(ws: Workspace, *, timeout_s: float = 60.0) -> SceneProbeResult:
- """Import-only probe: module loads, shape valid, cameras valid, update runs, census."""
+def timeout_finding(timeout_s: float, *, phase: str) -> GateFinding:
+ """A probe whose watchdog fired inside the scene's own code (``render_scene.SCENE_PHASES``) —
+ after the driver's one retry, on a browser of its own — is an ERROR against the CODE.
+
+ WHY (D111). Argon loop iteration 4, r1_08 (2026-10-15): the refine's new 37 k-vertex terrain met
+ the zones' per-vertex raycast seating and the scene no longer booted inside 120 s. The probe filed
+ it as a harness failure with "not your code; retry or report": the agent, told so by its own build
+ tool, went quiet until the watchdog killed it, and the round then spent 3 x 240 s rebuilding the
+ same code (``repair.MAX_HARNESS_REBUILDS``) and was never scored. The previous round of the same
+ workspace booted in 8 s: what changed is the code. Not ``harness_failure``, so the round's repair
+ session receives it (``tracks/repair.build_with_repair``) and the build tool reports it as a finding.
+ scene_threejs only: an offline scene's census GLB is the harness's export (:func:`run_probe`)."""
+ entry = ENTRY_FILE[Language.SCENE_THREEJS]
+ what = {"scene": f"importing {entry} and createScene()", "census": "the census of what createScene() built",
+ "update": "update(t, dt)"}.get(phase, "the scene's boot")
+ return _f(PROBE_GATE, Severity.ERROR,
+ f"scene construction exceeded the {timeout_s:.0f} s probe budget: {what} did not finish",
+ target=entry, kind="probe_timeout", timed_out=True, phase=phase,
+ hint=f"the scene must boot inside {timeout_s:.0f} s; the time is the scene's own construction work "
+ "(module-level code, createScene, update) — find what grows with the scene's size and bound it")
+
+
+def probe_scene(ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:
+ """Import-only probe: module loads, shape valid, cameras valid, update runs, census. The
+ budget defaults to the BUILD's (:func:`run_probe`): the ``scene_probe`` tool used to probe at
+ 60 s while the build allowed 120 s, so since D111 made a timeout the code's, the agent's own
+ tool would have condemned a scene the build accepts."""
report, _, census = run_probe(ws, timeout_s=timeout_s)
if census:
ws.write_json(ws.artifacts / "census.json", census)
diff --git a/harness/codeverse3d/spatial/render_scene.py b/harness/codeverse3d/spatial/render_scene.py
index 121d8f32..b0812681 100644
--- a/harness/codeverse3d/spatial/render_scene.py
+++ b/harness/codeverse3d/spatial/render_scene.py
@@ -48,8 +48,32 @@ JUDGE_MAX_VIEWS = 10
MAX_JUDGE_OVERVIEWS = 4
+#: The ``probe_scene.mjs`` watchdog phases that are the scene's own construction work (D111): the
+#: module import + createScene() + the boot settle (``scene``), the census + placement table over
+#: what it built (``census``) and ``update``. Every other phase — ``host`` (browser launch, page
+#: ready), ``report``, ``compile`` (the shader preflight), ``close`` — and a driver killed by the
+#: process clock (node itself starved: its own watchdog never got to run) are the box's.
+SCENE_PHASES = frozenset({"scene", "census", "update"})
+
+
class SceneRenderError(RuntimeError):
- """The node driver could not run (missing node/deps, timeout, crash)."""
+ """The node driver could not run (missing node/deps, timeout, crash).
+
+ ``timed_out`` (typed, D111): the driver ran out of its budget — its own watchdog's summary
+ (``lib/cli.armWatchdog``: ``timed_out: true``, exit 3) or the process clock above it — after
+ the one retry :func:`run_scene_script` grants. ``phase`` is the watchdog's word for where the
+ driver was (empty from the process clock or a driver that names none); :attr:`scene_timed_out`
+ is the one case that is a verdict on the code (``probes.run_probe``), not the box."""
+
+ def __init__(self, message: str, *, timed_out: bool = False, phase: str = ""):
+ super().__init__(message)
+ self.timed_out = timed_out
+ self.phase = phase
+
+ @property
+ def scene_timed_out(self) -> bool:
+ """The driver's own watchdog fired while the scene's code was running (:data:`SCENE_PHASES`)."""
+ return self.timed_out and self.phase in SCENE_PHASES
def _driver_failed(r: NodeResult) -> bool:
@@ -64,8 +88,9 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:
on timeout). The driver prints a JSON summary as its LAST stdout line; a
timeout or exit code 2/3 means the driver itself failed → ``SceneRenderError``.
- A driver that lost its BROWSER (``node.BROWSER_LOST_MARKERS``) is retried once on
- a browser of its own. That failure is the box, not the workspace, and without the
+ A driver that lost its BROWSER (``node.BROWSER_LOST_MARKERS``) — or whose own watchdog
+ fired (``timed_out``: a wedged shared browser times out the same way, D111) — is retried
+ once on a browser of its own. That failure is the box, not the workspace, and without the
retry it costs the round every render and therefore its judge — the object path
has retried it since 2026-08-28 (``spatial/render.py``), the scene path did not.
"""
@@ -84,16 +109,21 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:
return run_node(path, argv, cwd=cwd or rt, timeout_s=timeout_s, env_extra=env, check=False)
except NodeError as e:
if e.result is not None and e.result.timed_out:
- raise SceneRenderError(f"{script} timed out after {timeout_s:.0f}s\n{e.result.stderr_tail}") from e
+ # the PROCESS clock: node's own watchdog (timeout_s - 20 s) never ran — the box, no phase
+ raise SceneRenderError(f"{script} timed out after {timeout_s:.0f}s\n{e.result.stderr_tail}",
+ timed_out=True) from e
raise SceneRenderError(f"{script} could not run: {e}") from e
r = attempt(env_extra)
err = str(r.summary.get("error", "")) if r.summary else r.stderr_tail
lost_browser = _driver_failed(r) and browser_was_lost(err)
+ # the driver's own watchdog fired: retried on an OWNED browser, so a wedged shared one cannot
+ # time out both attempts and have the second read as the scene's construction cost (D111)
+ timed_out = not lost_browser and _driver_failed(r) and bool(r.summary.get("timed_out"))
# the rest of the transient vocabulary (`node.TRANSIENT_MARKERS`): a host that timed out
# waiting for the page under contention ("Waiting failed: 60000ms exceeded") — the object
# path retried it, this one did not, and a battery cell lost every render to it
- transient = not lost_browser and _driver_failed(r) and transient_failure(err)
+ transient = not lost_browser and not timed_out and _driver_failed(r) and transient_failure(err)
# Every scene driver ends with a JSON summary line (`lib/cli.finish` / `fail`), so a run
# that produced none had its stdout tail dropped — `proc._ABANDONED`, which a loaded box
# makes routine. That is transient and worth one more attempt; without it the empty
@@ -101,12 +131,13 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:
# boot" and spend the round's repair budget on a defect that was never there
# (desert_canyon, bench/out/scene_baseline, 2026-09-05).
lost_output = not lost_browser and not r.summary
- if lost_browser or lost_output or transient:
+ if lost_browser or lost_output or transient or timed_out:
log.warning(
"%s %s; retrying once%s",
script,
f"lost its browser ({err[:200]})" if lost_browser
else f"exited {r.rc} with no summary line (output lost)" if lost_output
+ else f"ran out of its budget in phase {r.summary.get('phase') or '?'}" if timed_out
else f"failed transiently ({err[:200]})",
"" if transient else " on an owned browser",
)
@@ -115,7 +146,8 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:
if _driver_failed(r):
raise SceneRenderError(
f"{script} failed (exit {r.rc}): {summary.get('error') if summary else ''}\n"
- f"stderr tail: {r.stderr_tail}\nstdout tail: {r.stdout[-1000:]}"
+ f"stderr tail: {r.stderr_tail}\nstdout tail: {r.stdout[-1000:]}",
+ timed_out=bool(summary.get("timed_out")), phase=str(summary.get("phase") or ""),
)
return r
diff --git a/harness/codeverse3d/spatial/scene_placement.py b/harness/codeverse3d/spatial/scene_placement.py
index 05c5c896..04248471 100644
--- a/harness/codeverse3d/spatial/scene_placement.py
+++ b/harness/codeverse3d/spatial/scene_placement.py
@@ -181,6 +181,17 @@ class Interpenetration(BaseModel):
inside_frac: float = 0.0 # vertices of the smaller inside the larger (the confirmation)
+class SceneryRoots(BaseModel):
+ """The roots outside every marked zone (D111): env scenery, a zone's stray ``scene.add`` — never
+ rows and never paired with each other; their pieces support, bury, hold (``attached``) and clip
+ the zone assets, but are not measured as placed things themselves."""
+
+ model_config = ConfigDict(extra="ignore")
+
+ n: int = 0
+ names: list[str] = Field(default_factory=list)
+
+
class PlacementTable(BaseModel):
model_config = ConfigDict(extra="ignore")
@@ -190,6 +201,8 @@ class PlacementTable(BaseModel):
checked: int = 0
truncated: bool = False
exempt: dict[str, int] = Field(default_factory=dict)
+ scenery: SceneryRoots = Field(default_factory=SceneryRoots,
+ description="roots outside the marked zones (none in a table measured before D111)")
ground_y: float | None = None
notes: list[str] = Field(default_factory=list)
thresholds: dict[str, float] = Field(default_factory=dict, description="the probe's own measurement constants")
@@ -228,6 +241,7 @@ LANGUAGE_WORDS: dict[str, dict[str, str]] = {
"lies past the bounds fades with distance instead of cutting off — the terrain, buildings, trees or "
"water out there then read as aerial perspective"),
"place": "import its builder / clone its GLB",
+ "in_zone": "as a direct child of the group the zone's build returns (what is added straight to the scene is not the zone's)",
"free_exempt": ("userData.placement = 'free' is for hanging / airborne things only (a bird, a hung lantern, a drone): "
"delete the tag on everything that stands on something and seat it with heightAt(x, z) or on its support"),
"cantilever": "seat every foot: follow the ground with heightAt(x, z) at each corner, sink it a few cm, or shorten the overhang",
@@ -244,6 +258,7 @@ LANGUAGE_WORDS: dict[str, dict[str, str]] = {
"so whatever lies past the bounds fades with distance instead of cutting off — the terrain, buildings, "
"trees or water out there then read as aerial perspective"),
"place": "place a collection-instance Empty of ctx.assets['<snake>']",
+ "in_zone": "as a root object linked into the zone's collection",
"free_exempt": ('obj["placement"] = "free" is for hanging / airborne things only (a bird, a hung lantern, a drone): '
"delete the tag on everything that stands on something and seat it with ctx.height_at(x, y) / lib.place.seat"),
"cantilever": ("seat every foot: follow the ground with ctx.height_at(x, y) at each corner (lib.place.seat), "
@@ -446,11 +461,13 @@ def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool =
f"{shown('sunken')} sunken, {shown('unsupported')} unsupported, {shown('interpenetration')} interpenetrating"
+ (f", {shown('cantilevered')} cantilevered" if counts["cantilevered"] else "")
+ (f", {n_free} tagged free ({free_share:.0%})" if n_free else "")
+ + (f"; {t.scenery.n} scenery roots outside the zones not measured" if t.scenery.n else "")
+ f"; {'indoor' if indoor else 'outdoor'} tolerance {floating_m * 100:.0f} cm, ERROR past "
f"{p.floating_error_m * 100:.0f} cm or more than {p.floating_error_count} floating"
+ ("; table truncated (first 400 assets / time budget)" if t.truncated else ""))
findings.insert(0, _f(Severity.INFO, summary, target="scene", kind="summary", counts=counts, listed=listed, checked=t.checked,
total=t.total, exempt=t.exempt, free=n_free, free_share=round(free_share, 3), truncated=t.truncated,
+ scenery=t.scenery.n,
thresholds={**p.model_dump(), "floating_m": floating_m, "indoor": indoor},
probe_thresholds=dict(t.thresholds)))
return GateReport.of(GATE, findings)
@@ -686,12 +703,26 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
by_zone.setdefault(to_snake(r.zone), []).append(r)
all_names = " ".join(_row_names(r) for r in rows)
gone = {to_snake(u) for u in unavailable}
+ # a table cut by its row cap (host_placement MAX_ASSETS: rows are written zone by zone, in scene
+ # order) stops wherever it stops: a zone past the cut has no rows although the census holds its
+ # built group, and the zone AT the cut (the last row's) has only its first rows (iteration 4,
+ # r1_01: an envelope of 337 meshes filled the table and ScooterParkingNook, built and visibly
+ # present, was "zone_empty"). A table cut by its time budget still writes a row per asset
+ # (exempt "time_budget"), so a zone with no row there really placed nothing.
+ cut = bool(table.get("truncated")) and int(table.get("total") or 0) > len(rows)
+ at_cut = to_snake(rows[-1].zone) if cut else None
+ built = {to_snake(str(g.get("name", ""))) for g in census.get("groups") or []
+ if isinstance(g, dict) and g.get("kind") in ("content", "ground")} # an EMPTY group placed nothing
for zone_name, contents in _plan_zones(plan):
zk = to_snake(zone_name)
placed = by_zone.get(zk, [])
# what the zone was allowed to place: an asset the asset stage never built was
# announced "NOT AVAILABLE" to it, for zone_empty exactly as for missing_content
expected = [c for c in contents if to_snake(c) not in gone]
+ if not placed and expected and cut and zk in built:
+ out.append(_f(Severity.INFO, f"zone {zone_name} was not measured: the placement table was truncated before "
+ "its rows (its group is in the census)", target=zone_name, kind="zone_unmeasured"))
+ continue
if not placed and expected:
out.append(_f(Severity.ERROR, f"zone {zone_name} placed nothing (plan lists: {', '.join(expected[:6])})",
target=zone_name, kind="zone_empty",
@@ -699,13 +730,17 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
continue
zone_names = " ".join(_row_names(r) for r in placed)
missing = [c for c in expected if to_snake(c) not in zone_names and to_snake(c) not in all_names]
- if missing:
+ if missing and zk == at_cut:
+ out.append(_f(Severity.INFO, f"zone {zone_name} was only partly measured: the placement table was truncated "
+ f"inside it, so {', '.join(missing[:5])} may lie past the cut",
+ target=zone_name, kind="zone_unmeasured", missing=missing[:8]))
+ elif missing:
out.append(_f(Severity.ERROR,
f"zone {zone_name} is missing planned contents: {', '.join(missing[:5])}"
+ (f" (+{len(missing) - 5} more)" if len(missing) > 5 else ""),
target=zone_name, kind="missing_content", missing=missing[:8],
hint=f"place each listed asset ({words['place']}) inside this "
- "zone's bbox AND give the object the plan's name for it — every gate and the "
+ f"zone's bbox, {words['in_zone']}, AND give the object the plan's name for it — every gate and the "
"judge find it by that name, so a lantern called 'LanternPost1' reads as absent"))
# -- plausible scale vs the plan's approx_size_m
sizes = _plan_asset_sizes(plan)
@@ -833,6 +868,7 @@ def placement_table_text(table: dict[str, Any] | PlacementTable, *, max_rows: in
if t.error:
return f"placement table unavailable: {t.error}"
lines = [f"placement: {t.checked} checked of {t.total} placed; exempt {t.exempt or '{}'}; ground_y {t.ground_y}"
+ + (f"; scenery (not measured): {', '.join(t.scenery.names[:8])}" if t.scenery.n else "")
+ ("; TRUNCATED" if t.truncated else "")]
lines.append("asset | gap to support (m) | support | sunk (m) | into | water | attached")
for r in [r for r in t.assets if not r.exempt][:max_rows]:
diff --git a/harness/codeverse3d/tracks/generation.py b/harness/codeverse3d/tracks/generation.py
index 1e6f4106..dbb1a1e4 100644
--- a/harness/codeverse3d/tracks/generation.py
+++ b/harness/codeverse3d/tracks/generation.py
@@ -309,6 +309,12 @@ class GenerationTask(BaseModel):
default=False,
description="enforce files_hint as the only existing files this session may overwrite",
)
+ shared_tree: bool = Field(
+ default=False,
+ description="other harness writers change the workspace while this task's session runs: it is "
+ "credited with its files_hint only (AgentJob.shared_tree, D111 — the scene env stage beside the "
+ "asset single-shots)",
+ )
owns_entry: bool = Field(
default=False,
description="this task may write the language entry file even under edit_only (assembly / "
@@ -564,6 +570,7 @@ def run_agent_task(
track=track,
files_hint=list(task.files_hint),
edit_only=task.edit_only,
+ shared_tree=task.shared_tree,
effort=session_effort(task),
always_writable=_always_writable(language, task),
read_only=_read_only(language),
@@ -768,13 +775,16 @@ def _attributed_fallback(ws: Workspace, task: GenerationTask, before: str) -> li
A whole-worktree diff claims sibling tasks' files under fan_out (a task that
wrote nothing looked ok because its neighbours wrote files); attribute the diff
- to this task instead: inside its write roots, never harness-owned paths."""
+ to this task instead: inside its write roots, never harness-owned paths, and —
+ ``shared_tree`` — inside its ``files_hint`` (the session's own attribution came back
+ empty, and this fallback used to hand the env task the asset files right back, D111)."""
raw = ws.changed_files(before) # Workspace serialises + retries the git index itself
try:
from codeverse3d.agents.cli_common import attribute_changes
except ImportError: # pragma: no cover — agents package always ships with tracks
return raw
- return attribute_changes(raw, write_roots=list(task.write_roots))
+ return attribute_changes(raw, write_roots=list(task.write_roots),
+ only=task.files_hint if task.shared_tree else None)
def generate(
diff --git a/harness/codeverse3d/tracks/scene.py b/harness/codeverse3d/tracks/scene.py
index 6f44e779..4e4be2d3 100644
--- a/harness/codeverse3d/tracks/scene.py
+++ b/harness/codeverse3d/tracks/scene.py
@@ -349,15 +349,52 @@ class SceneTrack(BaseTrack):
return manifest
def _env_stage(self, ctx: RunContext) -> dict[str, Any]:
+ """The env session, honest (D111): ``ok`` only when the env module ITSELF was written in this
+ stage — the session's ``files_changed`` (its ``files_hint`` alone: ``shared_tree``) or the
+ file's mtime, the test the zone stage uses. Iteration 4 of the argon loop (scene_threejs,
+ 2026-10-15): the session read for 7-10 minutes and wrote nothing in 12 of 15 runs, was
+ credited with the asset files the single-shots wrote beside it, and the stage read ``ok``;
+ round 0 was unlit and the one refine round wrote the whole environment from the skeleton.
+ A failed stage gets ONE recovery before the zones are written (:meth:`_recover_env`)."""
+ rel, t0 = env_file(ctx), time.time()
res = self._stage_session(ctx, "env", "env", self._env_task)
- return {"ok": res.ok, "files": [c.path for c in res.files_changed], "notes": res.notes}
+ written = {c.path for c in res.files_changed}
+ ok = res.ok and (rel in written or _touched(ctx.ws.root / rel, t0))
+ out = {"ok": ok, "files": sorted(written) if ok else [], "notes": res.notes}
+ if not ok and ctx.budget.ok():
+ out = self._recover_env(ctx, out)
+ return out
+
+ def _recover_env(self, ctx: RunContext, failed: dict[str, Any]) -> dict[str, Any]:
+ """One single-shot generation of the env module the session left unwritten — the
+ :meth:`_recover_zones` rule for the env stage (D111): a fresh brief, single-shot (it cannot
+ spend its window reading), bounded by the env window the budget still allows. It runs
+ before the zone stage starts, so no zone is authored against the skeleton's placeholder
+ (iteration 4, r1_01: a zone author built its own replacement world inside its zone file).
+ A recovery that also fails leaves the placeholder, and the stage reports it failed."""
+ gen = ctx if ctx.single_shot else (single_shot_ctx(ctx) or ctx)
+ rel = env_file(ctx)
+ ctx.events.emit("env.recover", file=rel, notes=str(failed.get("notes", ""))[:300])
+ t0 = time.time()
+ try:
+ task = self._env_task(gen)
+ res = generate_for(gen, task.model_copy(update={"label": f"{task.label}.recover"}))
+ except Exception as e: # noqa: BLE001 — BudgetExceeded included: the boundary check after the stage stops the run
+ out = {"ok": False, "files": [], "notes": f"recover: {type(e).__name__}: {e}"[:500]}
+ else:
+ ok = res.ok and (rel in {c.path for c in res.files_changed} or _touched(ctx.ws.root / rel, t0))
+ out = {"ok": ok, "files": [rel] if ok else [], "notes": f"recovered single-shot: {res.notes}"[:500]}
+ ctx.ws.commit("env.recover")
+ ctx.events.emit("env.recovered", ok=out["ok"], file=rel)
+ return out
def _env_task(self, ctx: RunContext) -> GenerationTask:
prompt = render(scene_templates(ctx.language).env, **self._ctx(ctx))
ctx.record_prompt("scene_env", prompt)
+ # shared_tree: the asset single-shots write src/ side by side with this session (D111)
return GenerationTask(label="env", prompt=prompt, system=self.system_prompt(ctx), files_hint=[env_file(ctx)], round=0, kind="env",
temperature=0.5, timeout_s=ctx.budget.timeout_s(ENV_TIMEOUT_S, floor_s=120),
- images=reference_images(ctx))
+ images=reference_images(ctx), shared_tree=True)
def _zones_stage(self, ctx: RunContext) -> dict[str, Any]:
plan: ScenePlan = ctx.plan # type: ignore[assignment]
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 3ca44320..134935d5 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -125,7 +125,8 @@ codeverse3d/
(claude-code / codex / antigravity: argv, env, each CLI's own record read
back — envelope, stream, conversation db, retry reports; agy's API-mode
HOME + pool key), cli_common.py (sessions, the watchdog clocks, the prompt
- on stdin, the transcript, files_changed attribution, THE failure vocabulary,
+ on stdin, the transcript, files_changed attribution — a `shared_tree` job's to
+ its files_hint, D111 —, THE failure vocabulary,
provider_wait), materialize.py
languages/ LanguageRuntime + RuntimeLayout (base.py: every runtime states its file layout —
expected_files / files_for — and the tracks ask it); one merged module per language since 2026-08-28 —
@@ -483,7 +484,10 @@ starts again at round 0 with no stage frozen. The plan itself is `run()`'s, bef
scene stages do: `assets` — both kinds climb one ladder (single-shot → check → one repair → agent;
blender_glb heroes get a sub-workspace with the static planner's parts + asset_v1 judge + one
re-judged fix pass, undone when worse; a degraded asset verdict leaves score None / judged False,
-emits asset.judge_degraded and skips the fix pass); `env` — `src/env.js`; `layouts` — L2 zone
+emits asset.judge_degraded and skips the fix pass); `env` — `env_file` (`src/env.js` / `src/env.py`): its
+session shares the tree with the asset single-shots, so it is a `shared_tree` job (credited with its own file
+only, watched for activity on it alone) and the stage is ok only when that file itself was written; else ONE
+single-shot `_recover_env` runs before the zones (`env.recover` / `env.recovered`, **D111**); `layouts` — L2 zone
layouts (planner calls, never fatal); `asset_api` — what the zones are told about the assets;
`zones` — ONE session owns every zone file (D70; a session whose charge crossed the ceiling after
it finished records the zones it wrote as written, the `BudgetExceeded` as their note); `clock` — the
@@ -542,7 +546,10 @@ after the run (`3dcode make`, unless --no-pick): addons/select.pick(by="score")
Track-specific gates: static `connectivity` + `contract` (+ `reference_silhouette`),
articulated + `joint_sweep` + `motion_direction` (URDF axis vs plan motion text),
scene `scene_placement` (`spatial/scene_placement.py`, the one gate `ScenePipeline.gates` adds: per placed
-asset, foot-column gap to the surface beneath, burial depth,
+asset — a direct child of a ZONE root, the roots the assembler marks `userData[conventions.ZONE_ROOT_KEY]`
+(scene_blender: the census GLB's zone-node extras); every other root is scenery, never a row and never paired
+with other scenery, but its pieces still support, bury, hold (`attached`) and clip the zone assets, **D111** —
+foot-column gap to the surface beneath, burial depth,
water, contacts and 3-D interpenetration pairs from `runtime_js/lib/host_placement.mjs` — the
first deterministic placement check on the track; before 2026-08-26 the scene_v1
`floating_part` cap could never fire and floating/sunken was left to the VLM) +
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 596f10ae..40b1a71d 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -247,7 +247,12 @@ An expired job never launches a CLI. Recomputed on resume; `None` keeps standalo
session grace. Process termination and final packaging can finish after the deadline),
`mcp_command` (override), `files_hint` (workspace-relative files/dirs the task is
expected to touch — used to attribute `files_changed`; harness-owned paths are dropped;
-sessions on one workspace are serialised, so there is no sibling filter),
+agent sessions on one workspace are serialised, so there is no sibling filter), **Δ D111**
+`shared_tree: bool` (harness writers that take no session lock — the scene asset single-shots — write
+the tree while the session runs: `files_changed` is the `files_hint` paths only
+(`cli_common.attribute_changes(files, write_roots=, only=)`, also `generation._attributed_fallback`) and the
+watchdog polls only those files (`cli_common.activity_paths(s)`); needs a `files_hint`, never with
+`edit_only` — a validator; `GenerationTask.shared_tree` carries it; the scene env task sets it),
`edit_only` / `always_writable` (a scoped refine may overwrite only its hinted files +
the entry file), **Δ D110** `effort: AgentEffort | None` (`Literal["low","medium","high"]`; filled from
`GenerationTask.thinking` only when the caller asked — `tracks.generation.session_effort`; None = the
@@ -304,6 +309,22 @@ rt.env_file: str # Δ 2026-10-14 (D105) src
# glb = an OFFLINE scene's census GLB (probe_scene.mjs --glb → runtime_js/lib/glb_scene.mjs, served at /__census.glb;
# host_page.openHost(..., glb=)), facts merged into the census by probes.merge_facts before any finding;
# probes.probe_result (was _result); conventions.glb_basis(language) (3×3, language frame → GLB frame)
+# Δ 2026-10-16 (D111) render_scene.SceneRenderError(message, *, timed_out=False, phase=""): timed_out = the driver
+# ran out of its budget (its watchdog's summary `timed_out: true` + `phase`, exit 3 — retried once on an OWNED
+# browser — or the process clock, phase ""); .scene_timed_out = timed_out and phase in render_scene.SCENE_PHASES
+# {"scene", "census", "update"} (probe_scene.mjs sets the phase; lib/cli.armWatchdog(ms, onFire) merges onFire()'s
+# return into the summary; host_page.openHost(..., onBoot=) is called before the import). Only then, and never
+# for a census GLB (glb=), run_probe returns probes.timeout_finding(timeout_s, *, phase) — an ERROR kind
+# "probe_timeout" on the entry file, NOT harness_failure (build_with_repair hands it to a repair session).
+# probes.probe_scene / rt.probe(ws, *, timeout_s: float | None = None): None = the build's budget.
+# Δ (D111) conventions.ZONE_ROOT_KEY = "c3d_zone": the assembler sets userData[ZONE_ROOT_KEY] = <zone> on every zone
+# root (render_scene_js addZone; scene_blender: write_census_glb(..., zone_key=) ← run_bpy_scene.py --zone-key);
+# host_placement.mjs (ZONE_ROOT_KEY, pinned) rows = children of marked roots only; the other roots' children are
+# scenery pieces — supports, `attached` targets (gate + settle), interpenetration partners of zone assets only
+# (the zone asset is `a`); the table gains scenery {n, names} (scene_placement.PlacementTable.scenery:
+# SceneryRoots); an unmarked scene keeps the old rule. contract_findings: a table cut by its row cap
+# (total > rows) → INFO "zone_unmeasured" instead of zone_empty (the zone's census group content/ground) and
+# instead of missing_content for the last row's zone.
from codeverse3d.prompts.catalog import language_prompt, language_text
language_prompt(language, name) -> str # "<dir>/<name>" under prompts/ (urdf_blender → urdf/): THE per-language prompt
language_text(language, name) -> str # its text, "" for a file the language does not ship (Δ 2026-09-22: replaces
@@ -562,6 +583,8 @@ StageNode(name, run: (track, ctx) -> Any, key: (ctx) -> dict | None = None, when
run_stages(track, ctx, runner, stages) -> None; plan_stage_key(spec, track) -> dict # the plan's key (eval pin_plan too)
StageRunner(ws, events, state=None, *, frozen=False) # frozen (rounds exist): a recorded stage is served whatever its key
from codeverse3d.orchestrator import RoundPolicy, build_refine_instructions, compact_instructions, gate_error_count
+# Δ 2026-10-16 (D111) build_refine_instructions de-duplicates a gate task on (target, "gate:<gate>", finding
+# data["kind"]): two env ERRORs of scene_placement (no_fog, no_background) are two tasks
RoundPolicy(max_rounds=4, max_refine_tasks=6, max_instructions_per_task=6, parallel_min_tasks=2,
n_candidates=1, judge_samples=1) # lifecycle.build_context: judge_samples = Settings.judge.samples (N74), n_candidates by ONE dataclasses.replace
# Δ 2026-09-22 FIXED rounds: a run is the baseline + max_rounds refine rounds, EACH built on the round before
diff --git a/harness/runtime_js/lib/cli.mjs b/harness/runtime_js/lib/cli.mjs
index 6cefba7a..1a24b5b9 100644
--- a/harness/runtime_js/lib/cli.mjs
+++ b/harness/runtime_js/lib/cli.mjs
@@ -72,12 +72,15 @@ export function safeName(name, label = 'name') {
return s;
}
-/** Wall-clock guard: kills the process if the driver exceeds its budget. */
+/** Wall-clock guard: kills the process if the driver exceeds its budget. `onFire()` may
+ * return extra summary fields (probe_scene.mjs: the `phase` the driver was in, D111). */
export function armWatchdog(ms, onFire) {
const t = setTimeout(() => {
- try { onFire && onFire(); } catch (e) { /* ignore */ }
+ let extra = null;
+ try { extra = onFire ? onFire() : null; } catch (e) { /* ignore */ }
process.stderr.write(`error: driver exceeded ${ms} ms budget\n`);
- finish({ ok: false, error: `timeout after ${ms} ms` }, 3); // flushes; see finish()
+ // `timed_out` (+ `phase`) are the typed words the python side reads (render_scene.SceneRenderError, D111)
+ finish({ ok: false, error: `timeout after ${ms} ms`, timed_out: true, ...(extra || {}) }, 3); // flushes; see finish()
}, ms);
t.unref();
return t;
diff --git a/harness/runtime_js/lib/host_page.mjs b/harness/runtime_js/lib/host_page.mjs
index c1a45345..fb40099b 100644
--- a/harness/runtime_js/lib/host_page.mjs
+++ b/harness/runtime_js/lib/host_page.mjs
@@ -49,10 +49,11 @@ export function requestFailureLine(url, base, hasResponse, errorText) {
}
/**
- * Open the host for workspace `wsRoot`.
+ * Open the host for workspace `wsRoot`. `onBoot()` is called once the page is ready, right before
+ * the scene module is imported and createScene() runs (probe_scene.mjs: the watchdog's phase, D111).
* @returns {Promise<{page, browser, base, gpu, renderer, errors, boot, close}>}
*/
-export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0, settle = true, cameraRepair = false, autoExposure = false, post = true, postOptions = null, glb = null } = {}) {
+export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0, settle = true, cameraRepair = false, autoExposure = false, post = true, postOptions = null, glb = null, onBoot = null } = {}) {
wsRoot = path.resolve(wsRoot);
// an offline scene (`glb`: its census GLB) boots the harness adapter, never a workspace module
const sceneFile = glb || path.join(wsRoot, sceneRel);
@@ -99,6 +100,7 @@ export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto
});
await page.goto(`${srv.base}/__host.html`, { waitUntil: 'load', timeout: 60000 });
await page.waitForFunction('window.__c3v_ready === true', { timeout: 60000 });
+ if (onBoot) onBoot();
const boot = await page.evaluate(
(o) => window.__c3v.boot(o),
{ sceneUrl, width, height, logDepth, createSceneTimeoutMs, settle, cameraRepair, autoExposure, post, postOptions },
diff --git a/harness/runtime_js/lib/host_placement.mjs b/harness/runtime_js/lib/host_placement.mjs
index 3d6a4612..cd114548 100644
--- a/harness/runtime_js/lib/host_placement.mjs
+++ b/harness/runtime_js/lib/host_placement.mjs
@@ -6,9 +6,14 @@
* assets were left to the VLM (defect −0.06), while the scene_v1 `floating_part`
* cap could never fire because no gate emitted those words.
*
- * A "placed asset" is each direct child of a top-level scene child (the zone
- * groups the census already calls `groups`) that has Mesh descendants; a
- * top-level Mesh is an asset of its own. Assets are named by Object3D name.
+ * A "placed asset" is each direct child of a ZONE ROOT that has Mesh descendants.
+ * The zone roots are the objects the harness's own assembler marks with
+ * `userData[ZONE_ROOT_KEY]` (conventions.ZONE_ROOT_KEY; scene_blender: the census GLB's zone
+ * node extras) — D111, 2026-10-16. Every other root (env scenery, a zone's stray
+ * `scene.add`) is SCENERY: no rows, never paired, never in the free share — but its meshes
+ * still support and bury the zone assets. A scene the harness did not assemble carries no
+ * mark: there every top-level child is a zone root and a top-level Mesh an asset of its
+ * own, as before. Assets are named by Object3D name.
*
* Per asset (all in world space, metres):
* bbox exact AABB of its (non-instanced) mesh vertices
@@ -62,6 +67,10 @@
import { classifyBackdrop, GROUND_NAME_RE, nonSolid, nameText, nameWords, splitInstance } from './backdrop.mjs';
import { geometryTriangles } from './census.mjs';
+//: the harness's zone-root mark (python twin: conventions.ZONE_ROOT_KEY; tests/scene_runtime/test_zone_roots.py pins them)
+export const ZONE_ROOT_KEY = 'c3d_zone';
+//: scenery root names recorded in the table (the count is exact)
+export const MAX_SCENERY_NAMES = 24;
export const MAX_ASSETS = 400;
export const TIME_BUDGET_MS = 4000;
export const CONTACT_TOL_M = 0.02;
@@ -227,89 +236,134 @@ function indexMeshes(scene, notes) {
function isFree(obj) { return !!(obj && obj.userData && obj.userData.placement === 'free'); }
-/** The placed assets: direct children of each top-level scene child (or a top-level mesh itself). */
+function isZoneRoot(obj) { return !!(obj && obj.userData && obj.userData[ZONE_ROOT_KEY]); }
+
+/**
+ * The roots whose direct children are the placed assets, and the scenery roots beside them.
+ * Marked zone roots are found anywhere in the tree (the assembler's own probe nests each in a
+ * wrapper), a marked root's subtree is not searched further. Why (D111, argon loop iteration 4,
+ * 2026-10-15): every top-level child used to be a "zone", so an env-built wall merged per material
+ * became a body row, a flashing row and a pier row that overlap by construction; a two-mesh bollard
+ * was a cap "interpenetrating" its post; a zone's envelope added straight to the scene filled 337 of
+ * the 400 rows. A replay of four of its runs put 3-15 placement ERRORs each on roots outside the
+ * zones; in two of them every final ERROR was of that kind (scenery-vs-scenery is never paired now;
+ * zone-vs-scenery still is, collectAssets).
+ */
+function zoneRoots(scene) {
+ const marked = [];
+ const walk = (o) => { for (const c of o.children) { if (isZoneRoot(c)) marked.push(c); else walk(c); } };
+ walk(scene);
+ if (!marked.length) return { roots: scene.children, scenery: [] };
+ const holdsZone = (o) => { let found = false; o.traverse((d) => { if (!found && isZoneRoot(d)) found = true; }); return found; };
+ const scenery = scene.children.filter((c) => c.visible && !c.isLight && !c.isCamera && !holdsZone(c));
+ return { roots: marked, scenery };
+}
+
+/** One root's measurable pieces: its direct children (or the root itself when it is a mesh). */
+function piecesOf(root) {
+ if (!root.visible || root.isLight || root.isCamera) return [];
+ return (root.isMesh || root.isInstancedMesh ? [root] : root.children).filter((c) => c.visible && !c.isLight && !c.isCamera);
+}
+
+/** The placed assets: direct children of each zone root (or a zone root that is a mesh itself) —
+ * and, measured the same way but never rows, the SCENERY PIECES (the children of every root outside
+ * the zones). A zone asset still touches and clips them: a sconce flush on an env facade is mounted
+ * on it (`attached`, and the settle leaves it), a storefront pushed through an env wall is an
+ * interpenetration; only scenery-vs-scenery is never paired (D111). */
function collectAssets(scene, indices, volumetrics, contentBox) {
const assets = [];
+ const sceneryPieces = [];
let total = 0;
const seen = new Set();
- for (const zone of scene.children) {
- if (!zone.visible || zone.isLight || zone.isCamera) continue;
- const children = zone.isMesh || zone.isInstancedMesh ? [zone] : zone.children;
- for (const child of children) {
- if (!child.visible || child.isLight || child.isCamera || seen.has(child)) continue;
+ const { roots, scenery } = zoneRoots(scene);
+ for (const zone of roots) {
+ for (const child of piecesOf(zone)) {
+ if (seen.has(child)) continue;
seen.add(child);
- const meshes = [];
- let instanced = 0;
- let volumetric = 0;
- // Named descendants, not just this row's own name: a zone often wraps its content in
- // one group ("IslandAssembly"), and the plan-contents check reads names off these
- // rows. Measured 2026-09-05 (scene_fixed/floating_islands): Windmill, FloatingRock
- // and SkyPine were built and named correctly, added to `IslandAssembly`, and three
- // zones were reported as "missing planned contents".
- const inner = [];
- // Per named FAMILY below this row, the world AABB of each member (a member = one named
- // descendant, its meshes pooled). A zone wraps a scatter in one group ('PicketFences' =
- // twelve 'PicketFence' builder outputs along a path, 'GorseBushClusters' = eight bushes
- // over 12 m), and the plan sized the INSTANCE: measured 2026-09-07 (loop 9 lighthouse),
- // the scale check read the wrapper's 14.7 m against the plan's 2.4 m fence, the judge
- // repeated "6.1x too large", and the repair shrank the whole run to microscopic dots.
- const members = new Map(); // family -> Map(member object -> [min, max])
- child.traverse((o) => {
- if (!o.visible) return;
- // one slot per FAMILY (Planter_3 / Planter.003 → Planter): the by-name check matches on
- // the plan's word, and 30 numbered props must not push the hero behind them past the cap
- const family = o.name ? splitInstance(o.name)[0] : '';
- if (o !== child && family && inner.length < MAX_INNER_NAMES && !inner.includes(family)) inner.push(family);
- if (o.isInstancedMesh) instanced += 1;
- else if (indices.has(o)) {
- const ci = indices.get(o);
- meshes.push(ci);
- for (let m = o; m && m !== child; m = m.parent) {
- if (!m.name) continue;
- const fam = splitInstance(m.name)[0];
- if (!members.has(fam)) members.set(fam, new Map());
- const box = members.get(fam).get(m) || [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];
- for (let k = 0; k < 3; k++) { box[0][k] = Math.min(box[0][k], ci.min[k]); box[1][k] = Math.max(box[1][k], ci.max[k]); }
- members.get(fam).set(m, box);
- }
- }
- else if (volumetrics.has(o)) volumetric += 1;
- });
- if (!meshes.length && !instanced && !volumetric) continue;
+ const a = measurePiece(zone, child, indices, volumetrics, contentBox, total);
+ if (!a) continue;
total += 1;
- if (assets.length >= MAX_ASSETS) continue;
- const families = {};
- for (const [fam, byMember] of members) {
- if (byMember.size < 2) continue;
- const sizes = [...byMember.values()].map(([lo, hi]) => Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2])).sort((x, y) => x - y);
- families[fam] = { n: sizes.length, size_m: r3(sizes[Math.floor(sizes.length / 2)]) };
- }
- const a = { obj: child, name: child.name || `${child.type}_${total}`, zone: zone === child ? '' : (zone.name || zone.type), meshes, instanced, inner, families, exempt: '' };
- if (isFree(zone) || isFree(child)) a.exempt = 'free';
- // the env's room shell (walls, lid, sills, lintels, trim under a `RoomShell…` root — the same
- // name the overview rig lifts) is the enclosure, never a placed asset: its members abut and
- // overlap each other by construction (2026-10-15: 24 of 41 Blender interpenetration ERRORs
- // in the loop's iteration 0 were lintel x ceiling / trim x trim pairs of one shell)
- else if (String(zone.name || '').startsWith('RoomShell')) a.exempt = 'enclosure';
- // instanced first: an asset that is scatter PLUS a haze shell is exempt because its
- // instances cannot be sampled at this budget, which is the more informative reason
- else if (!meshes.length && instanced) a.exempt = 'instanced';
- else if (!meshes.length && volumetric) a.exempt = 'volumetric';
- else {
- a.min = [Infinity, Infinity, Infinity]; a.max = [-Infinity, -Infinity, -Infinity];
- let backdrop = 0;
- for (const ci of meshes) {
- for (let k = 0; k < 3; k++) { a.min[k] = Math.min(a.min[k], ci.min[k]); a.max[k] = Math.max(a.max[k], ci.max[k]); }
- // a ground / floor / water surface is what things sit ON, whatever its size
- if (ci.kind !== 'content' || ci.groundLike || ci.water) backdrop += 1;
- }
- if (backdrop === meshes.length || GROUND_NAME_RE.test(nameText(a.name)) || WATER_RE.test(nameText(a.name))) a.exempt = 'backdrop';
- else if (contentBox && enclosesContent(a, contentBox)) a.exempt = 'enclosure';
+ if (assets.length < MAX_ASSETS) assets.push(a);
+ }
+ }
+ for (const root of scenery) {
+ for (const child of piecesOf(root)) {
+ const a = measurePiece(root, child, indices, volumetrics, contentBox, sceneryPieces.length);
+ // only a solid, non-exempt piece can hold or clip a zone asset — the rule the zone assets
+ // themselves follow (a ground / water / enclosing shell is a backdrop: things stand ON it)
+ if (a && !a.exempt) { a.scenery = true; sceneryPieces.push(a); }
+ }
+ }
+ return { assets, total, scenery, sceneryPieces };
+}
+
+/** Measure one piece (`child` of `zone`): its meshes, named inner families, AABB and exemption;
+ * null when it holds nothing measurable at all. */
+function measurePiece(zone, child, indices, volumetrics, contentBox, ordinal) {
+ const meshes = [];
+ let instanced = 0;
+ let volumetric = 0;
+ // Named descendants, not just this row's own name: a zone often wraps its content in
+ // one group ("IslandAssembly"), and the plan-contents check reads names off these
+ // rows. Measured 2026-09-05 (scene_fixed/floating_islands): Windmill, FloatingRock
+ // and SkyPine were built and named correctly, added to `IslandAssembly`, and three
+ // zones were reported as "missing planned contents".
+ const inner = [];
+ // Per named FAMILY below this row, the world AABB of each member (a member = one named
+ // descendant, its meshes pooled). A zone wraps a scatter in one group ('PicketFences' =
+ // twelve 'PicketFence' builder outputs along a path, 'GorseBushClusters' = eight bushes
+ // over 12 m), and the plan sized the INSTANCE: measured 2026-09-07 (loop 9 lighthouse),
+ // the scale check read the wrapper's 14.7 m against the plan's 2.4 m fence, the judge
+ // repeated "6.1x too large", and the repair shrank the whole run to microscopic dots.
+ const members = new Map(); // family -> Map(member object -> [min, max])
+ child.traverse((o) => {
+ if (!o.visible) return;
+ // one slot per FAMILY (Planter_3 / Planter.003 → Planter): the by-name check matches on
+ // the plan's word, and 30 numbered props must not push the hero behind them past the cap
+ const family = o.name ? splitInstance(o.name)[0] : '';
+ if (o !== child && family && inner.length < MAX_INNER_NAMES && !inner.includes(family)) inner.push(family);
+ if (o.isInstancedMesh) instanced += 1;
+ else if (indices.has(o)) {
+ const ci = indices.get(o);
+ meshes.push(ci);
+ for (let m = o; m && m !== child; m = m.parent) {
+ if (!m.name) continue;
+ const fam = splitInstance(m.name)[0];
+ if (!members.has(fam)) members.set(fam, new Map());
+ const box = members.get(fam).get(m) || [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];
+ for (let k = 0; k < 3; k++) { box[0][k] = Math.min(box[0][k], ci.min[k]); box[1][k] = Math.max(box[1][k], ci.max[k]); }
+ members.get(fam).set(m, box);
}
- assets.push(a);
}
+ else if (volumetrics.has(o)) volumetric += 1;
+ });
+ if (!meshes.length && !instanced && !volumetric) return null;
+ const families = {};
+ for (const [fam, byMember] of members) {
+ if (byMember.size < 2) continue;
+ const sizes = [...byMember.values()].map(([lo, hi]) => Math.max(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2])).sort((x, y) => x - y);
+ families[fam] = { n: sizes.length, size_m: r3(sizes[Math.floor(sizes.length / 2)]) };
}
- return { assets, total };
+ const a = { obj: child, name: child.name || `${child.type}_${ordinal}`, zone: zone === child ? '' : (zone.name || zone.type), meshes, instanced, inner, families, exempt: '' };
+ if (isFree(zone) || isFree(child)) a.exempt = 'free';
+ // (the `RoomShell…` name exemption of 2026-10-15 is gone, D111: the env's room shell is a
+ // scenery root of a marked scene, so its walls, lid and lintels are never rows at all)
+ // instanced first: an asset that is scatter PLUS a haze shell is exempt because its
+ // instances cannot be sampled at this budget, which is the more informative reason
+ else if (!meshes.length && instanced) a.exempt = 'instanced';
+ else if (!meshes.length && volumetric) a.exempt = 'volumetric';
+ else {
+ a.min = [Infinity, Infinity, Infinity]; a.max = [-Infinity, -Infinity, -Infinity];
+ let backdrop = 0;
+ for (const ci of meshes) {
+ for (let k = 0; k < 3; k++) { a.min[k] = Math.min(a.min[k], ci.min[k]); a.max[k] = Math.max(a.max[k], ci.max[k]); }
+ // a ground / floor / water surface is what things sit ON, whatever its size
+ if (ci.kind !== 'content' || ci.groundLike || ci.water) backdrop += 1;
+ }
+ if (backdrop === meshes.length || GROUND_NAME_RE.test(nameText(a.name)) || WATER_RE.test(nameText(a.name))) a.exempt = 'backdrop';
+ else if (contentBox && enclosesContent(a, contentBox)) a.exempt = 'enclosure';
+ }
+ return a;
}
function enclosesContent(a, cb) {
@@ -407,20 +461,28 @@ function containment(small, large) {
return { frac: sampled ? inside / sampled : 0, sampled };
}
-function pairs(checked) {
+/** Every touching pair of checked zone assets, and of a checked zone asset with a scenery piece
+ * (never two scenery pieces, D111): both sides of a touch are `attached`, an overlap past the floor
+ * whose vertices confirm it is an interpenetration. A zone-vs-scenery pair names the zone asset
+ * `a` whichever is smaller: the finding targets `a`, and the zone author is the one who can move it. */
+function pairs(checked, sceneryPieces = []) {
const out = [];
+ const vol = (o) => [0, 1, 2].reduce((v, k) => v * Math.max(0.01, o.max[k] - o.min[k]), 1);
+ const test = (a, b) => {
+ if (!touches(a, b, CONTACT_TOL_M)) return;
+ a.attached.push(b.name);
+ if (!b.scenery) b.attached.push(a.name);
+ const aabb = boxOverlapFrac(a, b);
+ if (aabb <= OVERLAP_MIN_FRAC) return;
+ const [small, large] = vol(a) <= vol(b) ? [a, b] : [b, a];
+ const c = containment(small, large);
+ if (c.frac <= OVERLAP_MIN_FRAC) return;
+ const [x, y] = b.scenery ? [a, b] : [small, large];
+ out.push({ a: x.name, b: y.name, zone_a: x.zone, zone_b: y.zone, aabb_overlap: r3(aabb), inside_frac: r3(c.frac), samples: c.sampled });
+ };
for (let i = 0; i < checked.length; i++) {
- for (let j = i + 1; j < checked.length; j++) {
- const a = checked[i], b = checked[j];
- if (!touches(a, b, CONTACT_TOL_M)) continue;
- a.attached.push(b.name); b.attached.push(a.name);
- const aabb = boxOverlapFrac(a, b);
- if (aabb <= OVERLAP_MIN_FRAC) continue;
- const vol = (o) => [0, 1, 2].reduce((v, k) => v * Math.max(0.01, o.max[k] - o.min[k]), 1);
- const [small, large] = vol(a) <= vol(b) ? [a, b] : [b, a];
- const c = containment(small, large);
- if (c.frac > OVERLAP_MIN_FRAC) out.push({ a: small.name, b: large.name, zone_a: small.zone, zone_b: large.zone, aabb_overlap: r3(aabb), inside_frac: r3(c.frac), samples: c.sampled });
- }
+ for (let j = i + 1; j < checked.length; j++) test(checked[i], checked[j]);
+ for (const s of sceneryPieces) test(checked[i], s);
}
return out.sort((x, y) => y.aabb_overlap - x.aabb_overlap).slice(0, 40);
}
@@ -430,11 +492,11 @@ function survey(scene, opts) {
const notes = [];
scene.updateMatrixWorld(true);
const { map: indices, volumetric } = indexMeshes(scene, notes);
- const { assets, total } = collectAssets(scene, indices, volumetric, opts.contentBox || null);
+ const { assets, total, scenery, sceneryPieces } = collectAssets(scene, indices, volumetric, opts.contentBox || null);
const meshOwner = new Map();
for (const a of assets) { a.meshSet = new Set(a.meshes); for (const ci of a.meshes) meshOwner.set(ci.mesh, a.name); }
const groundY = Number.isFinite(opts.groundY) ? opts.groundY : null;
- return { groundY, notes, indices, assets, total, owner: (mesh) => meshOwner.get(mesh) || nearestName(mesh) };
+ return { groundY, notes, indices, assets, total, scenery, sceneryPieces, owner: (mesh) => meshOwner.get(mesh) || nearestName(mesh) };
}
/** Probe every foot column of `a`: smallest gap (`best`) and largest (`gapMax`), how many columns
@@ -468,7 +530,7 @@ function probeFeet(a, indices, owner, groundY) {
*/
export function placementTable(scene, THREE, opts = {}) {
const t0 = Date.now();
- const { groundY, notes, indices, assets, total, owner } = survey(scene, opts);
+ const { groundY, notes, indices, assets, total, scenery, sceneryPieces, owner } = survey(scene, opts);
const checked = [];
let timeCut = false;
const rows = [];
@@ -494,7 +556,7 @@ export function placementTable(scene, THREE, opts = {}) {
checked.push(a);
rows.push(row);
}
- const inter = pairs(checked);
+ const inter = pairs(checked, sceneryPieces);
for (const a of checked) {
const row = a.row;
row.attached = a.attached.slice(0, 8);
@@ -508,6 +570,8 @@ export function placementTable(scene, THREE, opts = {}) {
return {
version: 1, assets: rows, interpenetrations: inter, total, checked: checked.length,
truncated: total > assets.length || timeCut, truncated_by_time: timeCut, exempt,
+ // the roots outside every marked zone (D111): measured as nothing, listed so nothing is silent
+ scenery: { n: scenery.length, names: scenery.slice(0, MAX_SCENERY_NAMES).map((o) => o.name || o.type) },
thresholds: { contact_m: CONTACT_TOL_M, floating_m: FLOATING_M, sunk_m: SUNK_M, overlap_min: OVERLAP_MIN_FRAC },
ground_y: groundY, notes, duration_ms: Date.now() - t0,
};
@@ -549,8 +613,11 @@ export function settleScene(scene, THREE, opts = {}) {
if (!opts.words) throw new Error('settleScene needs opts.words (runtime_js/lib/placement_words.json)');
const buriedOk = new Set(opts.words.buried_ok), slopeOk = new Set(opts.words.slope_ok);
const partialOk = new Set(opts.words.partial_ok), partialFrac = opts.words.partial_ok_frac;
- const { groundY, indices, assets, owner } = survey(scene, opts);
+ const { groundY, indices, assets, sceneryPieces, owner } = survey(scene, opts);
const checked = assets.filter((a) => !a.exempt);
+ // what a floating asset may be mounted on: another zone asset or a scenery piece (an env facade
+ // holding a sign or a sconce, D111) — the gate's `attached` rule, pairs() above
+ const neighbours = [...checked, ...sceneryPieces];
const moves = [];
const t0 = Date.now();
for (const a of checked) {
@@ -579,7 +646,7 @@ export function settleScene(scene, THREE, opts = {}) {
} else { continue; }
} else if (best && best.gap !== null && best.gap > FLOATING_M) {
// mounted on a neighbour? touching anything → leave it alone
- if (checked.some((b) => b !== a && touches(a, b, CONTACT_TOL_M))) continue;
+ if (neighbours.some((b) => b !== a && touches(a, b, CONTACT_TOL_M))) continue;
dy = -(best.gap - SETTLE_SEAT_EPS_M); // drop onto the support
why = 'floating';
} else { continue; }
diff --git a/harness/runtime_js/probe_scene.mjs b/harness/runtime_js/probe_scene.mjs
index 27c6ad93..20bae5f3 100644
--- a/harness/runtime_js/probe_scene.mjs
+++ b/harness/runtime_js/probe_scene.mjs
@@ -68,7 +68,12 @@ function fitCameras(census, azimuth, bounds) {
async function main() {
if (!args.ws) throw new Error('--ws is required');
const timeoutMs = parseInt(args['timeout-ms'], 10);
- const watchdog = armWatchdog(timeoutMs);
+ // The phase the watchdog reports when the budget runs out (D111; python: render_scene.SCENE_PHASES).
+ // `scene` (import, createScene, the boot settle), `census` (census + placement table) and `update`
+ // are the scene's own construction work, a verdict on the code; `host` (browser launch, page ready),
+ // `report`, `compile` (the shader preflight) and `close` are the box's.
+ let phase = 'host';
+ const watchdog = armWatchdog(timeoutMs, () => ({ phase }));
const t0 = Date.now();
let host;
try {
@@ -80,6 +85,7 @@ async function main() {
cameraRepair: !!args['camera-repair'],
autoExposure: !!args['auto-exposure'],
post: false,
+ onBoot: () => { phase = 'scene'; },
});
} catch (e) {
return fail(`host failed: ${e.message}`);
@@ -88,6 +94,7 @@ async function main() {
const result = { ok: false, renderer: boot.renderer || host.renderer, gpu: host.gpu, boot, census: null, update_ok: null, update_error: '', shader_errors: [] };
try {
if (boot.ok) {
+ phase = 'census';
result.census = await page.evaluate(() => window.__c3v.census());
// placement table (floating / sunken / unsupported / interpenetration per asset);
// a failure here must never fail the probe — the python gate reports it as a WARN
@@ -97,6 +104,7 @@ async function main() {
result.census.placement = { error: String((e && e.message) || e).slice(0, 400) };
}
// exercise update() for a few fixed steps and one tiny render (lazy programs compile)
+ phase = 'update';
const upd = await page.evaluate((n) => {
try {
const animation_hooks = window.__c3v.probeUpdateHooks(n / 30);
@@ -125,6 +133,7 @@ async function main() {
const bounds = args.bounds !== 'none' ? readJsonArg(args.bounds, 'bounds') : null;
if (Number.isFinite(sunAz)) result.fitted_cameras = fitCameras(result.census, sunAz, bounds);
}
+ phase = 'report';
// Probe truth is snapshotted BEFORE any forced compile: the probe gate sees
// exactly what a standalone probe would; the preflight below sees everything.
result.shader_errors = (await page.evaluate(() => window.__c3v.shaderErrors())).map(({ _key, ...e }) => e);
@@ -132,6 +141,7 @@ async function main() {
result.ok = boot.ok && result.update_ok === true && result.console_errors.length === 0 && result.shader_errors.length === 0;
if (args.compile) {
+ phase = 'compile';
const ts = Date.now();
if (boot.ok) {
const { report, files } = staticShaderReport(path.resolve(args.ws), null);
@@ -146,6 +156,7 @@ async function main() {
}
result.duration_ms = Date.now() - t0;
+ phase = 'close';
clearTimeout(watchdog);
await host.close();
if (args.out) writeJson(path.resolve(args.out), result);
diff --git a/harness/tests/agents/test_shared_tree.py b/harness/tests/agents/test_shared_tree.py
new file mode 100644
index 00000000..baf598e2
--- /dev/null
+++ b/harness/tests/agents/test_shared_tree.py
@@ -0,0 +1,122 @@
+"""D111: a session that shares its workspace with lock-free harness writers is credited with its own files.
+
+Argon loop iteration 4 (scene_threejs, 2026-10-15): the env session read for 7-10 minutes and wrote
+nothing in 12 of 15 runs; the asset single-shots wrote ``src/assets/*`` beside it, the whole-tree diff
+credited the env session with those files, its stage read ``ok``, and the same asset writes kept its
+idle clock alive until ~300 s after the asset stage ended. ``AgentJob.shared_tree`` narrows both
+the attribution and the activity watch to ``files_hint``.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+from pydantic import ValidationError
+
+from codeverse3d.agents.cli_common import (
+ activity_paths,
+ attribute_changes,
+ begin_session,
+ finish_session,
+ run_with_watchdog,
+)
+from codeverse3d.contracts.agent import AgentJob, FileChange
+from codeverse3d.contracts.common import Usage
+from codeverse3d.tracks.generation import GenerationTask, _attributed_fallback
+from codeverse3d.workspace import Workspace
+
+ENV, ASSET = "src/env.js", "src/assets/lantern.js"
+
+
+def _tree(ws: Workspace) -> None:
+ (ws.src / "assets").mkdir(parents=True, exist_ok=True)
+ (ws.root / ENV).write_text("// placeholder env\n")
+ (ws.root / ASSET).write_text("// asset stub\n")
+ ws.commit("skeleton")
+
+
+def _job(ws: Workspace, **kw) -> AgentJob:
+ return AgentJob(workspace=str(ws.root), prompt="p", label="env", round=0, files_hint=[ENV], **kw)
+
+
+def test_attribution_under_only_drops_what_the_hint_does_not_name():
+ files = [FileChange(path=ENV, status="modified"), FileChange(path=ASSET, status="modified"),
+ FileChange(path="src/lib/x.js", status="added")]
+ assert [f.path for f in attribute_changes(files, write_roots=["src"])] == [ENV, ASSET, "src/lib/x.js"]
+ assert [f.path for f in attribute_changes(files, write_roots=["src"], only=[ENV])] == [ENV]
+ assert [f.path for f in attribute_changes(files, write_roots=["src"], only=["src/assets/"])] == [ASSET]
+
+
+def test_a_shared_tree_session_that_wrote_nothing_is_not_credited_with_a_concurrent_write(tmp_ws: Workspace):
+ _tree(tmp_ws)
+ s = begin_session(_job(tmp_ws, shared_tree=True), "agy")
+ (tmp_ws.root / ASSET).write_text("// the asset single-shot's work, written meanwhile\n")
+ res = finish_session(s, ok=True, exit_reason="timeout", text="", usage=Usage())
+ assert res.files_changed == [], res.files_changed
+ assert (tmp_ws.root / ASSET).read_text().startswith("// the asset single-shot"), "never reverted: not edit_only"
+
+
+def test_a_shared_tree_session_that_wrote_its_file_is_credited_with_it_alone(tmp_ws: Workspace):
+ _tree(tmp_ws)
+ s = begin_session(_job(tmp_ws, shared_tree=True), "agy")
+ (tmp_ws.root / ENV).write_text("// the real env\n")
+ (tmp_ws.root / ASSET).write_text("// concurrent\n")
+ res = finish_session(s, ok=True, exit_reason="completed", text="", usage=Usage())
+ assert [f.path for f in res.files_changed] == [ENV]
+
+
+def test_a_plain_session_still_owns_the_whole_diff(tmp_ws: Workspace):
+ """Not shared_tree: a refine session that also fixed a file outside its hint keeps it (a narrower
+ attribution would turn real work into ``ok=False`` and a RoundFailed)."""
+ _tree(tmp_ws)
+ s = begin_session(_job(tmp_ws), "agy")
+ (tmp_ws.root / ASSET).write_text("// fixed here too\n")
+ res = finish_session(s, ok=True, exit_reason="completed", text="", usage=Usage())
+ assert [f.path for f in res.files_changed] == [ASSET]
+
+
+def test_the_generation_fallback_attributes_the_same_way(tmp_ws: Workspace):
+ _tree(tmp_ws)
+ before = tmp_ws.head()
+ (tmp_ws.root / ASSET).write_text("// concurrent\n")
+ shared = GenerationTask(label="env", prompt="p", files_hint=[ENV], shared_tree=True)
+ plain = shared.model_copy(update={"shared_tree": False})
+ assert _attributed_fallback(tmp_ws, shared, before) == []
+ assert [f.path for f in _attributed_fallback(tmp_ws, plain, before)] == [ASSET]
+
+
+def test_a_shared_tree_session_watches_only_its_own_files(tmp_ws: Workspace):
+ _tree(tmp_ws)
+ s = begin_session(_job(tmp_ws, shared_tree=True), "agy")
+ try:
+ assert activity_paths(s) == [tmp_ws.root / ENV]
+ finally:
+ finish_session(s, ok=False, exit_reason="error", text="", usage=Usage())
+ s = begin_session(_job(tmp_ws), "agy")
+ try:
+ assert activity_paths(s) == [tmp_ws.src, tmp_ws.public]
+ finally:
+ finish_session(s, ok=False, exit_reason="error", text="", usage=Usage())
+
+
+def test_writes_to_other_files_do_not_keep_a_watched_file_session_alive(tmp_path: Path):
+ """The watchdog with a FILE as its activity path: a sibling's writes beside it are not activity."""
+ src = tmp_path / "src"
+ src.mkdir()
+ own = src / "env.js"
+ own.write_text("x")
+ code = ("import time\n"
+ f"p = {str(src / 'asset.js')!r}\n"
+ "for i in range(40):\n open(p, 'a').write('x'); time.sleep(0.25)\n")
+ res = run_with_watchdog([sys.executable, "-c", code], cwd=tmp_path, env=None, soft_timeout_s=0.5, idle_grace_s=1.0,
+ hard_timeout_s=30, poll_s=0.1, scan_s=0.2, activity_dirs=[own])
+ assert res.killed_reason == "idle" and res.duration_s < 8, (res.killed_reason, res.duration_s)
+
+
+def test_shared_tree_needs_a_hint_and_excludes_edit_only(tmp_ws: Workspace):
+ with pytest.raises(ValidationError):
+ AgentJob(workspace=str(tmp_ws.root), prompt="p", shared_tree=True)
+ with pytest.raises(ValidationError):
+ _job(tmp_ws, shared_tree=True, edit_only=True)
diff --git a/harness/tests/orchestrator_tracks/test_env_stage_honest.py b/harness/tests/orchestrator_tracks/test_env_stage_honest.py
new file mode 100644
index 00000000..170d9192
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_env_stage_honest.py
@@ -0,0 +1,103 @@
+"""D111: the scene env stage is ``ok`` only when the env module itself was written, else it is recovered.
+
+Argon loop iteration 4 (scene_threejs, 2026-10-15): in 12 of 15 runs the env session wrote nothing,
+was credited with the asset files written beside it and its stage read ``ok``; round 0 was unlit and
+the single refine round wrote the whole environment from the skeleton. The stage now applies the
+zone stage's own test (the file in ``files_changed`` or rewritten since the stage began) and runs
+ONE single-shot recovery before the zones — for either scene language's env file.
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from typing import Any
+
+import pytest
+
+from codeverse3d.contracts.agent import FileChange
+from codeverse3d.contracts.common import Language, Track
+from codeverse3d.contracts.plan import ScenePlan
+from codeverse3d.orchestrator import RunState
+from codeverse3d.proc import EventLog
+from codeverse3d.tracks import scene as scene_mod
+from codeverse3d.tracks.generation import SINGLE_SHOT_PREFIX, GenerationResult
+from codeverse3d.tracks.planner import plan_example
+from codeverse3d.tracks.scene import SceneTrack, env_file
+from codeverse3d.workspace import Workspace
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import FakeRuntime, FakeServices
+
+LANGUAGES = [Language.SCENE_THREEJS, Language.SCENE_BLENDER]
+
+
+def _ctx(tmp_path, settings, language: Language):
+ ws = Workspace(tmp_path / "runs" / "s").create()
+ track = SceneTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(language))
+ ctx = track.build_context(make_spec(Track.SCENE, language, max_minutes=90.0), ws, EventLog(ws.events_path), RunState())
+ ctx.plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ rel = env_file(ctx)
+ (ws.root / rel).parent.mkdir(parents=True, exist_ok=True)
+ (ws.root / rel).write_text("# PLACEHOLDER env\n")
+ (ws.src / "assets").mkdir(parents=True, exist_ok=True)
+ (ws.src / "assets" / "lantern.js").write_text("// stub\n")
+ ws.commit("skeleton")
+ # the fake services expose no chat model; a real run's planner is an API model
+ ctx.extra["_single_shot_ctx"] = replace(ctx, agent_id=SINGLE_SHOT_PREFIX + "fake:planner", model=object(), agent=None)
+ return track, ctx
+
+
+def _events(ctx) -> list[str]:
+ return [e["event"] for e in ctx.events.read()]
+
+
[email protected]("language", LANGUAGES)
+def test_a_session_credited_only_with_other_stages_files_fails_and_is_recovered(tmp_path, settings, monkeypatch, language):
+ track, ctx = _ctx(tmp_path, settings, language)
+ rel = env_file(ctx)
+ calls: list[tuple[str, bool, bool]] = []
+
+ def fake_generate_for(gen: Any, task: Any) -> GenerationResult:
+ calls.append((task.label, bool(gen.single_shot), task.shared_tree))
+ if task.label.endswith(".recover"):
+ (ctx.ws.root / rel).write_text("# the env, at last\n")
+ return GenerationResult(ok=True, files_changed=[FileChange(path=rel, status="modified")], label=task.label)
+ # the iteration-4 session: read, wrote nothing, and the asset single-shot's file came back as its own
+ (ctx.ws.src / "assets" / "lantern.js").write_text("// written by the asset stage meanwhile\n")
+ return GenerationResult(ok=True, files_changed=[FileChange(path="src/assets/lantern.js", status="modified")],
+ label=task.label, notes="exit=timeout")
+
+ monkeypatch.setattr(scene_mod, "generate_for", fake_generate_for)
+ out = track._env_stage(ctx)
+ assert out["ok"] and out["files"] == [rel], out
+ assert [c[0] for c in calls] == ["env", "env.recover"], calls
+ assert calls[0][2] is True, "the env session shares its tree with the asset single-shots"
+ assert calls[1][1] is True, "the recovery is single-shot: it cannot spend its window reading"
+ assert {"env.recover", "env.recovered"} <= set(_events(ctx))
+
+
[email protected]("language", LANGUAGES)
+def test_a_recovery_that_also_writes_nothing_leaves_the_stage_failed(tmp_path, settings, monkeypatch, language):
+ track, ctx = _ctx(tmp_path, settings, language)
+
+ def fake_generate_for(gen: Any, task: Any) -> GenerationResult:
+ return GenerationResult(ok=False, label=task.label, notes="exit=timeout")
+
+ monkeypatch.setattr(scene_mod, "generate_for", fake_generate_for)
+ out = track._env_stage(ctx)
+ assert out["ok"] is False and out["files"] == [] and "recover" in out["notes"], out
+
+
+def test_a_session_that_wrote_the_env_triggers_no_recovery(tmp_path, settings, monkeypatch):
+ track, ctx = _ctx(tmp_path, settings, Language.SCENE_THREEJS)
+ rel = env_file(ctx)
+ labels: list[str] = []
+
+ def fake_generate_for(gen: Any, task: Any) -> GenerationResult:
+ labels.append(task.label)
+ (ctx.ws.root / rel).write_text("// lights, fog, sky\n")
+ return GenerationResult(ok=True, files_changed=[FileChange(path=rel, status="modified")], label=task.label)
+
+ monkeypatch.setattr(scene_mod, "generate_for", fake_generate_for)
+ out = track._env_stage(ctx)
+ assert out == {"ok": True, "files": [rel], "notes": ""} and labels == ["env"], (out, labels)
+ assert "env.recover" not in _events(ctx)
diff --git a/harness/tests/orchestrator_tracks/test_orchestrator.py b/harness/tests/orchestrator_tracks/test_orchestrator.py
index 48c72363..ca7de11e 100644
--- a/harness/tests/orchestrator_tracks/test_orchestrator.py
+++ b/harness/tests/orchestrator_tracks/test_orchestrator.py
@@ -125,3 +125,17 @@ def test_build_refine_instructions_merges_groups_and_the_cap_protects_gate_tasks
ImprovementItem(target=f"J{i}", kind="geometry", instruction="x", priority=1) for i in range(5)])
tasks = build_refine_instructions(judgment, gates, [], chair_plan, max_tasks=6)
assert len(tasks) == 8 and all(t.source == "gate" for t in tasks)
+
+
+def test_two_env_errors_of_one_gate_are_two_refine_tasks(chair_plan):
+ """D111: the dedup key carries the finding's kind — ``no_fog`` no longer hides ``no_background``
+ (argon loop iteration 4: both ERRORs on target ``env`` of ``scene_placement``, one task in the prompt)."""
+ env = [GateFinding(gate="scene_placement", severity=Severity.ERROR, target="env", message="scene.fog is not set",
+ data={"kind": "no_fog"}),
+ GateFinding(gate="scene_placement", severity=Severity.ERROR, target="env", message="scene.background is not set",
+ data={"kind": "no_background"}),
+ GateFinding(gate="scene_placement", severity=Severity.ERROR, target="env", message="scene.fog is not set (again)",
+ data={"kind": "no_fog"})]
+ tasks = build_refine_instructions(None, [GateReport(gate="scene_placement", passed=False, findings=env)], [], chair_plan)
+ lines = [t.instruction for t in tasks]
+ assert len(tasks) == 2 and any("fog" in x for x in lines) and any("background" in x for x in lines), lines
diff --git a/harness/tests/scene_blender/test_build.py b/harness/tests/scene_blender/test_build.py
index 02a23f40..69a98a6b 100644
--- a/harness/tests/scene_blender/test_build.py
+++ b/harness/tests/scene_blender/test_build.py
@@ -76,6 +76,15 @@ def test_placement_rows_for_sunk_floating_and_free(built) -> None:
assert [r["name"] for r in rows.values() if r["name"].startswith("GrassPatch")] == ["GrassPatch"]
+def test_the_zone_mark_survives_the_census_glb(built) -> None:
+ """D111: the census GLB's zone nodes carry ``extras[ZONE_ROOT_KEY]`` → three.js ``userData``, so only
+ the zones' children are rows; the env's roots (``Ground``) are scenery, measured as nothing."""
+ _, res = built
+ table = res.census["placement"]
+ assert table["assets"] and {r["zone"] for r in table["assets"]} <= {"Yard", "Meadow"}
+ assert "Ground" in table["scenery"]["names"]
+
+
def test_bpy_facts_reach_the_census(built) -> None:
ws, res = built
c = res.census
diff --git a/harness/tests/scene_gates/test_placement.py b/harness/tests/scene_gates/test_placement.py
index fc5be437..b5b0acab 100644
--- a/harness/tests/scene_gates/test_placement.py
+++ b/harness/tests/scene_gates/test_placement.py
@@ -499,3 +499,37 @@ def test_the_summary_records_the_thresholds_and_the_probe_s():
assert s.data["thresholds"]["sunk_error_frac"] == 0.2 and s.data["probe_thresholds"]["overlap_min"] == 0.1
assert s.data["free"] == 1 and s.data["free_share"] == 0.5 and s.data["counts"]["cantilevered"] == 0
assert "1 tagged free (50%)" in s.message and "indoor tolerance 2 cm" in s.message
+
+
+def test_a_zone_past_a_truncated_tables_cut_is_unmeasured_not_empty():
+ """D111: argon loop iteration 4, r1_01 — an envelope of 337 meshes filled the 400-row table and the
+ last zone in the scene, built and visibly present, read "placed nothing". A table cut by its ROW CAP
+ with the zone's built group in the census gives an INFO note and no ``zone_empty`` ERROR; the zone AT
+ the cut (the last row's) gets an INFO for what may lie past it, not ``missing_content``."""
+ table = _table(_row("Lantern"), _row("Bench"), total=9, truncated=True)
+ census = {"groups": [{"name": "Yard", "kind": "content"}, {"name": "House", "kind": "content"}], "placement": table}
+ kinds = {(f.data.get("kind"), f.target, f.severity) for f in placement_gate_safe(census, plan=_contract_plan()).findings}
+ assert ("zone_unmeasured", "House", Severity.INFO) in kinds
+ assert not {k for k, t, _ in kinds if t == "House" and k in ("zone_empty", "missing_content")}, kinds
+ # not truncated; cut by the TIME budget (a row per asset, so no row = nothing placed); the group absent
+ # from the census; or present but EMPTY: still an ERROR
+ for c in ({**census, "placement": _table(_row("Lantern"), _row("Bench"))},
+ {**census, "placement": {**table, "total": 2}},
+ {**census, "groups": [{"name": "Yard", "kind": "content"}]},
+ {**census, "groups": [{"name": "Yard", "kind": "content"}, {"name": "House", "kind": "empty"}]}):
+ kinds = {(f.data.get("kind"), f.target) for f in placement_gate_safe(c, plan=_contract_plan()).findings}
+ assert ("zone_empty", "House") in kinds, (c, kinds)
+
+
+def test_the_zone_at_a_truncated_tables_cut_is_partly_measured():
+ table = _table(_row("Lantern"), total=9, truncated=True) # Yard's Bench lies past the cut
+ census = {"groups": [{"name": "Yard", "kind": "content"}, {"name": "House", "kind": "content"}], "placement": table}
+ found = {(f.data.get("kind"), f.target): f for f in placement_gate_safe(census, plan=_contract_plan()).findings}
+ assert ("missing_content", "Yard") not in found
+ assert found[("zone_unmeasured", "Yard")].severity == Severity.INFO and found[("zone_unmeasured", "Yard")].data["missing"] == ["Bench"]
+ # uncut, the same rows are a real missing_content ERROR
+ census["placement"] = _table(_row("Lantern"))
+ found = {(f.data.get("kind"), f.target): f for f in placement_gate_safe(census, plan=_contract_plan()).findings}
+ assert found[("missing_content", "Yard")].severity == Severity.ERROR
+ # D111 measures the zone group's children only: the hint says so (a stray scene.add is not the zone's)
+ assert "direct child of the group the zone's build returns" in found[("missing_content", "Yard")].fix_hint
diff --git a/harness/tests/scene_runtime/test_placement_census.py b/harness/tests/scene_runtime/test_placement_census.py
index 791bc4a4..5d827564 100644
--- a/harness/tests/scene_runtime/test_placement_census.py
+++ b/harness/tests/scene_runtime/test_placement_census.py
@@ -42,11 +42,6 @@ zone.add(box('Bench', 1.6, 0.9, 0.5, 16, 0, 15));
zone.add(box('Boat', 2, 0.6, 0.8, -20, 0.0, -20));
const rock = new THREE.Mesh(new THREE.DodecahedronGeometry(0.6, 1), mat); rock.name = 'Rock'; rock.position.set(8, 0.2, -8); zone.add(rock);
const inst = new THREE.InstancedMesh(new THREE.BoxGeometry(0.2, 0.2, 0.2), mat, 50); inst.name = 'Pebbles'; zone.add(inst);
-// the env's room shell: a lid and a lintel whose box runs INTO the lid (a 3.2 m door head in a 3 m room) —
-// one enclosure, never placed assets (2026-10-15: half the Blender interpenetration ERRORs of loop iteration 0)
-const shell = new THREE.Group(); shell.name = 'RoomShell'; scene.add(shell);
-shell.add(box('Ceiling', 8.4, 0.2, 6.4, -30, 3.0, 30));
-shell.add(box('RoomShellWallBack_0Lintel', 1.2, 0.5, 0.2, -30, 2.8, 33.1));
scene.updateMatrixWorld(true);
const c = sceneCensus(scene, THREE, { placement: true });
console.log(JSON.stringify({ ground_y: c.ground_y, placement: c.placement, plain_has_placement: 'placement' in sceneCensus(scene, THREE) }));
@@ -67,8 +62,10 @@ def _row(table, name):
def test_counts_exemptions_and_budget(table):
- assert table["total"] == 19 and table["checked"] == 12 and table["truncated"] is False
- assert table["exempt"] == {"backdrop": 3, "enclosure": 2, "free": 1, "instanced": 1}
+ # an unmarked scene (no ZONE_ROOT_KEY, D111): every top-level child is a zone root, as before;
+ # the room shell's own case lives in test_zone_roots.py (a marked scene: scenery, no rows)
+ assert table["total"] == 17 and table["checked"] == 12 and table["truncated"] is False
+ assert table["exempt"] == {"backdrop": 3, "free": 1, "instanced": 1} and table["scenery"] == {"n": 0, "names": []}
assert {a["name"] for a in table["assets"] if a["exempt"] == "backdrop"} == {"Ground", "SkyDome", "PondWater"}
assert _row(table, "Bird")["exempt"] == "free" and _row(table, "Pebbles")["exempt"] == "instanced"
assert table["duration_ms"] < 2000 and table["notes"] == []
@@ -96,16 +93,6 @@ def test_supported_floating_and_sunk_boxes(table):
assert anvil["supported"] and not anvil["floating"]
-def test_the_room_shells_members_are_the_enclosure_not_placed_assets(table):
- """Walls, lid, sills and lintels under a `RoomShell…` root abut and overlap each other by
- construction (a lintel runs into the lid here): they are exempt as the enclosure, so they get
- no seating row and no interpenetration pair (24 of 41 Blender ERRORs in loop iteration 0)."""
- for name in ("Ceiling", "RoomShellWallBack_0Lintel"):
- row = _row(table, name)
- assert row["zone"] == "RoomShell" and row["exempt"] == "enclosure"
- assert not [p for p in table["interpenetrations"] if "RoomShell" in (p["zone_a"], p["zone_b"])]
-
-
def test_interpenetration_is_a_pair_not_a_burial(table):
pairs = table["interpenetrations"]
assert [(p["a"], p["b"], p["aabb_overlap"]) for p in pairs] == [("CrateA", "CrateB", 0.5)]
diff --git a/harness/tests/scene_runtime/test_probe_timeout.py b/harness/tests/scene_runtime/test_probe_timeout.py
new file mode 100644
index 00000000..5bc6ab92
--- /dev/null
+++ b/harness/tests/scene_runtime/test_probe_timeout.py
@@ -0,0 +1,169 @@
+"""D111: a scene probe that runs out of its budget is a verdict on the code, not a harness failure.
+
+Argon loop iteration 4, r1_08 (2026-10-15): the refine's new 37 k-vertex terrain met the zones'
+per-vertex raycast seating and the scene stopped booting inside the 120 s probe budget. The probe
+called it "a harness/driver failure, not your code", the agent stopped working, and the round spent
+3 x 240 s rebuilding identical code and was never scored. After the driver's one retry (on a browser
+of its own) a timeout INSIDE the scene's own code — the watchdog's ``phase`` — is now a typed ERROR
+against the entry file, so the round's repair session receives it; a timeout anywhere else (browser
+launch, page ready, the shader preflight, node itself starved) and any census-GLB boot stay the box's.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+import codeverse3d.spatial.probes as probes_mod
+import codeverse3d.spatial.render_scene as RS
+from codeverse3d.contracts.artifacts import GateReport
+from codeverse3d.languages.scene_threejs import SceneThreeJsRuntime
+from codeverse3d.spatial.node import OWN_BROWSER_ENV, NodeError, NodeResult
+from codeverse3d.spatial.render_scene import SCENE_PHASES, SceneRenderError, run_scene_script
+from codeverse3d.tracks import repair as R
+from codeverse3d.tracks.generation import GenerationResult
+from tests.scene_runtime.conftest import needs_browser
+
+TIMEOUT = {"ok": False, "error": "timeout after 120000 ms", "timed_out": True, "phase": "scene"}
+
+
+def _feed(monkeypatch, results: list[NodeResult]) -> list[dict[str, str]]:
+ seen: list[dict[str, str]] = []
+
+ def fake(path, args, *, cwd, timeout_s, env_extra, check):
+ seen.append(dict(env_extra))
+ return results[len(seen) - 1]
+
+ monkeypatch.setattr(RS, "run_node", fake)
+ return seen
+
+
+def _timed_out(phase: str) -> SceneRenderError:
+ return SceneRenderError("probe_scene.mjs failed (exit 3): timeout after 120000 ms", timed_out=True, phase=phase)
+
+
+def test_a_driver_timeout_is_retried_once_on_its_own_browser_then_raised_typed(monkeypatch):
+ seen = _feed(monkeypatch, [NodeResult(rc=3, stdout="", stderr="", last_json=TIMEOUT, duration_ms=1)] * 2)
+ with pytest.raises(SceneRenderError) as ei:
+ run_scene_script("probe_scene.mjs", ["--ws", "x"], timeout_s=10)
+ assert ei.value.timed_out is True and ei.value.phase == "scene" and ei.value.scene_timed_out
+ assert len(seen) == 2, "one harness retry, then the verdict"
+ # a wedged SHARED browser times out the same way: the retry must not reuse it
+ assert not set(OWN_BROWSER_ENV.items()) <= set(seen[0].items()) and set(OWN_BROWSER_ENV.items()) <= set(seen[1].items())
+
+
[email protected]("phase", ["host", "compile", "report", "close", ""])
+def test_a_timeout_outside_the_scenes_code_is_not_the_scenes(monkeypatch, phase):
+ _feed(monkeypatch, [NodeResult(rc=3, stdout="", stderr="", last_json={**TIMEOUT, "phase": phase}, duration_ms=1)] * 2)
+ with pytest.raises(SceneRenderError) as ei:
+ run_scene_script("probe_scene.mjs", ["--ws", "x"], timeout_s=10)
+ assert ei.value.timed_out and not ei.value.scene_timed_out and phase not in SCENE_PHASES
+
+
+def test_the_process_clock_is_the_box(monkeypatch):
+ """Node's own watchdog runs 20 s inside the process clock; when the process clock fires, node itself
+ was starved — no phase, never the code's."""
+ def starved(path, args, *, cwd, timeout_s, env_extra, check):
+ raise NodeError("timed out", result=NodeResult(rc=-9, stdout="", stderr="", last_json=None, duration_ms=1,
+ timed_out=True))
+
+ monkeypatch.setattr(RS, "run_node", starved)
+ with pytest.raises(SceneRenderError) as ei:
+ run_scene_script("probe_scene.mjs", ["--ws", "x"], timeout_s=10)
+ assert ei.value.timed_out and ei.value.phase == "" and not ei.value.scene_timed_out
+
+
+def test_a_driver_that_fails_otherwise_is_not_timed_out(monkeypatch):
+ _feed(monkeypatch, [NodeResult(rc=2, stdout="", stderr="", last_json={"ok": False, "error": "--ws is required"},
+ duration_ms=1)])
+ with pytest.raises(SceneRenderError) as ei:
+ run_scene_script("probe_scene.mjs", [], timeout_s=10)
+ assert ei.value.timed_out is False
+
+
+@needs_browser
+def test_the_driver_watchdog_names_the_phase_it_fired_in(starter_ws):
+ """A real ``probe_scene.mjs`` boot whose createScene() blocks the page: the watchdog fires inside
+ the scene's code and says so. (The block is bounded, so the page frees itself after the test.)"""
+ from codeverse3d.spatial.node import run_node
+
+ (starter_ws.src / "scene.js").write_text(
+ "import * as THREE from 'three';\n"
+ "export function createScene() { const end = Date.now() + 25000; while (Date.now() < end) {}\n"
+ " return { scene: new THREE.Scene(), cameras: [], update() {} }; }\n")
+ r = run_node(RS.runtime_js_dir() / "probe_scene.mjs", ["--ws", str(starter_ws.root), "--timeout-ms", "12000"],
+ cwd=RS.runtime_js_dir(), timeout_s=60, env_extra=dict(OWN_BROWSER_ENV), check=False)
+ assert r.rc == 3 and r.summary.get("timed_out") is True and r.summary.get("phase") == "scene", r.summary
+
+
[email protected]("phase", sorted(SCENE_PHASES))
+def test_a_timed_out_probe_is_an_error_against_the_code(tmp_ws, monkeypatch, phase):
+ monkeypatch.setattr(probes_mod, "run_scene_script", lambda script, args, **kw: (_ for _ in ()).throw(_timed_out(phase)))
+ probe, _, census = probes_mod.run_probe(tmp_ws, timeout_s=120)
+ (f,) = probe.findings
+ assert f.severity.value == "error" and f.data["kind"] == "probe_timeout" and f.data["timed_out"] is True
+ assert f.data["phase"] == phase
+ assert not f.data.get("harness_failure") and "not your code" not in f.fix_hint
+ assert "120 s probe budget" in f.message and f.target == "src/scene.js" and census == {}
+ # the build tool shows it as a finding, not as "the tool could not run"
+ res = probes_mod.probe_result(probe, census)
+ assert res.ok and res.errors == [] and any("probe budget" in line for line in res.findings)
+
+
[email protected]("err", [SceneRenderError("chrome went away"), _timed_out("host"), _timed_out("compile"),
+ SceneRenderError("probe_scene.mjs timed out after 140s", timed_out=True)],
+ ids=["crash", "host", "compile", "process-clock"])
+def test_a_probe_that_could_not_run_is_still_the_harnesss(tmp_ws, monkeypatch, err):
+ monkeypatch.setattr(probes_mod, "run_scene_script", lambda script, args, **kw: (_ for _ in ()).throw(err))
+ probe, _, _ = probes_mod.run_probe(tmp_ws, timeout_s=120)
+ assert probe.findings[0].data.get("harness_failure") is True
+
+
+def test_a_census_glb_that_never_boots_stays_the_harnesss(tmp_ws, monkeypatch):
+ """scene_blender: the author's bpy already ran in Blender; the GLB the probe loads is the harness's
+ export, and a three.js hint ("createScene, update") names nothing a bpy author has."""
+ monkeypatch.setattr(probes_mod, "run_scene_script", lambda script, args, **kw: (_ for _ in ()).throw(_timed_out("scene")))
+ probe, _, _ = probes_mod.run_probe(tmp_ws, timeout_s=120, glb=tmp_ws.artifacts / "census.glb")
+ assert probe.findings[0].data.get("harness_failure") is True and probe.findings[0].data.get("kind") != "probe_timeout"
+
+
+def test_the_probe_tool_and_the_build_share_one_budget(tmp_ws, monkeypatch):
+ """The ``scene_probe`` tool probed at 60 s while the build allowed 120 s: with a timeout now the code's,
+ the agent's own tool would condemn a scene the build accepts."""
+ from codeverse3d.languages.scene_threejs import write_example
+
+ write_example(tmp_ws)
+ budgets: list[str] = []
+
+ def capture(script, args, **kw):
+ budgets.append(args[args.index("--timeout-ms") + 1])
+ raise SceneRenderError("stop here")
+
+ monkeypatch.setattr(probes_mod, "run_scene_script", capture)
+ rt = SceneThreeJsRuntime()
+ rt.probe(tmp_ws)
+ rt.build(tmp_ws)
+ assert len(budgets) == 2 and budgets[0] == budgets[1], budgets
+
+
+def test_the_scene_build_hands_a_timeout_to_repair_not_to_rebuilds(tmp_ws, monkeypatch):
+ """The scene_threejs build's BuildResult is not a harness failure, so ``build_with_repair`` runs a
+ repair session on the first pass instead of MAX_HARNESS_REBUILDS identical rebuilds."""
+ from codeverse3d.languages.scene_threejs import write_example
+
+ write_example(tmp_ws)
+
+ monkeypatch.setattr(probes_mod, "run_scene_script", lambda script, args, **kw: (_ for _ in ()).throw(_timed_out("scene")))
+ build = SceneThreeJsRuntime().build(tmp_ws)
+ assert not build.ok and build.harness_failure is False and build.error_type == "probe_timeout"
+
+ events: list[str] = []
+ ctx = SimpleNamespace(spec=SimpleNamespace(budget=SimpleNamespace(max_repair_attempts=1)),
+ events=SimpleNamespace(emit=lambda name, **k: events.append(name)))
+ monkeypatch.setattr(R, "build_once", lambda c: (build, GateReport(gate="lint", passed=True, findings=[])))
+ monkeypatch.setattr(R, "make_repair_task", lambda *a, **k: SimpleNamespace(label="repair"))
+ monkeypatch.setattr(R, "generate_for", lambda c, t: GenerationResult(ok=True, label="repair"))
+ out = R.build_with_repair(ctx, round_index=1, label="r01")
+ assert "build.harness_retry" not in events and "repair.attempt" in events and len(out.attempts) == 1, events
diff --git a/harness/tests/scene_runtime/test_zone_roots.py b/harness/tests/scene_runtime/test_zone_roots.py
new file mode 100644
index 00000000..e7924204
--- /dev/null
+++ b/harness/tests/scene_runtime/test_zone_roots.py
@@ -0,0 +1,162 @@
+"""D111: placed-asset rows come from the plan's ZONE roots only — the roots the harness marks itself.
+
+Argon loop iteration 4 (scene_threejs, 2026-10-15): every top-level scene child was a "zone", so an env
+wall merged per material (body + piers in one mesh, the flashing strip in another) became rows that
+overlap by construction, a two-mesh bollard was a cap "interpenetrating" its post, and in two runs
+(r1_02, r1_10) every final placement ERROR sat on such scenery. The assembler now marks each zone root with
+``userData[ZONE_ROOT_KEY]`` (the census GLB's zone-node extras for scene_blender); every other root is
+scenery: no rows, never paired with other scenery, not in the free share — still a support, something
+to sink into, something a zone asset is mounted on (``attached``, and the boot settle leaves it) and
+something a zone asset can clip (a zone-vs-scenery interpenetration names the zone asset).
+"""
+
+from __future__ import annotations
+
+import re
+
+import pytest
+
+from codeverse3d.config import get_settings
+from codeverse3d.conventions import ZONE_ROOT_KEY
+from codeverse3d.languages.scene_threejs import render_scene_js
+from codeverse3d.spatial.node import runtime_js_dir
+from codeverse3d.spatial.scene_placement import placement_findings
+from tests.scene_runtime.conftest import needs_node, run_node_json
+
+SCENE_JS = """
+import * as THREE from 'three';
+import fs from 'node:fs';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+import { sceneCensus } from './lib/host_census.mjs';
+import { settleScene } from './lib/host_placement.mjs';
+const brick = new THREE.MeshStandardMaterial({ name: 'Brick' }), metal = new THREE.MeshStandardMaterial({ name: 'Metal' });
+const geo = (sx, sy, sz, x, y, z) => new THREE.BoxGeometry(sx, sy, sz).translate(x, y + sy / 2, z);
+const box = (name, sx, sy, sz, x, y, z, m = brick) => { const o = new THREE.Mesh(geo(sx, sy, sz, 0, 0, 0), m); o.name = name; o.position.set(x, y, z); return o; };
+function build(mark, withScenery) {
+ const scene = new THREE.Scene();
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(200, 200, 8, 8), brick); ground.name = 'Ground'; ground.rotation.x = -Math.PI / 2;
+ scene.add(ground);
+ const yard = new THREE.Group(); yard.name = 'Yard';
+ if (mark) yard.userData[mark] = 'Yard';
+ yard.add(box('Crate', 1, 1, 1, 0, 0, 0));
+ yard.add(box('Anvil', 1, 1, 1, -5, -0.5, 0)); // sunken 0.5 m into Ground: a real finding
+ yard.add(box('CrateA', 1, 1, 1, 10, 0, 0)); yard.add(box('CrateB', 1, 1, 1, 10.5, 0, 0)); // a real pair
+ // the assembler's probe nests the marked root in a wrapper: still found
+ const wrap = new THREE.Group(); wrap.name = '__zone__yard'; wrap.add(yard); scene.add(wrap);
+ if (withScenery) {
+ // an env parapet built and MERGED BY MATERIAL: wall body + piers in one brick mesh, the flashing
+ // strip in a metal one, flush on the wall and pierced by the piers (iteration 4, r1_02)
+ const parapet = new THREE.Group(); parapet.name = 'ParapetWall_North';
+ const body = [geo(25, 1.1, 0.5, 0, 0, -30)];
+ for (let i = -3; i <= 3; i++) body.push(geo(0.6, 1.3, 0.6, i * 4, 0, -30));
+ parapet.add(new THREE.Mesh(mergeGeometries(body), brick));
+ parapet.add(new THREE.Mesh(geo(25, 0.14, 0.5, 0, 1.0, -30), metal));
+ scene.add(parapet);
+ // harbour bollards: a cap and a post as two unnamed sibling meshes (iteration 4, r1_10)
+ const harbor = new THREE.Group(); harbor.name = 'HarborSurroundings';
+ for (const z of [-16, -6, 4]) {
+ harbor.add(box('', 0.4, 0.72, 0.4, 20, 0, z, metal));
+ harbor.add(box('', 0.36, 0.3, 0.36, 20, 0.6, z, metal)); // its foot inside the post's top
+ }
+ scene.add(harbor);
+ // a room shell (the RoomShell name exemption this replaces): a lintel running into the lid
+ const shell = new THREE.Group(); shell.name = 'RoomShell';
+ shell.add(box('Ceiling', 8.4, 0.2, 6.4, -30, 3.0, 30)); shell.add(box('RoomShellWallBack_0Lintel', 1.2, 0.5, 0.2, -30, 2.8, 33.1));
+ scene.add(shell);
+ // a free-tagged scenery root never enters the free share
+ const birds = box('Gull', 0.3, 0.2, 0.3, 0, 8, 0); birds.userData.placement = 'free'; scene.add(birds);
+ }
+ scene.updateMatrixWorld(true);
+ return sceneCensus(scene, THREE, { placement: true }).placement;
+}
+// a marked street zone whose things hang on, and push into, an env facade (the scenery)
+function street(mark) {
+ const scene = new THREE.Scene();
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(200, 200, 8, 8), brick); ground.name = 'Ground'; ground.rotation.x = -Math.PI / 2;
+ scene.add(ground);
+ const facades = new THREE.Group(); facades.name = 'StreetFacades';
+ facades.add(box('FacadeWall', 20, 6, 0.5, 0, 0, -5)); // z in [-5.25, -4.75]
+ scene.add(facades);
+ const zone = new THREE.Group(); zone.name = 'Street'; if (mark) zone.userData[mark] = 'Street';
+ for (const x of [-6, -2, 2, 6]) zone.add(box('WallSconce', 0.2, 0.3, 0.2, x, 2.2, -4.65)); // flush on the facade
+ zone.add(box('ShopSign', 2, 0.6, 0.1, 0, 3.0, -4.7)); // flush on the facade, 3 m up
+ zone.add(box('Kiosk', 1, 2, 1, 8, 0, -4.6)); // pushed 0.35 m into the facade
+ scene.add(zone);
+ scene.updateMatrixWorld(true);
+ return scene;
+}
+const KEY = process.argv[2];
+const words = JSON.parse(fs.readFileSync('./lib/placement_words.json', 'utf8'));
+const settled = street(KEY);
+const settle = settleScene(settled, THREE, { groundY: 0, words });
+console.log(JSON.stringify({ zoneOnly: build(KEY, false), marked: build(KEY, true), unmarked: build('', true),
+ street: sceneCensus(street(KEY), THREE, { placement: true }).placement, settle }));
+"""
+
+
[email protected](scope="module")
+def tables() -> dict:
+ return run_node_json(SCENE_JS.replace("process.argv[2]", repr(ZONE_ROOT_KEY)))
+
+
+def _findings(table: dict) -> list[tuple[str, str, str]]:
+ report = placement_findings(table, thresholds=get_settings().placement)
+ return sorted((f.severity.value, f.data.get("kind", ""), f.target or "") for f in report.findings
+ if f.data.get("kind") != "summary")
+
+
+def test_the_key_is_one_word_on_both_sides():
+ src = (runtime_js_dir() / "lib" / "host_placement.mjs").read_text()
+ m = re.search(r"export const ZONE_ROOT_KEY = '([^']+)';", src)
+ assert m and m.group(1) == ZONE_ROOT_KEY
+
+
+def test_the_assembled_scene_marks_every_zone_root():
+ text = render_scene_js(["yard", "quay"], [], [])
+ assert f"g.userData['{ZONE_ROOT_KEY}'] = name;" in text
+
+
+@needs_node
+def test_env_scenery_yields_no_rows_while_the_zone_findings_are_unchanged(tables):
+ marked, zone_only = tables["marked"], tables["zoneOnly"]
+ assert {r["zone"] for r in marked["assets"]} == {"Yard"}
+ assert marked["scenery"]["n"] == 5 and {"ParapetWall_North", "HarborSurroundings", "RoomShell", "Ground"} <= set(marked["scenery"]["names"])
+ assert not marked["exempt"].get("free"), "a free-tagged scenery root is not in the free share"
+ # the room shell (walls, lid, lintels abutting by construction): no row, no pair — the 2026-10-15
+ # `RoomShell…` name exemption this replaces (24 of 41 Blender ERRORs in loop iteration 0)
+ assert not [r for r in marked["assets"] if r["name"] in ("Ceiling", "RoomShellWallBack_0Lintel")]
+ found = _findings(marked)
+ assert found == _findings(zone_only), "scenery changes nothing about the zone's own findings"
+ kinds = {(k, t) for _, k, t in found}
+ assert ("sunken", "Yard/Anvil") in kinds and any(k == "interpenetration" for k, _ in kinds), found
+ assert all(t.startswith("Yard/") or t == "scene" for _, _, t in found), found
+
+
+@needs_node
+def test_a_zone_asset_mounted_on_scenery_is_attached_and_one_pushed_into_it_clips(tables):
+ """A sconce flush on an env facade is mounted on it — the gate leaves it, and so does the boot
+ settle (it used to drop a sign hung on scenery to the ground: the "touching a neighbour" test
+ looked at zone assets only) — while a kiosk pushed into the facade is still an interpenetration,
+ reported on the zone asset whichever box is smaller."""
+ t = tables["street"]
+ rows = {r["name"]: r for r in t["assets"]}
+ assert rows["WallSconce"]["attached"] == ["FacadeWall"] and rows["ShopSign"]["attached"] == ["FacadeWall"]
+ assert tables["settle"]["count"] == 0, tables["settle"]
+ found = _findings(t)
+ assert not [f for f in found if f[1] in ("floating", "unsupported")], found
+ assert [t for _, k, t in found if k == "interpenetration"] == ["Street/Kiosk"], found
+ (pair,) = t["interpenetrations"]
+ assert (pair["a"], pair["zone_a"], pair["b"], pair["zone_b"]) == ("Kiosk", "Street", "FacadeWall", "StreetFacades")
+
+
+@needs_node
+def test_without_the_mark_the_scenery_is_measured_as_before(tables):
+ """The control: the same scene unmarked (a scene the harness did not assemble) still measures
+ every top-level child — which is exactly the artefact the mark removes."""
+ pairs = tables["unmarked"]["interpenetrations"]
+ zones = {p["zone_a"] for p in pairs} | {p["zone_b"] for p in pairs}
+ assert {"ParapetWall_North", "HarborSurroundings"} <= zones, pairs
+ assert tables["unmarked"]["scenery"]["n"] == 0