Skip to content

Official Codebase of 3DCodeVerse

Python

D112: agy steps count as activity; env recovery checked; is_interior obeys the flag; the clock leaves room to judge

gaoypengc54163357f5d
diff --git a/eval/bench/_bare_agent.py b/eval/bench/_bare_agent.py
index 243c94d8..94788c9f 100644
--- a/eval/bench/_bare_agent.py
+++ b/eval/bench/_bare_agent.py
@@ -90,7 +90,9 @@ def run_bare_agent(spec: Spec, target: str, cell: Path, eval_ws: Workspace, *, m
kind="baseline", language=spec.language.value, track=spec.track.value,
env={"NODE_PATH": str(node_modules_dir())})
result = get_coding_agent(target).run(job)
- if not result.transient: # a session a 503 storm killed is not finished: a --redo must run it again
+ # a session a 503 storm killed, or one the watchdog found hung (D112 ``stalled``), is not
+ # finished: a --redo must run it again
+ if not (result.transient or result.stalled):
write_text_atomic(done, result.model_dump_json(indent=1))
for rel in files_for(spec.language):
src = ws.root / rel
diff --git a/eval/bench/_infra.py b/eval/bench/_infra.py
index 1654bfa3..c1154b0d 100644
--- a/eval/bench/_infra.py
+++ b/eval/bench/_infra.py
@@ -68,14 +68,15 @@ def _has_marker(text: str) -> bool:
def _looks_infra(exc: BaseException) -> bool:
"""The outage rules, applied to ONE exception. Typed first: the harness's own verdict
(``RoundFailed`` / ``GenerationResult`` ``.transient`` — a provider storm, a dropped socket
- — and ``.quota`` — the vendor's usage limit, "not ours") decided from the CLI's own record,
- which the bench must not re-guess from the message (N76: a gemini-cli (pre-D103) 503 storm that killed a
+ — ``.quota`` — the vendor's usage limit, "not ours" — and ``.stalled`` — a session the
+ watchdog found hung with nothing produced, which D112 no longer files as transient) decided
+ from the CLI's own record, which the bench must not re-guess from the message (N76: a gemini-cli (pre-D103) 503 storm that killed a
baseline twice matched no marker and was scored as an error). Then the HTTP status, from the
harness's one table (``models.parts.retryable_status``: 408/409/429/5xx), and a spent key
pool. The string markers are the fallback, for exceptions nobody typed and for the error
TEXT of old records. ONE copy: this ran as two hand-kept copies (head vs each wrapped
cause) until 2026-08-28, which is how a rule reaches one path and not the other."""
- if getattr(exc, "transient", False) is True or getattr(exc, "quota", False) is True:
+ if any(getattr(exc, flag, False) is True for flag in ("transient", "quota", "stalled")):
return True
if type(exc).__name__ == "KeyPoolExhausted" or isinstance(exc, TimeoutError):
return True
diff --git a/eval/bench/_oneshot.py b/eval/bench/_oneshot.py
index 87a64285..ab2aa8a8 100644
--- a/eval/bench/_oneshot.py
+++ b/eval/bench/_oneshot.py
@@ -463,7 +463,7 @@ class ClaudeOneShot:
end = claude_end(proc, env, stream, text)
(out_dir / "response.md").write_text(text)
return OneShotResult(ok=ok, text=text, usage=usage, tool_calls=usage.tool_calls, notes=notes,
- infra_failed=not ok and (end.transient or end.quota),
+ infra_failed=not ok and (end.transient or end.quota or end.stalled),
duration_s=round(proc.duration_s, 2), transcript_dir=str(out_dir))
@@ -523,7 +523,7 @@ class CodexOneShot:
end = codex_end(proc, events, text) # the provider's failure, read as the harness reads it (N76)
(out_dir / "response.md").write_text(text)
return OneShotResult(ok=ok, text=text, usage=usage, tool_calls=events.tool_calls, notes=notes,
- infra_failed=not ok and (end.transient or end.quota),
+ infra_failed=not ok and (end.transient or end.quota or end.stalled),
duration_s=round(proc.duration_s, 2), transcript_dir=str(out_dir))
diff --git a/eval/bench/compare_backends.py b/eval/bench/compare_backends.py
index c9f71ab1..fce44a19 100644
--- a/eval/bench/compare_backends.py
+++ b/eval/bench/compare_backends.py
@@ -376,7 +376,9 @@ def _run_bare_agent(arm: Arm, spec: Spec, cell: Path, eval_ws: Workspace, opts:
res.error_is_infra = True
if not (eval_ws.root / entry_of(spec)).is_file():
res.error = f"bare agent delivered no {entry_of(spec)} ({result.exit_reason}: {'; '.join(result.errors)[:300]})"
- res.error_is_infra = bool(result.transient)
+ # no file and a provider death or a hung session (D112 ``stalled``, which a watchdog kill no
+ # longer reports as transient): the session never happened, as in the one-shot arm
+ res.error_is_infra = bool(result.transient or result.stalled)
def _new_cell(item: BenchPrompt, arm: Arm, out: Path, opts: CompareOptions) -> tuple[Path, CellResult]:
diff --git a/eval/tests/test_bare_agent.py b/eval/tests/test_bare_agent.py
index 22c2398a..4566a0db 100644
--- a/eval/tests/test_bare_agent.py
+++ b/eval/tests/test_bare_agent.py
@@ -87,3 +87,19 @@ def test_a_storm_killed_session_is_not_cached_so_a_redo_runs_it(tmp_path, monkey
run_bare_agent(_spec(), "agy:gemini-3.8-flash", tmp_path, eval_ws, minutes=10)
run_bare_agent(_spec(), "agy:gemini-3.8-flash", tmp_path, eval_ws, minutes=10)
assert len(calls) == 2 and not (tmp_path / "agent" / ".bare_done.json").exists()
+
+
+def test_a_hung_session_is_not_cached_so_a_redo_runs_it(tmp_path, monkeypatch):
+ """D112: a watchdog kill is ``stalled``, not ``transient`` — a hung session is not finished either."""
+ calls: list[int] = []
+
+ class Hung:
+ def run(self, job: AgentJob) -> AgentResult:
+ calls.append(1)
+ return AgentResult(ok=False, exit_reason="timeout", stalled=True)
+
+ monkeypatch.setattr("bench._bare_agent.get_coding_agent", lambda target: Hung())
+ eval_ws = Workspace(tmp_path / "eval").create()
+ run_bare_agent(_spec(), "agy:gemini-3.8-flash", tmp_path, eval_ws, minutes=10)
+ run_bare_agent(_spec(), "agy:gemini-3.8-flash", tmp_path, eval_ws, minutes=10)
+ assert len(calls) == 2 and not (tmp_path / "agent" / ".bare_done.json").exists()
diff --git a/eval/tests/test_fixed_eval_language.py b/eval/tests/test_fixed_eval_language.py
index 71e7f32d..96bbad8f 100644
--- a/eval/tests/test_fixed_eval_language.py
+++ b/eval/tests/test_fixed_eval_language.py
@@ -152,7 +152,7 @@ def test_scene_cells_run_the_placement_gate_before_the_judge(monkeypatch, tmp_pa
placement = gates[1]
assert not placement.passed and [f.data["kind"] for f in placement.errors] == ["floating"]
assert placement.errors[0].target == "Quay/Crate" and placement.errors[0].data["gap_m"] == 0.31
- assert "Quay/Crate is floating 0.31 m" in placement.errors[0].message
+ assert "Quay/Crate is floating 0.310 m" in placement.errors[0].message # to the millimetre since D112
def test_the_fixed_judge_reads_the_in_run_payload_for_the_same_round(monkeypatch, tmp_path):
diff --git a/eval/tests/test_infra_failures.py b/eval/tests/test_infra_failures.py
index 0669dc9f..0f00437d 100644
--- a/eval/tests/test_infra_failures.py
+++ b/eval/tests/test_infra_failures.py
@@ -449,3 +449,30 @@ def test_the_scene_scaffold_leaves_no_example_entry_to_score(tmp_path):
ws = Workspace(tmp_path / "eval").create()
_render_scaffold(CompareDeps(Evaluator()), spec, ws)
assert not (ws.root / "src" / "scene.js").exists() and (ws.root / "src" / "lib" / "env.js").is_file()
+
+
+def test_a_hung_harness_round_is_infra_as_a_transport_death_was():
+ """D112: a watchdog kill is never ``transient`` any more; a session found hung with nothing produced
+ is ``stalled``. A harness run whose round 0 hung twice is the provider's, not the arm's — before D112
+ the same hang was transient whenever the CLI had logged one provider retry."""
+ from codeverse3d.tracks.steps import RoundFailed
+
+ assert is_infra_failure(RoundFailed("r00: killed by watchdog (idle)", stalled=True)) is True
+ assert is_infra_failure(RoundFailed("r00: the agents ran and changed nothing")) is False
+
+
+def test_a_hung_bare_agent_that_delivered_nothing_is_infra(tmp_path, monkeypatch):
+ """The bare arm reads the same flag: no file + a hung session is dropped, not scored 0 (D112)."""
+ from bench.compare_backends import CompareDeps, CompareOptions, parse_arm, run_cell
+ from bench.run_bench import Battery
+ from codeverse3d.contracts.agent import AgentResult
+ from tests.conftest import BATTERY, FakeEvaluator
+
+ def hung(spec, target, cell, eval_ws, *, minutes):
+ return AgentResult(ok=False, exit_reason="timeout", stalled=True, errors=["killed by watchdog (idle) after 600s"])
+
+ monkeypatch.setattr("bench._bare_agent.run_bare_agent", hung)
+ battery = Battery.load(BATTERY)
+ result = run_cell(battery, battery.prompts[0], parse_arm("agent:agy:gemini-3.8-flash"), tmp_path,
+ CompareOptions(judge="gemini:x", loop_judge="gemini:x"), CompareDeps(FakeEvaluator()))
+ assert (result.status, result.score, result.error_is_infra) == ("infra_failed", None, True)
diff --git a/harness/codeverse3d/agents/backends.py b/harness/codeverse3d/agents/backends.py
index 5a6d1665..10705f55 100644
--- a/harness/codeverse3d/agents/backends.py
+++ b/harness/codeverse3d/agents/backends.py
@@ -35,7 +35,6 @@ from codeverse3d.agents.cli_common import (
finish_session,
hardened_env,
invoke,
- is_transient_failure,
mcp_command_for,
provider_wait,
record_tool_calls,
@@ -246,7 +245,7 @@ def claude_end(proc: CompletedProc, env: dict[str, Any] | None, stream: ClaudeSt
``api_retry`` events, its result envelope) — the harness session and the bench one-shot alike."""
sub = str((env or {}).get("subtype", ""))
if proc.timed_out:
- return classify_end(proc, ok=False, text=text, provider_retried=bool(stream.retries))
+ return classify_end(proc, ok=False, text=text)
if env is None or proc.rc != 0:
# a 529 / overloaded exit is the provider's, not the task's (AgentResult.transient)
return classify_end(proc, ok=False, text=text, said=(proc.stderr, proc.stdout))
@@ -327,7 +326,7 @@ class ClaudeCodeAgent(_CliAgent):
errors.append(f"claude reported {sub or 'is_error'}: {text[-800:]}")
return finish_session(
s, ok=end.exit_reason == "completed", exit_reason=end.exit_reason, text=text, usage=usage,
- tool_calls=n_calls, turns=turns, errors=errors, transient=end.transient, quota=end.quota,
+ tool_calls=n_calls, turns=turns, errors=errors, transient=end.transient, quota=end.quota, stalled=end.stalled,
provider_wait_s=provider_wait([(t, b) for t, b, _ in stream.retries], ended, stream.progress),
rc=proc.rc, killed_reason=proc.killed_reason, num_turns=turns, effort=get_settings().agents.claude_effort,
session_id=(env or {}).get("session_id", ""), subtype=(env or {}).get("subtype", ""),
@@ -473,8 +472,7 @@ def codex_end(proc: CompletedProc, events: CodexEvents, text: str) -> SessionEnd
its own error events — a dropped stream, a 5xx it gave up on) — the harness session and the
bench one-shot alike."""
ok = not proc.timed_out and proc.rc == 0 and events.n_events > 0 and not (events.errors and events.turns_completed == 0)
- return classify_end(proc, ok=ok, text=text, said=(*events.errors, proc.stderr),
- provider_retried=is_transient_failure(*events.errors))
+ return classify_end(proc, ok=ok, text=text, said=(*events.errors, proc.stderr))
class CodexAgent(_CliAgent):
@@ -532,7 +530,7 @@ class CodexAgent(_CliAgent):
ok = end.exit_reason == "completed"
return finish_session(
s, ok=ok, exit_reason=end.exit_reason, text=text, usage=usage, tool_calls=events.tool_calls,
- turns=events.turns_completed, errors=errors, transient=end.transient, quota=end.quota,
+ turns=events.turns_completed, errors=errors, transient=end.transient, quota=end.quota, stalled=end.stalled,
rc=proc.rc, killed_reason=proc.killed_reason, thread_id=events.thread_id, effort=self.reasoning_effort,
turns_completed=events.turns_completed, usage_raw=events.usage_raw, usage_estimated=estimated,
)
@@ -566,6 +564,13 @@ AGY_LOG = "agy.log"
#: where agy keeps each conversation under its HOME: one SQLite file named by the envelope's
#: ``conversation_id``, a ``steps`` table whose ``step_payload`` is protobuf
AGY_CONVERSATIONS = Path(".gemini") / "antigravity-cli" / "conversations"
+#: where agy records each step as it takes it, under the session's HOME: ``brain/<id>/`` (step
+#: outputs, its own transcript) and the conversation database — the session's activity for the
+#: watchdog (:func:`~codeverse3d.agents.cli_common.activity_paths`; D112). agy prints nothing
+#: until it exits, so without them a session that reads before it writes is "idle" from second 0.
+#: Passed by name: the watchdog's walk skips ``.gemini``, and the rest of the dir (presence lock,
+#: updater, caches) is touched at start-up, not per step.
+AGY_STEP_DIRS = (Path(".gemini") / "antigravity-cli" / "brain", AGY_CONVERSATIONS)
#: agy's Gemini-API mode (1.2+, checked live on 1.3.4, 2026-10-13): ``modelProvider: "gemini"``
#: in its settings plus ``GEMINI_API_KEY`` in the env — no sign-in, billed to the key, and the
#: catalogue is the API's. Without the setting the key alone is ignored and the CLI asks for a
@@ -844,7 +849,7 @@ class AntigravityAgent(_CliAgent):
home = self.build_home(s)
effort = self.effort_for(job)
proc = invoke(s, self.build_argv(s), self.build_env(s, key=key, home=home), prompt=_compose_prompt_agy(s),
- model=self.model, effort=effort, key_tail=key[-4:])
+ activity=[home / d for d in AGY_STEP_DIRS], model=self.model, effort=effort, key_tail=key[-4:])
ended = time.time()
env = parse_agy_json(proc.stdout)
n_calls = self._record_trace(s, home, str((env or {}).get("conversation_id") or ""))
@@ -871,13 +876,12 @@ class AntigravityAgent(_CliAgent):
errors.append("empty response")
else:
ok = True
- end = classify_end(proc, ok=ok, text=text, said=said, provider_retried=bool(retries) or bool(died.get("retryable")),
- provider_failed=bool(died.get("retryable")))
+ end = classify_end(proc, ok=ok, text=text, said=said, provider_failed=bool(died.get("retryable")))
pool.report(key, _pool_outcome(end, ok, died))
usage.tool_calls = n_calls
return finish_session(
s, ok=ok, exit_reason=end.exit_reason, text=text, usage=usage, tool_calls=n_calls,
- turns=int((env or {}).get("num_turns") or 0), errors=errors, transient=end.transient, quota=end.quota,
+ turns=int((env or {}).get("num_turns") or 0), errors=errors, transient=end.transient, quota=end.quota, stalled=end.stalled,
provider_wait_s=provider_wait([(t, b) for t, b, _ in retries], ended),
rc=proc.rc, killed_reason=proc.killed_reason, agy_error=died, effort=effort,
conversation_id=(env or {}).get("conversation_id", ""), num_turns=(env or {}).get("num_turns", 0),
diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.py
index 5d6d7101..8bd3b973 100644
--- a/harness/codeverse3d/agents/cli_common.py
+++ b/harness/codeverse3d/agents/cli_common.py
@@ -15,7 +15,7 @@ import re
import sys
import threading
import time
-from collections.abc import Callable, Iterable, Mapping, Sequence
+from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
@@ -381,6 +381,23 @@ def _session_lock(ws: Workspace) -> threading.RLock:
return _WS_SESSION_LOCKS.setdefault(str(ws.root), threading.RLock())
+def exclusive_workspace(ws: Workspace) -> Iterator[None]:
+ """Hold ``ws``'s session lock for a HARNESS writer that commits while agent sessions may run on
+ the same workspace (the scene env recovery beside an escalated asset session, D112).
+
+ WHY the lock and not "restore an out-of-scope path to HEAD instead of ``head_before``": every
+ commit is ``git add -A``, so a harness commit made mid-session also absorbs the session's own
+ in-flight writes — restoring to HEAD would keep exactly the out-of-scope writes the revert
+ exists to undo, on every track. Holding the lock keeps every harness commit out of every
+ session's window, so ``head_before`` stays the whole truth :func:`_enforce_scope` relies on.
+ Argon loop iteration 5, scene_blender r1_10: the asset session's revert restored env.py to its
+ ``head_before`` and erased the harness's recovered env (+391 lines) — round 0 rendered black."""
+ lock = _session_lock(ws)
+ with lock:
+ yield
+
+
def release_session(s: Session) -> None:
"""Release ``s``'s workspace lock (idempotent). ``finish_session`` always calls it;
the CLI backends also call it in a ``finally`` so a session that crashes between
@@ -447,8 +464,9 @@ def _enforce_scope(s: Session) -> dict[str, str]:
to write and commit a root-level ``conftest.py``; then, for ``edit_only``, the
narrowing to ``files_hint`` + ``always_writable`` (a pre-existing file outside it is
out of scope; new files stay allowed). Only safe because sessions on one workspace
- are serialised (:data:`EXCLUSIVE_KINDS`): ``head_before`` holds no sibling's
- in-flight work."""
+ are serialised (:data:`EXCLUSIVE_KINDS`) and a harness writer that commits mid-run takes the
+ same lock (:func:`exclusive_workspace`): ``head_before`` holds no sibling's in-flight work and
+ no harness commit lands inside the session's window."""
roots = tuple(r.strip("/") for r in s.job.write_roots if r.strip("/"))
frozen = _clean(s.job.read_only)
narrow = (s.files_hint | _clean(s.job.always_writable)
@@ -501,6 +519,7 @@ def finish_session(
errors: list[str] | None = None,
transient: bool = False,
quota: bool = False,
+ stalled: bool = False,
provider_wait_s: float = 0.0,
usage_estimated: bool = False,
effort: str = "",
@@ -509,8 +528,8 @@ def finish_session(
"""Commit the agent's work, compute ``files_changed`` via git (attributed to this
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
+ backend's own count (``AgentResult.turns``); ``transient`` / ``quota`` / ``stalled`` its typed
+ failure class (:class:`SessionEnd`) and ``provider_wait_s`` the time its CLI lost to provider errors
(:func:`provider_wait`); ``effort`` what the backend passed its CLI (``AgentResult.effort``);
``extra`` lands in result.json only.
@@ -538,6 +557,7 @@ def finish_session(
transcript_path=str(s.traj.transcript_path if s.traj.transcript_path.exists() else s.traj.dir),
usage=usage, duration_s=duration, provider_wait_s=round(min(max(provider_wait_s, 0.0), duration), 3),
tool_calls=tool_calls, turns=turns, errors=errors, transient=transient and not quota, quota=quota,
+ stalled=stalled and not files,
usage_estimated=usage_estimated, effort=effort,
)
s.traj.write_result(res, kind=s.kind, label=s.label, round=s.round_index, attempt=s.attempt, job_label=s.job.label,
@@ -561,6 +581,10 @@ IDLE_GRACE_S = 300.0
#: a clock of its own must be set past it (agy ``--print-timeout``), or that clock decides.
HARD_GRACE_S = 300.0
+#: how often the watchdog re-reads the activity paths' mtimes; read at call time like
+#: :data:`POLL_S` so a test can turn it down.
+SCAN_S = 5.0
+
#: watchdog poll period. A real vendor CLI runs for minutes, so 1 s of latency on
#: noticing it exited is free — but a FAKE cli in a test exits in milliseconds and then
#: waits out the poll, which was ~1 s on every agent.run() in the suite. Same shape as
@@ -577,6 +601,7 @@ def invoke(
stdout_name: str = "stdout.json",
on_stdout: Callable[[str], None] | None = None,
on_stderr: Callable[[str], None] | None = None,
+ activity: Sequence[Path] = (),
**invoke_extra: Any,
) -> CompletedProc:
"""Run one CLI agent process under the watchdog and record it in the trajectory.
@@ -592,8 +617,9 @@ 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 — a ``shared_tree`` job's own files only,
- :func:`activity_paths`) and the stdout/stderr captures next to
+ transcript, ``src/`` + ``public/`` as activity dirs — a ``shared_tree`` job's own files only —
+ plus ``activity``, the backend's own record of the session's steps, :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,
@@ -620,23 +646,31 @@ def invoke(
else:
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=activity_paths(s),
+ idle_grace_s=IDLE_GRACE_S, poll_s=POLL_S, scan_s=SCAN_S,
+ on_line=on_line, stdin=prompt, activity_dirs=activity_paths(s, activity),
)
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]:
+def activity_paths(s: Session, steps: Sequence[Path] = ()) -> 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]
+ ``shared_tree`` job (D111) — its ``files_hint`` paths alone; plus ``steps``, where the
+ CLI itself records each step it takes (agy: its per-session HOME's ``brain/`` and
+ ``conversations/``, :data:`~codeverse3d.agents.backends.AGY_STEP_DIRS`).
+
+ 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. Narrowed to its own file, though, a session that is READING was idle from second 0:
+ agy prints nothing until it exits, so its soft window was a hard kill — 22 of 26 env
+ sessions and 4 of 21 refines of iteration 5 died at exactly the window with nothing written,
+ mid-read (D112). A step the CLI records is activity; a session that takes none for
+ ``IDLE_GRACE_S`` past its window is still killed there, and every session stops at its
+ hard limit."""
+ own = [s.ws.root / h for h in sorted(s.files_hint)] if s.job.shared_tree else [s.ws.src, s.ws.public]
+ return own + list(steps)
def watchdog_error(proc: CompletedProc) -> str:
@@ -758,26 +792,30 @@ class SessionEnd:
transient: bool = False
quota: bool = False
rate_limited: bool = False
+ stalled: bool = False
def classify_end(proc: CompletedProc, *, ok: bool, text: str, said: Sequence[str] = (),
- provider_retried: bool = False, provider_failed: bool = False,
- rate_limited: bool | None = None) -> SessionEnd:
+ provider_failed: bool = False, rate_limited: bool | None = None) -> SessionEnd:
"""THE end rule for every CLI backend (N71; D83) — each backend brings only its vendor's
- evidence: ``said`` (what the CLI printed about the call that ended it), ``provider_retried``
- (the CLI's OWN record of retried provider calls: claude's
- ``api_retry`` events, codex's error events, agy's log) and ``provider_failed`` (a typed
- vendor verdict: agy's ``AGY_ERROR.retryable``).
-
- A watchdog kill is ``timeout``, and transient only when nothing was produced AND the CLI
- recorded provider retries: a kill with no provider evidence is the task's (a retry buys
- another full window for the same outcome), whatever its stderr says. Any other failure is
- ``quota`` / ``transient`` by the vocabulary above, and ``budget`` when the usage limit is
- spent or the call was rate limited, for every vendor."""
+ evidence: ``said`` (what the CLI printed about the call that ended it) and ``provider_failed``
+ (a typed vendor verdict: agy's ``AGY_ERROR.retryable``).
+
+ A watchdog kill is ``timeout`` and never ``transient`` (the key it ran on is not at fault). It
+ is ``stalled`` when the watchdog found the session IDLE — no output, no workspace write and no
+ step the CLI recorded for ``IDLE_GRACE_S`` past its window — and it answered nothing: a hang
+ (iteration 5, r1_09: "connection reset by peer", then 10.8 minutes of silence), which the round
+ loop and the stage retry give ONE more session when the clock still holds a minimum window
+ (D112). A kill at the hard limit is the task's own pace: a retry buys the same window for the
+ same outcome. Until D112 a kill was transient whenever the CLI's log held ANY provider retry —
+ one 4 s 503 at t=0 — so the same 901 s / zero-file kill was retried in r1_05 and r1_09 and
+ ended r1_07 and r1_08 as no_change. Any other failure is ``quota`` / ``transient`` by the
+ vocabulary above, and ``budget`` when the usage limit is spent or the call was rate limited,
+ for every vendor."""
if ok:
return SessionEnd("completed")
if proc.timed_out:
- return SessionEnd("timeout", transient=provider_retried and not text.strip())
+ return SessionEnd("timeout", stalled=proc.killed_reason == "idle" and not text.strip())
quota = is_quota_failure(*said)
limited = is_rate_limited(*said) if rate_limited is None else rate_limited
return SessionEnd("budget" if quota or limited else "error",
diff --git a/harness/codeverse3d/contracts/agent.py b/harness/codeverse3d/contracts/agent.py
index f3c69026..c6bae1fb 100644
--- a/harness/codeverse3d/contracts/agent.py
+++ b/harness/codeverse3d/contracts/agent.py
@@ -90,7 +90,7 @@ class AgentJob(BaseModel):
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``; "
+ "``files_hint`` and only a write to a ``files_hint`` path (or a step the CLI records, D112) 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)",
)
@@ -142,6 +142,12 @@ class AgentResult(BaseModel):
"overloaded / a 429 rate limit / a dropped connection, as the CLI itself reported it — not of "
"the task: the round loop re-runs such a round once",
)
+ stalled: bool = Field(
+ default=False,
+ description="the watchdog killed the session as IDLE (no output, no workspace write, no recorded "
+ "step for the idle grace past its window) and it produced nothing: a hang, not the task's pace — "
+ "one more session when the clock allows a minimum window (D112; cli_common.classify_end)",
+ )
quota: bool = Field(
default=False,
description="the vendor's usage limit or credits are spent (codex 'You've hit your usage limit', "
diff --git a/harness/codeverse3d/languages/_js_lint.py b/harness/codeverse3d/languages/_js_lint.py
index 12d2d839..d9696392 100644
--- a/harness/codeverse3d/languages/_js_lint.py
+++ b/harness/codeverse3d/languages/_js_lint.py
@@ -249,6 +249,53 @@ def module_exports(src: str) -> frozenset[str] | None:
return frozenset(names)
+_EXPORT_FN_RE = re.compile(r"\bexport\s+(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*\(")
+# ``export const name = (params) => …`` / ``= async (…) =>`` / ``= function (…) {`` — the ``(`` opens the
+# parameter list only when ``=>`` follows its close (or the value is a ``function``); checked below
+_EXPORT_CONST_FN_RE = re.compile(r"\bexport\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?"
+ r"(function\b\s*\*?\s*[\w$]*\s*)?\(")
+# ``export const name = x => …``: one bare parameter
+_EXPORT_CONST_ARROW1_RE = re.compile(r"\bexport\s+(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s+)?"
+ r"([A-Za-z_$][\w$]*)\s*=>")
+#: one signature line's ceiling: a destructured options object can run to a screenful
+SIGNATURE_CHARS = 240
+
+
+def export_signatures(src: str) -> list[str]:
+ """Every name the module exports, an exported function — a declaration, or a ``const`` bound to
+ an arrow / function expression — as ``name(params)`` (its parameter list as written, whitespace
+ collapsed, capped at :data:`SIGNATURE_CHARS`), sorted; ``[]`` when the surface cannot be
+ enumerated (:func:`module_exports`). Facts read off the text —
+ the index a single-shot writer gets of a library it cannot open (D112)."""
+ names = module_exports(src)
+ if not names:
+ return []
+ code = strip_js(src, strings=False)
+ sigs: dict[str, str] = {}
+
+ def _add(name: str, params: str) -> None:
+ sig = f"{name}({' '.join(params.split())})"
+ sigs[name] = sig if len(sig) <= SIGNATURE_CHARS else sig[:SIGNATURE_CHARS - 2] + "…)"
+
+ def _close(start: int) -> int:
+ """The index just past the ``)`` matching the ``(`` before ``start``."""
+ depth, i = 1, start
+ while i < len(code) and depth:
+ depth += {"(": 1, ")": -1}.get(code[i], 0)
+ i += 1
+ return i
+
+ for m in _EXPORT_FN_RE.finditer(code):
+ _add(m.group(1), code[m.end():_close(m.end()) - 1])
+ for m in _EXPORT_CONST_FN_RE.finditer(code):
+ end = _close(m.end())
+ if m.group(2) or code[end:].lstrip().startswith("=>"): # a function, not a parenthesised value
+ _add(m.group(1), code[m.end():end - 1])
+ for m in _EXPORT_CONST_ARROW1_RE.finditer(code):
+ _add(m.group(1), m.group(2))
+ return [sigs.get(n, n) for n in sorted(names - {"default"})]
+
+
def exported_names(path: Path) -> frozenset[str] | None:
""":func:`module_exports` of the file at ``path`` (``None`` when it cannot be read)."""
try:
diff --git a/harness/codeverse3d/languages/base.py b/harness/codeverse3d/languages/base.py
index 72e49cb1..fb0b1461 100644
--- a/harness/codeverse3d/languages/base.py
+++ b/harness/codeverse3d/languages/base.py
@@ -79,6 +79,18 @@ class SceneRuntime(LanguageRuntime, Protocol):
the result lands in ``artifacts/assemble.json``."""
...
+ def lib_interface(self, ws: Workspace) -> str:
+ """The harness-owned ``src/lib/`` as facts, one line per module: the names it exports and
+ their parameter lists, read off the files (D112: the env recovery's single-shot cannot open
+ them, and invented ``gravel`` / ``pavingPatch`` / a ``roughness=`` keyword)."""
+ ...
+
+ def check_env(self, ws: Workspace) -> str:
+ """The env module alone: ``""`` when it lints clean, builds with nothing beside it and
+ lights what it builds; else the failure, quoted for a repair prompt (D112). A check the
+ harness cannot run returns ``""`` — never a verdict on the module."""
+ ...
+
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)."""
diff --git a/harness/codeverse3d/languages/scene_blender/__init__.py b/harness/codeverse3d/languages/scene_blender/__init__.py
index 43bce6b1..a1873dbd 100644
--- a/harness/codeverse3d/languages/scene_blender/__init__.py
+++ b/harness/codeverse3d/languages/scene_blender/__init__.py
@@ -17,6 +17,7 @@ from __future__ import annotations
import ast
import json
+import logging
import math
import re
import time
@@ -60,6 +61,7 @@ from codeverse3d.languages._common import (
target_line,
ws_rel,
)
+from codeverse3d.languages._js_lint import SIGNATURE_CHARS
from codeverse3d.languages.blender import (
BlenderNotFoundError,
BpyCollector,
@@ -77,6 +79,7 @@ if TYPE_CHECKING:
from codeverse3d.spatial.probes import SceneProbeResult
LANGUAGE = Language.SCENE_BLENDER
+log = logging.getLogger(__name__)
ENTRY_REL = ENTRY_FILE[LANGUAGE] # "src/scene.py"
GATE = "lint:scene_blender"
#: the harness's frame clock: ``frame(t) = 1 + round(t * FPS)`` — the wrapper sets it, the render
@@ -426,12 +429,62 @@ LIB_DIR = STARTER_DIR / "lib"
ENV_FILE = "src/env.py"
+#: the env check's data entry (deleted after use): no zone, asset or hero, so only build_env runs
+ENV_CHECK_REL = "src/_c3d_env_check.py"
+
+
+_TB_FRAME_RE = re.compile(r'File "(?P<file>[^"]+)", line (?P<line>\d+)')
+
+
+def env_frame(traceback_text: str) -> str:
+ """``src/env.py:N`` — the deepest frame of a Python traceback that is the env module's own, with its
+ source line when the traceback quotes it — or ``""`` when no frame is. ``check_env`` leads with it
+ when the raise surfaced inside a ``src/lib`` helper (D112 review: iteration 5 blender r1_04's
+ recovered env was reported as ``src/lib/mesh.py:69`` while its own bad call was ``env.py:287``)."""
+ lines = traceback_text.splitlines()
+ found = ""
+ for i, text in enumerate(lines):
+ m = _TB_FRAME_RE.search(text)
+ if m is None or not m.group("file").replace("\\", "/").endswith("/" + ENV_FILE):
+ continue
+ code = lines[i + 1].strip() if i + 1 < len(lines) and not _TB_FRAME_RE.search(lines[i + 1]) else ""
+ found = f"{ENV_FILE}:{m.group('line')}" + (f" `{code[:160]}`" if code else "")
+ return found
+
+
def lib_files() -> list[Path]:
"""The library modules shipped into a workspace, sorted (the package's ``__init__.py`` ships
too but names no calls, so the catalog does not list it)."""
return sorted(p for p in LIB_DIR.glob("*.py") if p.name != "__init__.py")
+def lib_interface(ws: Workspace) -> str:
+ """The workspace's ``src/lib/`` surface, one line per module: every public top-level function
+ with its parameters as written, every public class and UPPER_CASE constant. Facts read off the
+ files — what a single-shot writer, which cannot open them, may call (D112)."""
+ rows: list[str] = []
+ lib = ws.src / "lib"
+ for p in sorted(lib.glob("*.py")) if lib.is_dir() else []:
+ if p.name == "__init__.py":
+ continue
+ try:
+ tree = ast.parse(p.read_text(errors="replace"))
+ except SyntaxError:
+ continue
+ names: list[str] = []
+ for node in tree.body:
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) and not node.name.startswith("_"):
+ sig = f"{node.name}({ast.unparse(node.args)})"
+ names.append(sig if len(sig) <= SIGNATURE_CHARS else sig[:SIGNATURE_CHARS - 2] + "…)")
+ elif isinstance(node, ast.ClassDef) and not node.name.startswith("_"):
+ names.append(node.name)
+ elif isinstance(node, ast.Assign):
+ names += [t.id for t in node.targets if isinstance(t, ast.Name) and t.id.isupper() and not t.id.startswith("_")]
+ if names:
+ rows.append(f"lib/{p.name} (lib.{p.stem}): " + ", ".join(names))
+ return "\n".join(rows)
+
+
def _put(path: Path, text: str, written: list[Path]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
@@ -754,6 +807,52 @@ class SceneBlenderRuntime:
def lint(self, ws: Workspace) -> GateReport:
return lint(ws)
+ def lib_interface(self, ws: Workspace) -> str:
+ return lib_interface(ws)
+
+ def check_env(self, ws: Workspace) -> str:
+ """``""`` when ``src/env.py`` lints clean, runs ``build_env`` in Blender with nothing beside
+ it, and lights what it builds (``probes.unlit``); else the first failure, quoted. A Blender
+ that cannot run is the harness's: ``""``. What the scene track asks of a recovered env (D112):
+ in argon loop iteration 5, three recovered env.py modules failed at assembly (a ``curb_ mats``
+ SyntaxError, an AttributeError, an unknown ``roughness=`` keyword) and two more that a scope
+ revert kept from assembly were broken too (``noise_ centered = ...`` did not parse; a tuple
+ rotation raised inside ``lib/mesh.py``)."""
+ from codeverse3d.spatial.probes import unlit
+
+ env = ws.root / ENV_FILE
+ if not env.is_file():
+ return f"{ENV_FILE} does not exist"
+ own = [f for f in lint_scene_source(env.read_text(errors="replace"), target=ENV_FILE, role="env")
+ if f.severity == Severity.ERROR]
+ if own:
+ return "\n".join(f"{f.target}: {f.message}" + (f" ({f.fix_hint})" if f.fix_hint else "") for f in own[:6])
+ entry = ws.root / ENV_CHECK_REL
+ entry.write_text(render_scene_py([], [], [], []))
+ try:
+ run = self.run_wrapper(ws, ws.artifacts / "env_check", zones={}, blend=False, entry=ENV_CHECK_REL)
+ except BlenderNotFoundError as e:
+ log.warning("env check could not run: %s", e)
+ return ""
+ finally:
+ entry.unlink(missing_ok=True)
+ raised = [e for e in run.report.get("errors") or [] if e.get("stage") == "env"]
+ if raised:
+ e = raised[0]
+ at = f"{e.get('error_file') or ENV_FILE}:{e.get('error_line')}" if e.get("error_line") else ENV_FILE
+ if (e.get("error_file") or ENV_FILE) != ENV_FILE and (own_at := env_frame(str(e.get("traceback") or ""))):
+ # the raise is inside a src/lib helper: the repair writes env.py, so the env's own
+ # call line leads and the helper's line stays as where it surfaced
+ at = f"{own_at} (raised in {at})"
+ return f"{at}: build_env raised {e.get('error_type')}: {str(e.get('error_message'))[:600]}"
+ if not run.result.ok:
+ if run.result.harness_failure:
+ return ""
+ return f"{ENV_FILE}: the env-only build failed: {run.result.error_type}: {run.result.error_message}"[:900]
+ facts = run.facts
+ dark = unlit({"totals": {"lights": int(facts.get("lights") or 0)}, "background": facts.get("background")}, offline=True)
+ return f"{ENV_FILE}: {dark.message}" if dark is not None else ""
+
# ------------------------------------------------------------------ the Blender process
def blender_binary(self) -> str:
b = self._blender or self._settings.resolve_blender()
@@ -762,13 +861,14 @@ class SceneBlenderRuntime:
return b
def run_wrapper(self, ws: Workspace, out_dir: Path, *, zones: dict[str, str] | None = None, blend: bool = True,
- timeout_s: float | None = None) -> WrapperRun:
+ timeout_s: float | None = None, entry: str = ENTRY_REL) -> WrapperRun:
"""Build the workspace in Blender, outputs into ``out_dir`` (``bpy_build.json``,
- ``bpy_census.json``, ``census.glb``, ``scene.blend``); ``zones`` overrides the entry's ZONES."""
+ ``bpy_census.json``, ``census.glb``, ``scene.blend``); ``zones`` overrides the entry's ZONES;
+ ``entry`` is another data entry under ``src/`` (the env check's, :func:`check_env`)."""
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, "--zone-key", ZONE_ROOT_KEY,
+ "--scene", str(ws.root / entry), "--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:
diff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.py
index 3f9974aa..3ded21f1 100644
--- a/harness/codeverse3d/languages/scene_threejs/__init__.py
+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py
@@ -661,6 +661,64 @@ def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0, sun_azimuth_de
return ZoneProbeReport(probes=probes, census=census, other_errors=other, camera_specs=s.get("fitted_cameras") or {})
+# --------------------------------------------------------------------------- the env module alone
+#: the env check's probe entry (deleted after use; the leading ``_`` keeps it out of every listing)
+ENV_PROBE_REL = "src/_c3v_env_probe.js"
+
+
+def lib_interface(ws: Workspace) -> str:
+ """The workspace's ``src/lib/`` surface, one line per module: every exported name, a function
+ with its parameter list as written (:func:`~codeverse3d.languages._js_lint.export_signatures`).
+ Facts read off the files — what a single-shot writer, which cannot open them, may import (D112)."""
+ from codeverse3d.languages._js_lint import export_signatures
+
+ lib = ws.src / "lib"
+ rows = [f"lib/{p.name}: " + ", ".join(sigs) for p in sorted(lib.glob("*.js"))
+ if (sigs := export_signatures(p.read_text(errors="replace")))] if lib.is_dir() else []
+ return "\n".join(rows)
+
+
+def check_env(ws: Workspace, *, timeout_s: float = 90.0) -> str:
+ """``""`` when ``src/env.js`` passes the lint (its own findings), loads and runs ``buildEnv`` in the
+ browser host with no zone beside it, and lights what it builds (``probes.unlit``); else the first
+ failure, quoted. A probe that cannot run is the harness's, not the module's: ``""`` (logged).
+ What the scene track asks of a recovered env before it counts as written (D112): 5 of 21
+ recovered env modules of argon loop iteration 5 failed only later, at assembly."""
+ import logging
+
+ from codeverse3d.spatial.probes import unlit
+ from codeverse3d.spatial.render_scene import SceneRenderError, probe_env_args, run_scene_script
+
+ rel = SCENE_FILES[1]
+ if not (ws.root / rel).is_file():
+ return f"{rel} does not exist"
+ own = [f for f in lint(ws).errors if (f.target or "").split(":")[0] == rel]
+ if own:
+ return "\n".join(f"{f.target}: {f.message}" + (f" ({f.fix_hint})" if f.fix_hint else "") for f in own[:6])
+ probe_path = ws.root / ENV_PROBE_REL
+ probe_path.write_text(_probe_module([], []))
+ args = ["--ws", str(ws.root), "--scene", ENV_PROBE_REL, "--timeout-ms", str(int(timeout_s * 1000)), *probe_env_args()]
+ try:
+ res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)
+ except SceneRenderError as e:
+ if e.scene_timed_out:
+ return f"{rel}: buildEnv did not finish inside the {timeout_s:.0f} s probe budget"
+ logging.getLogger(__name__).warning("env check could not run: %s", e)
+ return ""
+ finally:
+ probe_path.unlink(missing_ok=True)
+ s = res.summary
+ # nothing but the env module (and the library it imports) runs in this probe: every console error is its
+ errors = [e for e in s.get("console_errors", []) if not e.startswith("boot[")]
+ boot = s.get("boot") or {}
+ if not boot.get("ok"):
+ errors.insert(0, f"the env probe did not boot [{boot.get('stage')}]: {boot.get('error', '')}")
+ if errors:
+ return "\n".join(e[:900] for e in errors[:3])
+ dark = unlit(s.get("census") or {}, offline=False)
+ return f"{rel}: {dark.message}" if dark is not None else ""
+
+
# --------------------------------------------------------------------------- cameras
def fallback_camera(plan: ScenePlan | None, azimuth_deg: float = SUN_AZIMUTH_GUESS_DEG) -> CameraPlan:
"""An overview when nothing was measurable: on the lit side (``azimuth_deg`` is the scene's
@@ -851,6 +909,12 @@ class SceneThreeJsRuntime:
def lint(self, ws: Workspace) -> GateReport:
return lint(ws) # the module-level gates function (class ns is not in method scope)
+ def lib_interface(self, ws: Workspace) -> str:
+ return lib_interface(ws)
+
+ def check_env(self, ws: Workspace) -> str:
+ return check_env(ws)
+
def render_asset(self, ws: Workspace, name: str, out_dir: Path, *, timeout_s: float = 180.0) -> RenderSet:
"""Quick sheet of ONE procedural asset module, on the rig a Blender hero's GLB gets.
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js
index 7cb4ebc3..1da8bb72 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/celestial.js
@@ -335,8 +335,9 @@ function shimmerMaterial(strength, speed, cells, aspect, height, phase) {
* Combine with a dome, never instead of one: `worldShell({mood:
* 'night'})` (lib/environment.js) draws the gradient this sits in
* front of, or `makeSky(scene, { rig })` with a night `sunRig()` for
- * a graded physical dome. Both leave `scene.background` null and
- * neither writes depth, so the stars paint over either one.
+ * a graded physical dome. Neither writes depth (`scene.background`
+ * is only the clear colour behind them), so the stars paint over
+ * either one.
*
* @param {object} [opts]
* `count` stars (default 1400); `radius` metres to the star sphere
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js
index ac9f53b1..0fe7cd7f 100644
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js
+++ b/harness/codeverse3d/languages/scene_threejs/starter/src/lib/sky.js
@@ -2,7 +2,10 @@
* The physical atmosphere dome — a graded Preetham sky in one call.
* Contract: the dome only GLOWS — pair it with a key light on the
* SAME sun vector (`sunRig()` from ./environment.js) — and it owns
- * the backdrop: `scene.background` stays null, never a second dome.
+ * the backdrop: never a second dome. `scene.background` is the clear
+ * colour behind it: a background the caller set is kept, an unset one
+ * becomes the dome's own horizon colour (the census reads it — the
+ * `no_background` gate — and it is what shows past the dome's far clip).
*
* Graded for THIS renderer (ACES filmic, exposure 1.0, no post chain,
* measured 2026-09-01): three's Sky shader gamma-encodes its radiance
@@ -130,15 +133,16 @@ export function skyRadiance(dir, sunDir, opts = {}) {
}
/**
- * Build the atmosphere dome, add it to the scene, null the
- * background, and return the normalized sun vector for the key light.
+ * Build the atmosphere dome, add it to the scene, give an unset
+ * background the dome's horizon colour, and return the normalized sun
+ * vector for the key light.
* Sun precedence: `rig` (uses the rig's baked skySunDir; hides its flat
* disc — the Preetham shader draws its own; a NIGHT rig's disc is the
* moon and stays) > `sunDir` (normalized copy, input untouched) >
* `elevationDeg`/`azimuthDeg` (same convention as `sunRig()`).
*
- * @param {THREE.Scene} scene The dome is added to it and its
- * `background` is set to null (the dome IS the backdrop).
+ * @param {THREE.Scene} scene The dome is added to it; a `background`
+ * the caller set stays, an unset one becomes the dome's horizon colour.
* @param {object} [opts]
* `rig` a `sunRig()` result to slave to; `sunDir` explicit sun
* vector; `elevationDeg` (default 15) / `azimuthDeg` (default 135)
@@ -246,7 +250,20 @@ export function makeSky(scene, opts = {}) {
sky.material.needsUpdate = true;
scene.add(sky);
- scene.background = null; // the dome IS the backdrop (measured req)
+ // The dome is the backdrop; the background is only the clear colour behind it. It used to
+ // be nulled here, which wiped a background the caller had set and failed the harness's own
+ // `no_background` gate (D112: three of iteration 5's scenes). Keep the caller's, else the
+ // dome's graded horizon on the side away from the sun.
+ if (!scene.background) {
+ _tmp.set(-sunDir.x, 0, -sunDir.z);
+ if (_tmp.lengthSq() < 1e-12) _tmp.set(1, 0, 0);
+ _tmp.normalize().setY(0.02).normalize();
+ const [r, g, b] = skyRadiance(_tmp.clone(), sunDir, {
+ turbidity: u.turbidity.value, rayleigh: u.rayleigh.value, mieCoefficient: u.mieCoefficient.value,
+ mieDirectionalG: u.mieDirectionalG.value, gain: u.uSkyGain.value, gamma: u.uSkyGamma.value,
+ });
+ scene.background = new THREE.Color().setRGB(r, g, b); // linear: the working colour space
+ }
attachDisposal(sky, snapshotResources(sky));
// Update every dependent twilight uniform together. This controls the dome;
// callers still update their scene lights and rebake environment lighting.
diff --git a/harness/codeverse3d/orchestrator.py b/harness/codeverse3d/orchestrator.py
index c037ac1d..d10b5e9d 100644
--- a/harness/codeverse3d/orchestrator.py
+++ b/harness/codeverse3d/orchestrator.py
@@ -451,6 +451,23 @@ class RoundPolicy:
parallel_min_tasks: int = 2 # fan out only when >= this many file-disjoint groups
n_candidates: int = 1 # best-of-N baseline (candidates generated in parallel, best kept)
judge_samples: int = 1 # VLM judge samples per round (flash: std ≈ 0.001 between samples → 1 is enough)
+ #: seconds of the hard clock a refine / rebuild session leaves for its round's build, gates, render
+ #: and judge (D112: 201 s measured for iteration 5 r1_09 — build 11 s, render 24 s, judge 166 s)
+ judge_reserve_s: float = 240.0
+ #: the shortest AGENT session window worth opening; with ``judge_reserve_s`` it is what a refine
+ #: round, a transport / stall retry or a stage retry needs left on the clock before it is launched
+ #: (D112). A single-shot call has no session window: it needs the judge reserve only.
+ min_session_s: float = 180.0
+
+ def need_s(self, *, single_shot: bool = False) -> float:
+ """What :meth:`can_open` asks of the clock: the judge reserve, plus the minimum session window
+ when the generation is an agent session."""
+ return self.judge_reserve_s + (0.0 if single_shot else self.min_session_s)
+
+ def can_open(self, budget: BudgetGuard, *, single_shot: bool = False) -> bool:
+ """Does the hard clock still hold :meth:`need_s` — a minimum session window (agent sessions
+ only) plus the judge reserve?"""
+ return budget.left_s() >= self.need_s(single_shot=single_shot)
def gate_error_count(r: RoundRecord) -> int:
@@ -569,6 +586,10 @@ class BudgetGuard:
left = max(0.0, (self.soft_minutes() if soft else self.hard_minutes) - self.elapsed_minutes()) * 60.0
return int(max(floor_s, min(float(want_s), left) if left > 0 else floor_s))
+ def left_s(self, *, soft: bool = False) -> float:
+ """Seconds left before the hard ceiling (the soft one with ``soft``), never negative."""
+ return max(0.0, (self.soft_minutes() if soft else self.hard_minutes) - self.elapsed_minutes()) * 60.0
+
def summary(self) -> dict[str, float]:
"""``record.extra["budget"]``: the clock at the end, beside its ceiling."""
return {"elapsed_min": round(self.elapsed_minutes(), 2), "max_minutes": self.budget.max_minutes}
diff --git a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
index 856db474..c3e86919 100644
--- a/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
+++ b/harness/codeverse3d/prompts/scene_threejs/effects_catalog.md
@@ -49,7 +49,7 @@ and `src/assets/x.js` say `import { makeGrass } from '../lib/grass.js';`,
| a Blender hero's own keyframed motion (the GLB carries a clip) | nothing to call — the assembled scene plays every clone's clips; `clone.userData.clipOffset = 0.7` de-phases a copy |
| the sun, the fill and the baked environment | `sunRig({ azimuth, elevation })` — `lib/environment.js`; returns `{ sun, fill, sunDisc, envTex, sunDir }`. Add the lights, assign `scene.environment = rig.envTex` |
| a rectangular interior's walls, ceiling and window/door openings | `roomShell({ center, extents, openings, thickness, wallColor, ceilingColor, glazed, frameColor, bay })` — `lib/environment.js`; walls sit outward of the box you pass (inner face = that box's face, which need not be the plan bounds), openings cut as span / sill / lintel panels; glazed: true makes every wall and the roof glass on an iron frame grid (a conservatory, greenhouse, glass atrium). One option for a box-shaped room; the requirement for any interior is that it reads as enclosed from every camera (six runs measured "not enclosed, a diorama on a flat plane" with no walls or roof) |
-| the sky itself | `makeSky(scene, { rig })` — `lib/sky.js`; the dome IS the backdrop, so `scene.background` stays null |
+| the sky itself | `makeSky(scene, { rig })` — `lib/sky.js`; the dome IS the backdrop; it keeps a `scene.background` already set and gives an unset one its horizon colour |
| cloud, cirrus | `makeClouds({ preset, sunDir, quality: 'balanced' })` · `makeCirrus()` — one ray-marched cloud deck with scene-lit self-shadowing; `lib/clouds.js` |
| volumetric cumulus with internal sunlight attenuation | `makeCloudVolume({ size: [600,180,360], coverage: 0.55, density: 0.028, wind: [2.5,0.4], seed, quality: 'balanced' })` — `lib/cloudvolume.js`; Mesh centred on its local origin. Move it to cloud altitude. Wind advects density/erosion inside a bounded billow scaffold; translate the Mesh to move the whole cloud. `userData.sampleDensity(x,y,z,t)` mirrors the GPU field. Use one bounded sky volume and inspect its screen cost. No terrain shadows or opaque-depth intersections. |
| stars, the Milky Way, aurora, heat shimmer | `makeStars` · `makeAurora` · `makeHeatShimmer` — `lib/celestial.js` |
diff --git a/harness/codeverse3d/prompts/tracks/scene_env.j2 b/harness/codeverse3d/prompts/tracks/scene_env.j2
index 200d4019..8c1ee323 100644
--- a/harness/codeverse3d/prompts/tracks/scene_env.j2
+++ b/harness/codeverse3d/prompts/tracks/scene_env.j2
@@ -121,6 +121,23 @@ table it prints: every authored camera must pass the exposure checks.
{{ textures }}
{% endif %}
+{% if lib_interface is defined and lib_interface %}
+
+## What `src/lib/` exports (read from the files in this workspace)
+{{ lib_interface }}
+An import from `src/lib/` can bind only these names; a call passes only these parameters.
+{% endif %}
+{% if env_check_error is defined and env_check_error %}
+
+## The previous single-shot of `{{ env_file }}` failed the harness's env check
+```
+{{ env_check_error }}
+```
+That file, as written (return it COMPLETE, with the failure fixed):
+```
+{{ env_previous }}
+```
+{% endif %}
## Output
{{ output_format }}
diff --git a/harness/codeverse3d/prompts/tracks/scene_env_bpy.j2 b/harness/codeverse3d/prompts/tracks/scene_env_bpy.j2
index c9775c8d..350f7fb2 100644
--- a/harness/codeverse3d/prompts/tracks/scene_env_bpy.j2
+++ b/harness/codeverse3d/prompts/tracks/scene_env_bpy.j2
@@ -105,6 +105,23 @@ and the atmosphere were found.
(These are PNG files under `public/textures/`: load one with `bpy.data.images.load("public/textures/<file>",
check_existing=True)` into an Image Texture node; the build runs with the workspace root as its working directory.)
{% endif %}
+{% if lib_interface is defined and lib_interface %}
+
+## What `src/lib/` exports (read from the files in this workspace)
+{{ lib_interface }}
+An import from `src/lib/` can bind only these names; a call passes only these parameters.
+{% endif %}
+{% if env_check_error is defined and env_check_error %}
+
+## The previous single-shot of `{{ env_file }}` failed the harness's env check
+```
+{{ env_check_error }}
+```
+That file, as written (return it COMPLETE, with the failure fixed):
+```
+{{ env_previous }}
+```
+{% endif %}
## Output
{{ output_format }}
diff --git a/harness/codeverse3d/prompts/tracks/scene_refine.j2 b/harness/codeverse3d/prompts/tracks/scene_refine.j2
index 32a52608..dd872bf7 100644
--- a/harness/codeverse3d/prompts/tracks/scene_refine.j2
+++ b/harness/codeverse3d/prompts/tracks/scene_refine.j2
@@ -81,7 +81,9 @@ the number passes; a judge note that repeats needs a visible change in the named
## Tools
{{ tool_cards }}
Run `build` → `check_placement` → fix → `build` after editing (and `scene_probe` for the census);
-finish only when both are clean. `check_placement` measures floating / sunken / unsupported /
+finish only when both are clean. `artifacts/scene_probe.json` is the probe driver's raw dump (thousands of
+lines); `check_placement` returns the placement rows, each with its gap and the tolerance it was measured
+against. `check_placement` measures floating / sunken / unsupported /
interpenetrating assets deterministically — its numbers, not your impression. `scene_views` prints the
frame table and the MEASURED MOTION per camera — use those numbers, not your impression.
{% endif %}
diff --git a/harness/codeverse3d/prompts/tracks/scene_refine_bpy.j2 b/harness/codeverse3d/prompts/tracks/scene_refine_bpy.j2
index 3481ef26..cf3f2c33 100644
--- a/harness/codeverse3d/prompts/tracks/scene_refine_bpy.j2
+++ b/harness/codeverse3d/prompts/tracks/scene_refine_bpy.j2
@@ -87,7 +87,9 @@ named view. The skills named below are in your session's skill list; the contra
## Tools
{{ tool_cards }}
Run `build` → `check_placement` → fix → `build` after editing (and `scene_probe` for the census);
-finish only when both are clean. `check_placement` measures floating / sunken / unsupported /
+finish only when both are clean. `artifacts/scene_probe.json` is the probe driver's raw dump (thousands of
+lines); `check_placement` returns the placement rows, each with its gap and the tolerance it was measured
+against. `check_placement` measures floating / sunken / unsupported /
interpenetrating assets deterministically — its numbers, not your impression. `scene_views` prints the
frame table and the MEASURED MOTION per camera — use those numbers, not your impression.
{% endif %}
diff --git a/harness/codeverse3d/skills/c3d-scene-atmosphere/SKILL.md b/harness/codeverse3d/skills/c3d-scene-atmosphere/SKILL.md
index 289b7d71..b01b68fe 100644
--- a/harness/codeverse3d/skills/c3d-scene-atmosphere/SKILL.md
+++ b/harness/codeverse3d/skills/c3d-scene-atmosphere/SKILL.md
@@ -29,7 +29,7 @@ stars / clouds / sun / moon / atmosphere and spans more than 50 m (or by size al
place has a visible sky at all is the brief's (an interior, a cave, deep space).
Strong options: `makeSky(scene, { rig })` from `lib/sky.js` is the shipped dome, lit from the
-same `sunRig` as the scene (`scene.background` stays null). One of your own is a `BackSide`
+same `sunRig` as the scene (it keeps a `scene.background` already set, else sets its horizon colour). One of your own is a `BackSide`
sphere (`fog: false`, `depthWrite: false`, built with `makeShaderMaterial` from `lib/shader.js`
so the tonemap chunks stay) whose fragment colour is a function of the view direction: a
horizon-to-zenith gradient, a sun term around `sunDir` (a halo and, if the brief's weather
diff --git a/harness/codeverse3d/spatial/probes.py b/harness/codeverse3d/spatial/probes.py
index aaf307e0..5cc1e28c 100644
--- a/harness/codeverse3d/spatial/probes.py
+++ b/harness/codeverse3d/spatial/probes.py
@@ -301,16 +301,15 @@ def _census_findings(c: dict[str, Any], *, offline: bool = False) -> list[GateFi
kind="unobserved_animation_hook", hook_path=hook.get("path"),
))
tot = c.get("totals", {})
+ if (dark := unlit(c, offline=offline)) is not None:
+ out.append(dark)
if offline:
- if tot.get("lights", 0) == 0 and not c.get("background"):
- out.append(_f(gate, Severity.WARN, "scene has no lamps and no world: it renders black", target="src/env.py",
- hint="in build_env create a world (Sky Texture) and a Sun lamp"))
if tot.get("meshes", 0) == 0:
out.append(_f(gate, Severity.ERROR, "scene has no meshes", target="src/scene.py",
hint="every zone's build(ctx) links its objects into ctx.collection"))
out.extend(_offline_findings(c))
else:
- if tot.get("lights", 0) == 0:
+ if tot.get("lights", 0) == 0 and dark is None:
out.append(_f(gate, Severity.WARN, "scene has no lights (MeshStandardMaterial renders black)", target="src/env.js",
hint="add new THREE.DirectionalLight (castShadow) + new THREE.HemisphereLight in buildEnv"))
if tot.get("meshes", 0) == 0:
@@ -330,6 +329,29 @@ def _census_findings(c: dict[str, Any], *, offline: bool = False) -> list[GateFi
return out
+def unlit(census: Mapping[str, Any], *, offline: bool) -> GateFinding | None:
+ """The ERROR for a scene that nothing lights: no lamp and no world (bpy), or no light, no
+ background and no environment map (three.js) — every frame renders black.
+
+ An ERROR since D112 (was a WARN): argon loop iteration 5, scene_blender r1_10 built round 0 on
+ the skeleton's placeholder env (lights 0, background null); the build passed with
+ "0 errors", the round-0 repair fixed an asset and left the env, and every frame was 96-99 %
+ black — judged 0.109 after the full render and judge spend. An ERROR fails the build, so the
+ repair session is handed the env module before anything is rendered. The same rule checks
+ an env module alone (``SceneRuntime.check_env``)."""
+ lights = int((census.get("totals") or {}).get("lights", 0) or 0)
+ if lights or census.get("background"):
+ return None
+ if offline:
+ return _f(PROBE_GATE, Severity.ERROR, "scene has no lamps and no world: it renders black", target="src/env.py",
+ kind="unlit", hint="build_env must light the scene: a world (sky or background colour) and/or lamps")
+ if census.get("environment"):
+ return None
+ return _f(PROBE_GATE, Severity.ERROR, "scene has no lights, no scene.background and no scene.environment: it renders black",
+ target="src/env.js", kind="unlit",
+ hint="buildEnv must light the scene: lights, and the sky as scene.background / scene.environment")
+
+
def _draw_findings(c: dict[str, Any]) -> list[GateFinding]:
"""The scene draw budget (D99): ``totals.draws`` against ``DRAWS_WARN_SCENE`` /
``MAX_DRAWS_SCENE``. The count is the census's, so it is the number ``scene_probe`` shows
diff --git a/harness/codeverse3d/spatial/scene_placement.py b/harness/codeverse3d/spatial/scene_placement.py
index 04248471..b505a95e 100644
--- a/harness/codeverse3d/spatial/scene_placement.py
+++ b/harness/codeverse3d/spatial/scene_placement.py
@@ -221,9 +221,18 @@ def infer_indoor(text: str) -> bool:
def is_interior(plan: Any) -> bool:
- """The plan's typed ``interior`` flag (D69) when it says so, else the setting text."""
+ """The plan's typed ``interior`` flag (D69) whenever it has one, True OR False; the setting
+ text only for a plan without it (absent or None — a plan.json older than the field).
+
+ It used to be ``bool(flag) or infer_indoor(...)``, so ``interior: False`` lost to the word
+ list: a zone named ``GiantTrunkCorridor`` snake-splits to "corridor", and "hold the frame
+ luminance inside 0.42-0.62" says "inside". 6 of 26 outdoor plans of argon loop iteration 5
+ were measured at the 2 cm indoor tolerance — three 4-5 cm gaps in a redwood forest became
+ ``floating`` ERRORs and a 0.60 gate cap (D112)."""
flag = plan.get("interior") if isinstance(plan, dict) else getattr(plan, "interior", None)
- return bool(flag) or infer_indoor(setting_text(plan))
+ if isinstance(flag, bool):
+ return flag
+ return infer_indoor(setting_text(plan))
#: the fix hints / messages that name a language's API, per scene language (``census["language"]``;
@@ -312,8 +321,13 @@ def _cantilever(row: AssetRow, p: Placement) -> bool:
def _asset_findings(rows: list[AssetRow], *, p: Placement, floating_m: float, ground_y: float | None,
- words: dict[str, str]) -> list[GateFinding]:
+ words: dict[str, str], indoor: bool = False) -> list[GateFinding]:
+ """A floating / unsupported row states its gap to the millimetre and the tolerance it was
+ measured against (D112): "floating 0.05 m" for a 0.048 m gap in a forest the prompt calls
+ outdoors (0.05 m tolerance) read as a contradiction, and the refine session of iteration 5
+ r1_07 spent its whole window paging a 3 772-line probe dump to resolve it."""
out: list[GateFinding] = []
+ tolerance = f"{'indoor' if indoor else 'outdoor'} tolerance {floating_m:.2f} m"
floating: list[tuple[AssetRow, float]] = []
for row in rows:
q = row.qualified
@@ -343,8 +357,9 @@ def _asset_findings(rows: list[AssetRow], *, p: Placement, floating_m: float, gr
if gap > floating_m:
floating.append((row, gap))
else:
- out.append(_f(Severity.WARN, f"{q} is unsupported: hovers {gap:.2f} m above {support} and touches nothing", target=q,
- hint=f"lower {q} by {gap:.2f} m onto {support}, or attach it to a neighbour; "
+ out.append(_f(Severity.WARN, f"{q} is unsupported: hovers {gap:.3f} m above {support} and touches nothing "
+ f"(within the {tolerance})", target=q,
+ hint=f"lower {q} by {gap:.3f} m onto {support}, or attach it to a neighbour; "
f"if it is meant to hang free set {words['free'].format(name=row.name)}",
kind="unsupported", gap_m=gap, **at))
many = len(floating) > p.floating_error_count
@@ -352,8 +367,10 @@ def _asset_findings(rows: list[AssetRow], *, p: Placement, floating_m: float, gr
q = row.qualified
support = _support_label(row, ground_y)
sev = Severity.ERROR if (many or gap > p.floating_error_m) else Severity.WARN
- out.append(_f(sev, f"{q} is floating {gap:.2f} m above {support} (touches nothing)", target=q,
- hint=f"lower {q} by {gap:.2f} m onto {support} — {words['seat']}; "
+ why = (f"; ERROR past {p.floating_error_m:.2f} m" if gap > p.floating_error_m
+ else f"; ERROR because {len(floating)} rows float, more than {p.floating_error_count}" if many else "")
+ out.append(_f(sev, f"{q} is floating {gap:.3f} m above {support} (touches nothing; {tolerance}{why})", target=q,
+ hint=f"lower {q} by {gap:.3f} m onto {support} — {words['seat']}; "
f"a deliberately airborne thing gets {words['free'].format(name=row.name)}",
kind="floating", gap_m=gap, zone=row.zone, bbox=row.bbox_data()))
return out
@@ -442,7 +459,7 @@ def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool =
floating_m = p.floating_indoor_m if indoor else p.floating_outdoor_m
words = placement_words(language)
rows = [r for r in t.assets if not r.exempt]
- raw = (_asset_findings(rows, p=p, floating_m=floating_m, ground_y=t.ground_y, words=words)
+ raw = (_asset_findings(rows, p=p, floating_m=floating_m, ground_y=t.ground_y, words=words, indoor=indoor)
+ _pair_findings(t.interpenetrations, p, {r.qualified: r for r in t.assets}))
free = _free_exempt_finding(t, p, words)
findings = _cap_per_kind(raw) + ([free] if free is not None else [])
diff --git a/harness/codeverse3d/spatial/tools.py b/harness/codeverse3d/spatial/tools.py
index ba24208b..c94fe357 100644
--- a/harness/codeverse3d/spatial/tools.py
+++ b/harness/codeverse3d/spatial/tools.py
@@ -154,6 +154,23 @@ def _build_failed(ctx: ToolContext, br: BuildResult, warns: list[str]) -> Observ
"error_file": error_file_display(br.error_file, ws.root), "error_line": br.error_line})
+def _env_unlit_only(br: BuildResult) -> str:
+ """The headline line for a scene build whose ONLY errors are ``probes.unlit`` (nothing lights the
+ scene), else ``""``. The round's build fails on that ERROR so its repair is handed the env module
+ (D112); a session's own ``build`` reports it above a BUILD OK instead — most sessions that build
+ while the env is still the placeholder (an asset session beside the env stage, a zone session
+ after a failed env stage) cannot write the env module, and a BUILD FAILED they cannot clear would
+ cost them their window."""
+ if br.ok or br.harness_failure:
+ return ""
+ errors = [f for g in br.gates for f in g.errors]
+ if not errors or any(f.data.get("kind") != "unlit" for f in errors):
+ return ""
+ f = errors[0]
+ return (f"SCENE UNLIT — scene_probe ERROR on {f.target}: {f.message}. The round's build fails on it until "
+ f"{f.target} lights the scene; everything else built.")
+
+
@tool("build", NoArgs, "Lint + build the code in src/ with the language runtime, export artifacts/object.glb and measure it. Call after every edit.", cost_hint="slow")
def build(ctx: ToolContext, args: NoArgs) -> Observation:
# ToolDef.call stamps Observation.duration_ms for every tool — no timing here
@@ -166,9 +183,12 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
if refused is not None:
return refused
br: BuildResult = rt.build(ws, timeout_s=get_settings().limits.build_timeout_s)
- if not br.ok:
+ unlit_line = _env_unlit_only(br) if language in SCENE_LANGUAGES else ""
+ if not br.ok and not unlit_line:
return _build_failed(ctx, br, lint_warns)
numbers: dict[str, Any] = {"stage": "build", "ok": br.ok, "duration_ms": br.duration_ms}
+ if unlit_line:
+ numbers["env_unlit"] = True
broken = False
if not br.glb_path and language in SCENE_LANGUAGES + GRAPHICS_LANGS:
# languages without a GLB deliverable: report the language's own artifacts
@@ -194,6 +214,8 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
"footprint_offset_m": m.footprint_offset_m, "parts": [p.name for p in m.parts]})
if m.extra.get("findings"):
numbers["findings"] = m.extra["findings"]
+ if unlit_line:
+ lines.insert(0, unlit_line)
if lint_warns:
lines.append("lint warnings:\n" + "\n".join(lint_warns[:_LINT_WARNS_SHOWN]))
census_warn = br.census.get("warnings") if isinstance(br.census, dict) else None
diff --git a/harness/codeverse3d/tracks/candidates.py b/harness/codeverse3d/tracks/candidates.py
index 30cd01a1..99843066 100644
--- a/harness/codeverse3d/tracks/candidates.py
+++ b/harness/codeverse3d/tracks/candidates.py
@@ -111,7 +111,9 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
died = [r for r in results if isinstance(r, Exception)]
raise RoundFailed("; ".join(f"{r.label}: {r.notes}" for r in records) or "every candidate failed",
transient=any(e.transient if isinstance(e, RoundFailed) else is_model_outage(e) for e in died),
- quota=any(isinstance(e, RoundFailed) and e.quota for e in died))
+ quota=any(isinstance(e, RoundFailed) and e.quota for e in died),
+ # D112: a hung candidate is retried by the round loop like a hung single session
+ stalled=any(isinstance(e, RoundFailed) and e.stalled for e in died))
best = rank_candidates(records)[0]
records[best].selected = True
usage = sum((r.usage for r in records), Usage())
diff --git a/harness/codeverse3d/tracks/generation.py b/harness/codeverse3d/tracks/generation.py
index dbb1a1e4..222b0253 100644
--- a/harness/codeverse3d/tracks/generation.py
+++ b/harness/codeverse3d/tracks/generation.py
@@ -315,6 +315,12 @@ class GenerationTask(BaseModel):
"credited with its files_hint only (AgentJob.shared_tree, D111 — the scene env stage beside the "
"asset single-shots)",
)
+ reserve_s: float = Field(
+ default=0.0,
+ description="seconds of the run's HARD clock this task's session leaves untouched for the round's "
+ "build, gates, render and judge (a refine / rebuild: RoundPolicy.judge_reserve_s, D112) — its "
+ "deadline ends that much before the budget does",
+ )
owns_entry: bool = Field(
default=False,
description="this task may write the language entry file even under edit_only (assembly / "
@@ -353,6 +359,11 @@ class GenerationResult(BaseModel):
description="the last session met the vendor's usage limit (AgentResult.quota): no retry gets "
"through until it resets",
)
+ stalled: bool = Field(
+ default=False,
+ description="the last session hung — killed as idle with nothing produced (AgentResult.stalled, "
+ "D112): one more session when the clock still holds a minimum window",
+ )
@classmethod
def from_error(cls, label: str, e: BaseException) -> GenerationResult:
@@ -549,7 +560,9 @@ def run_agent_task(
# wait, retry attempts and the CLI's activity grace inside the run's hard clock.
hard_deadline = None
if budget is not None and hasattr(budget, "timeout_s"):
- hard_deadline = time.monotonic() + budget.timeout_s(float("inf"), floor_s=0, soft=False)
+ # ``reserve_s`` (D112): a refine session cut by the run's own edge left its edits unbuilt and
+ # unjudged (iteration 5, r1_09: the retry's camera fix was committed, never scored)
+ hard_deadline = time.monotonic() + max(0.0, budget.timeout_s(float("inf"), floor_s=0, soft=False) - task.reserve_s)
turns_cap = agent_max_turns() # 0 = leave AgentJob's own default
# typed job context honoured by every CodingAgent: round → trajectory dir + ToolContext,
# language/track → spatial tool filtering, files_hint → the edit_only scope.
@@ -645,6 +658,7 @@ def run_agent_task(
turn_capped=acc.wrapped,
transient=bool(res.transient),
quota=bool(res.quota),
+ stalled=bool(res.stalled) and not changes,
)
diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.py
index f376a4e3..b2f3e0c6 100644
--- a/harness/codeverse3d/tracks/lifecycle.py
+++ b/harness/codeverse3d/tracks/lifecycle.py
@@ -295,7 +295,8 @@ class BaseTrack:
refine-from-best, no whole-artifact rewrite after a regression)."""
index = last.index + 1
if last.build is None or not last.build.ok:
- return [self._rebuild_task(ctx, last, index)], ["rebuild: previous round did not build"]
+ rebuild = self._rebuild_task(ctx, last, index).model_copy(update={"reserve_s": ctx.policy.judge_reserve_s})
+ return [rebuild], ["rebuild: previous round did not build"]
tasks = build_refine_instructions(last.judgment, last.gates, failed_acceptance(ctx, last.judgment), ctx.plan,
file_for_target=self.refine_file_for_target(ctx),
max_tasks=ctx.policy.max_refine_tasks,
@@ -304,7 +305,8 @@ class BaseTrack:
return [], []
groups, parallel = plan_refine_groups(tasks, allow_fanout=self.allow_refine_fanout,
parallel_min_tasks=ctx.policy.parallel_min_tasks)
- gen_tasks = [self._refine_task(ctx, g, last, index, parallel=parallel) for g in groups]
+ gen_tasks = [self._refine_task(ctx, g, last, index, parallel=parallel).model_copy(
+ update={"reserve_s": ctx.policy.judge_reserve_s}) for g in groups]
ctx.events.emit("refine.planned", round=index, n_tasks=len(tasks), n_groups=len(groups), parallel=parallel,
targets=[g.targets for g in groups])
return gen_tasks, [t.line() for t in tasks]
@@ -360,7 +362,7 @@ class BaseTrack:
except BudgetExceeded as e:
events.emit("budget.exceeded", reason=e.reason)
stop, error = RunStatus.BUDGET, e.reason
- self._salvage_baseline(ctx, rounds)
+ self._salvage(ctx, rounds)
except Exception as e: # noqa: BLE001 — persist a FAILED record, then fail loud
error = f"{type(e).__name__}: {e}"
events.emit("run.failed", error=error, traceback=traceback.format_exc()[-3000:])
@@ -634,6 +636,13 @@ class BaseTrack:
# no gate error, no failed must-item, no judge plan: nothing to ask for. When
# that is only because the judge never scored the round, say so.
return _stop(RunStatus.JUDGE_UNAVAILABLE if _unjudged(last) else RunStatus.NO_REFINE_TASKS)
+ if last is not None and not ctx.policy.can_open(ctx.budget, single_shot=ctx.single_shot):
+ # D112: a refine round (or its transport / stall retry) that cannot also be built and
+ # judged before the clock stops is money for edits nobody scores (iteration 5, r1_09:
+ # the retry launched with 15 min left, was cut at the budget edge, never judged)
+ ctx.events.emit("round.skipped_budget", round=index, left_s=round(ctx.budget.left_s(), 1),
+ need_s=ctx.policy.need_s(single_shot=ctx.single_shot))
+ return _stop(RunStatus.BUDGET)
ctx.state.save(ctx.ws)
try:
if index == 0 and tasks and ctx.policy.n_candidates > 1:
@@ -653,7 +662,7 @@ class BaseTrack:
if index == 0:
raise
return _stop(RunStatus.AGENT_QUOTA)
- if index not in transport_retried and e.transient:
+ if index not in transport_retried and (e.transient or e.stalled):
# A 503 storm / dropped socket / overloaded provider is not an agent
# verdict — the session never really happened. Re-run the SAME
# round once, baseline included (rc=247 alone killed three whole
@@ -661,9 +670,13 @@ class BaseTrack:
# ``continue`` re-enters through the loop head, so the budget and
# round ceilings still guard the retry. Typed since 2026-09-22
# (RoundFailed.transient): a session that merely timed out on its own
- # work, or a CLI that crashed with no provider error, is not retried.
+ # work, or a CLI that crashed with no provider error, is not retried. A session
+ # the watchdog found HUNG (``stalled``: idle, nothing produced) is retried by the
+ # same rule, whatever the vendor's log says (D112); the window check at the loop
+ # head keeps the retry from launching when it could not also be judged.
transport_retried.add(index)
- ctx.events.emit("round.transport_retry", round=index, detail=str(e)[:500])
+ ctx.events.emit("round.transport_retry", round=index, stalled=e.stalled and not e.transient,
+ detail=str(e)[:500])
continue
if index == 0:
raise
@@ -674,28 +687,45 @@ class BaseTrack:
rounds.append(rec)
self._save_budget(ctx)
- def _salvage_baseline(self, ctx: RunContext, rounds: list[RoundRecord]) -> None:
- """A stage tripped the budget BEFORE round 0 ever ran (the greenhouse scene:
- the zone fan-out crossed the ceiling, so the run finished with no build, no
- render, no judge and no score at all).
-
- The workspace still holds buildable code, and build → render → judge is a
- fraction of a generation session, so grant an explicit one-off grace and
- deliver ONE no-generation round. Any failure here is swallowed: the run is
- already stopping on budget."""
- if rounds or ctx.plan is None:
- return # nothing was built yet (the PLAN itself blew the budget) → nothing to salvage
+ def _salvage(self, ctx: RunContext, rounds: list[RoundRecord]) -> None:
+ """The budget stopped the run with work nobody has judged: give ONE bounded grace and run
+ a no-generation round (build → gates → render → judge) on what is in the workspace.
+
+ * Before round 0 (the greenhouse scene: the zone fan-out crossed the ceiling, so the run
+ finished with no build, no render, no judge and no score at all): the baseline.
+ * After it (D112): a refine round whose sessions changed files before the clock stopped
+ them — a session cut at the budget edge, or a round stopped after its generate step.
+ Iteration 5, r1_09: the transport retry's edits (the camera that capped the run at 0.60)
+ were committed and thrown away; finalise rebuilt round 0. A refine killed by its OWN
+ hard limit was always built and judged (iteration 4, the same run: 0.817).
+
+ Any failure here is swallowed: the run is already stopping on budget."""
+ if ctx.plan is None:
+ return # the PLAN itself blew the budget → nothing to salvage
+ last = rounds[-1] if rounds else None
+ edits: list[str] = []
+ if last is not None:
+ if not last.commit:
+ return
+ edits = [f.path for f in ctx.ws.changed_files(last.commit) if f.path.split("/", 1)[0] in ("src", "public")]
+ if not edits:
+ return # the stop came before anything changed: the last round IS the work
grace_min = max(5.0, ctx.spec.budget.max_minutes * 0.15)
ctx.budget.grant_grace(minutes=grace_min)
- ctx.events.emit("budget.salvage", reason="no round completed before the clock stop",
- grace_minutes=round(grace_min, 1))
+ reason = ("no round completed before the clock stop" if last is None
+ else f"the clock stopped a refine round after it changed {len(edits)} file(s)")
+ ctx.events.emit("budget.salvage", reason=reason, grace_minutes=round(grace_min, 1), files=edits[:20])
+ index = len(rounds)
try:
- if not self.prepare_salvage(ctx):
+ if last is None and not self.prepare_salvage(ctx):
ctx.events.emit("budget.salvage_skipped", reason="nothing buildable to salvage")
return
- rec = run_round(ctx, index=0, kind="baseline", tasks=[], pipeline=self.make_pipeline(), instructions=[],
- previous=None, files_hint=ctx.runtime.expected_files(ctx.plan),
- extra_notes=["salvaged: the budget stopped the run before round 0", *self.round_extra_notes(ctx)])
+ note = ("salvaged: the budget stopped the run before round 0" if last is None
+ else "salvaged: the budget stopped this round's sessions; their edits are judged as they stand")
+ rec = run_round(ctx, index=index, kind="baseline" if last is None else "refine", tasks=[],
+ pipeline=self.make_pipeline(), instructions=[], previous=previous_verdict(rounds, index),
+ findings=last.gates if last is not None else (), files_hint=ctx.runtime.expected_files(ctx.plan),
+ extra_notes=[note, *self.round_extra_notes(ctx)])
except Exception as e: # noqa: BLE001 — the run is already stopping; never mask the budget stop
log.warning("salvage round failed: %s", e)
ctx.events.emit("budget.salvage_failed", error=f"{type(e).__name__}: {e}")
diff --git a/harness/codeverse3d/tracks/scene.py b/harness/codeverse3d/tracks/scene.py
index 4e4be2d3..73421bbc 100644
--- a/harness/codeverse3d/tracks/scene.py
+++ b/harness/codeverse3d/tracks/scene.py
@@ -312,15 +312,16 @@ class SceneTrack(BaseTrack):
try:
task = skills_hook.with_inlined_skill(gen, [task])[0]
res = generate_for(gen, task)
- if res.transient and not res.ok and ctx.budget.ok():
+ if (res.transient or res.stalled) and not res.ok and ctx.policy.can_open(ctx.budget, single_shot=gen.single_shot):
# ONE transport retry, the round loop's rule (lifecycle: a 503 storm / dropped
- # socket is not a verdict on the work — the session never really happened):
- # the same task again under the ``.a2`` label the CLI's own second session
- # wears, so the ledger and the trajectory dir tell the two apart. Typed:
- # ``GenerationResult.transient`` only — a quota wall or a session that merely
- # timed out is not retried. Only while the budget still allows; the clock
- # check inside ``generate`` stops a retry that would overrun it.
- ctx.events.emit("stage.transport_retry", stage=stage, label=task.label, detail=res.notes[:500])
+ # socket / a session that HUNG is not a verdict on the work — the session never
+ # really happened): the same task again under the ``.a2`` label the CLI's own second
+ # session wears, so the ledger and the trajectory dir tell the two apart. Typed:
+ # ``GenerationResult.transient`` / ``.stalled`` only — a quota wall or a session that
+ # worked to its hard limit is not retried — and only when the clock still holds a
+ # minimum window plus the judge reserve (``RoundPolicy.can_open``, D112).
+ ctx.events.emit("stage.transport_retry", stage=stage, label=task.label, stalled=res.stalled and not res.transient,
+ detail=res.notes[:500])
res = generate_for(gen, task.model_copy(update={"label": f"{task.label}.a2"}))
return res
finally:
@@ -371,25 +372,62 @@ class SceneTrack(BaseTrack):
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."""
+
+ CHECKED (D112): the written module counts only once the runtime's env check passes
+ (``SceneRuntime.check_env``: its lint, a build with nothing beside it, something that lights
+ it); a failure gets ONE repair single-shot with the check's words and the file fed back (the
+ asset ladder's single-shot + repair). Both prompts carry the ``src/lib/`` interface
+ (``SceneRuntime.lib_interface``) — names and parameter lists, read off the files. Iteration 5
+ (2026-10-16): 7 of 21 unchecked recoveries were broken or unlit (a SyntaxError, a non-existent
+ ``gravel`` export, a ``roughness=`` keyword no function takes) and reached round 0 as an
+ assembly without env. A module that still fails is replaced by what was there before (the
+ placeholder: zones import its interface), and the stage reports it failed.
+
+ Under :func:`~codeverse3d.agents.cli_common.exclusive_workspace` (D112): an escalated asset
+ session may hold the workspace while this runs, and a harness commit inside its window was
+ reverted by its scope check (iteration 5, scene_blender r1_10: the recovered env erased)."""
+ from codeverse3d.agents.cli_common import exclusive_workspace
+
gen = ctx if ctx.single_shot else (single_shot_ctx(ctx) or ctx)
rel = env_file(ctx)
+ path = ctx.ws.root / rel
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)
+ with exclusive_workspace(ctx.ws):
+ before = path.read_text(errors="replace") if path.is_file() else None
+ lib = ctx.runtime.lib_interface(ctx.ws)
+ ok, error, previous, notes = False, "", "", ""
+ for attempt in (1, 2): # the single-shot, then ONE repair with the check's words fed back
+ t0 = time.time()
+ try:
+ task = self._env_task(gen, lib_interface=lib, env_check_error=error, env_previous=previous)
+ label = f"{task.label}.recover" + (".repair" if attempt > 1 else "")
+ res = generate_for(gen, task.model_copy(update={"label": label}))
+ except Exception as e: # noqa: BLE001 — BudgetExceeded included: the boundary check after the stage stops the run
+ notes = f"recover: {type(e).__name__}: {e}"
+ break
+ if not (res.ok and (rel in {c.path for c in res.files_changed} or _touched(path, t0))):
+ notes = f"recovered single-shot wrote nothing: {res.notes}"
+ break
+ error = ctx.runtime.check_env(ctx.ws)
+ ctx.events.emit("env.checked", attempt=attempt, ok=not error, error=error[:500])
+ if not error:
+ ok, notes = True, f"recovered single-shot{' + repair' if attempt > 1 else ''}: {res.notes}"
+ break
+ notes = f"recovered env failed its check: {error}"
+ previous = path.read_text(errors="replace") if path.is_file() else ""
+ if not ctx.budget.ok():
+ break
+ if not ok and before is not None and path.is_file() and path.read_text(errors="replace") != before:
+ path.write_text(before) # a broken env breaks every zone that imports it; the placeholder does not
+ ctx.ws.commit("env.recover")
+ out = {"ok": ok, "files": [rel] if ok else [], "notes": notes[:500]}
+ ctx.events.emit("env.recovered", ok=ok, file=rel)
return out
- def _env_task(self, ctx: RunContext) -> GenerationTask:
- prompt = render(scene_templates(ctx.language).env, **self._ctx(ctx))
+ def _env_task(self, ctx: RunContext, **recovery: str) -> GenerationTask:
+ """``recovery``: the recovery's extra facts (``lib_interface``, ``env_check_error``,
+ ``env_previous`` — :meth:`_recover_env`); the session's own brief has none."""
+ prompt = render(scene_templates(ctx.language).env, **self._ctx(ctx, **recovery))
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",
diff --git a/harness/codeverse3d/tracks/static_object.py b/harness/codeverse3d/tracks/static_object.py
index a1154f81..48f516ea 100644
--- a/harness/codeverse3d/tracks/static_object.py
+++ b/harness/codeverse3d/tracks/static_object.py
@@ -204,10 +204,6 @@ class StaticObjectTrack(BaseTrack):
)
-#: what an object round still needs once its session ends — build, gates, renders, the judge.
-#: Measured 0.7 min in both baseline-first smoke runs (2026-10-15, machine load ~23); 3 min
-#: leaves room for a slow render or one quick repair build.
-OBJECT_ROUND_RESERVE_S = 180.0
#: the shortest refine window opened: below it the hard run clock decides anyway
REFINE_MIN_WINDOW_S = 120.0
@@ -215,14 +211,16 @@ REFINE_MIN_WINDOW_S = 120.0
def object_session_window_s(ctx: RunContext) -> int:
"""A refine session's window: the agent default, clipped so that the session — which the
watchdog lets run ``HARD_GRACE_S`` past its window while it is still working — ends
- :data:`OBJECT_ROUND_RESERVE_S` before the run's HARD ceiling.
+ ``RoundPolicy.judge_reserve_s`` before the run's HARD ceiling (the round's build, gates, renders and
+ judge: 0.7 min measured for an object, 2026-10-15; one reserve for every track since D112 — it was
+ ``OBJECT_ROUND_RESERVE_S``, 180 s, beside the refine task's own ``GenerationTask.reserve_s``).
WHY. With no window of its own the session ran to the run's deadline: the baseline-first
smoke's blender refine (started at 25.8 min, 36 min allowed) was killed by the run clock at
60.0 min after $4.63 of work, and the round was dropped unbuilt and unjudged — as were all
three refines of iteration 0's dining chair. Ended earlier, its edits are built and judged
and the picker chooses between the rounds."""
- left = (ctx.budget.hard_minutes - ctx.budget.elapsed_minutes()) * 60.0 - OBJECT_ROUND_RESERVE_S - HARD_GRACE_S
+ left = ctx.budget.left_s() - ctx.policy.judge_reserve_s - HARD_GRACE_S
return int(max(REFINE_MIN_WINDOW_S, min(float(ctx.settings.limits.agent_timeout_s), left)))
diff --git a/harness/codeverse3d/tracks/steps.py b/harness/codeverse3d/tracks/steps.py
index 7a2d6715..51402732 100644
--- a/harness/codeverse3d/tracks/steps.py
+++ b/harness/codeverse3d/tracks/steps.py
@@ -82,16 +82,22 @@ class RoundFailed(RuntimeError):
substring-matched the joined notes, with a vocabulary that had drifted from the backends'
(a codex usage limit reached the loop only because the loop's list said "usage limit")."""
- def __init__(self, message: str, *, transient: bool = False, quota: bool = False) -> None:
+ def __init__(self, message: str, *, transient: bool = False, quota: bool = False, stalled: bool = False) -> None:
super().__init__(message)
self.transient = transient
self.quota = quota
+ #: a session hung (``GenerationResult.stalled``, D112): retried like a transport death
+ self.stalled = stalled
@classmethod
def of(cls, results: Sequence[GenerationResult], default: str) -> RoundFailed:
- """The round's failure: every task's notes, and the typed flags of any of them."""
+ """The round's failure: every task's notes, and the typed flags of any of them — except
+ ``stalled``, which needs EVERY session to have hung or died of transport (D112): a split
+ round whose other session worked to its hard limit and wrote nothing is that session's
+ verdict, and the round loop retries a round whole."""
return cls("; ".join(f"{r.label}: {r.notes}" for r in results) or default,
- transient=any(r.transient for r in results), quota=any(r.quota for r in results))
+ transient=any(r.transient for r in results), quota=any(r.quota for r in results),
+ stalled=any(r.stalled for r in results) and all(r.stalled or r.transient for r in results))
def round_record_path(ctx: RunContext, index: int) -> Path:
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 134935d5..b53a2acd 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -486,8 +486,18 @@ blender_glb heroes get a sub-workspace with the static planner's parts + asset_v
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` — `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
+only, watched for activity on its own file and — **D112** — on the steps agy records under its session HOME) 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**), CHECKED (**D112**): it counts only once `SceneRuntime.check_env` passes
+(the env module alone lints, builds and lights what it builds), a failure gets ONE repair single-shot with the
+check's words and the file fed back, both prompts carry `SceneRuntime.lib_interface` (src/lib names + parameter
+lists; a const-bound arrow function counts as a function), a module that still fails is replaced by the
+placeholder it overwrote, and the whole recovery holds the
+workspace session lock (`cli_common.exclusive_workspace`) so it never commits inside an escalated asset session's
+window (whose scope check would revert it). An env that lights nothing (`probes.unlit`: no lamp and no world /
+no light, background or environment map) is a `scene_probe` ERROR, so the ROUND's build fails and its repair is
+handed the env; a session's own MCP `build` states it on a `SCENE UNLIT` line above BUILD OK when it is the only
+error (an asset or zone session building beside the placeholder env cannot write the env module); `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
@@ -517,7 +527,7 @@ plateau, regression or diminishing-returns stop, no rewrite or surface-detail ro
fan out when the track allows it (scene: zones/assets/env) AND ≥ 2 file-disjoint groups AND every task maps to
files; the object tracks never fan out (allow_refine_fanout = False, D110): ONE session edits the whole
object in place, told to make targeted edits, never whole-file rewrites — its window ends
- OBJECT_ROUND_RESERVE_S (3 min) + the watchdog's grace before the run's hard ceiling, so the round is still
+ RoundPolicy.judge_reserve_s (4 min; D112, was 3 min) + the watchdog's grace before the run's hard ceiling, so the round is still
built and judged (static_object.object_session_window_s); a single-shot refine is fenced (edit_only) to
the files its tasks name, the only ones it is shown; graphics is one program
generate (no HARNESS turn cap by default — claude-code runs under AgentJob.max_turns=60 (+6-turn wrap-up),
@@ -533,8 +543,16 @@ plateau, regression or diminishing-returns stop, no rewrite or surface-detail ro
that raises mid-way still reports what it burned (rounds/aborted_rNN.json + record.extra["aborted_rounds"])
a round whose every task failed raises RoundFailed, TYPED (2026-09-22 — the loop never reads its message):
.quota (a backend saw the vendor's usage limit) → agent_quota; .transient (a session died of a provider
- failure — AgentResult.transient, or a ModelError outage) → the SAME round re-runs once, baseline included;
- neither → no_change (a refine round) / the run fails (the baseline)
+ failure — AgentResult.transient, or a ModelError outage) or .stalled (D112: the watchdog found a session hung —
+ idle past its window, nothing produced — whatever the vendor's log says; a split round only when EVERY session
+ hung or died of transport, and best-of-N candidates carry it too) → the SAME round re-runs once,
+ baseline included; neither → no_change (a refine round) / the run fails (the baseline)
+ D112: a refine round (and its retry) launches only while RoundPolicy.can_open — judge_reserve_s, plus
+ min_session_s for an agent session (a single-shot call needs the reserve only), left on the hard clock (else
+ round.skipped_budget → budget; round 0's retry is not gated); refine / rebuild sessions end judge_reserve_s before
+ the budget (GenerationTask.reserve_s); a budget stop after refine sessions changed src/ / public/ gets ONE bounded
+ grace and a no-generation round that builds, renders and judges those edits (BaseTrack._salvage, like the
+ baseline salvage before round 0)
stop reasons: max_rounds | budget (the wall clock — BudgetGuard / max_minutes) | agent_quota | no_change (a refine
round's sessions changed nothing) | no_refine_tasks | judge_unavailable | failed
(a record from before 2026-09-22 may say passed / plateau: it loads as `stopped`)
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 40b1a71d..b560f2dd 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -227,6 +227,9 @@ res.turns # claude-code num_turns · codex turn.completed count
res.files_changed (git-derived, attributed per session), res.usage, res.transcript_path, res.tool_calls, res.errors
res.transient # a provider failure a retry may get through (5xx / overloaded / 429 / dropped connection)
res.quota # Δ 2026-09-22 the vendor's usage limit is spent — never also transient
+res.stalled # Δ D112 the watchdog killed it IDLE (no output / write / recorded step for IDLE_GRACE_S past
+ # its window) and it answered nothing: a hang — never transient; retried by the clock
+ # (RoundPolicy.can_open), never by the vendor's log (classify_end has no provider_retried)
res.provider_wait_s # Δ seconds of duration_s lost to provider errors (cli_common.provider_wait; codex: 0.0)
# Δ 2026-09-22 the prompt reaches EVERY CLI on stdin (cli_common.invoke; no -p / --print / positional text,
# codex "-"), byte for byte; the >100 kB task_prompt.md stub is gone. The transcript's invoke row keeps
@@ -251,7 +254,9 @@ agent sessions on one workspace are serialised, so there is no sibling filter),
`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
+watchdog polls only those files (`cli_common.activity_paths(s, steps=())`; **Δ D112** plus `steps`, where the CLI
+records each step it takes — agy passes its session HOME's `backends.AGY_STEP_DIRS` (brain/, conversations/) through
+`invoke(..., activity=)` for every agy session, shared_tree or not); 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
@@ -305,6 +310,14 @@ rt.probe(ws, *, timeout_s=60.0) -> SceneProbeResult # scene_probe gate + cens
rt.render_scene(ws, out_dir, *, cameras=None, orbit=True, times=(0.0, 1.5), width=1024, height=576, sheet=True) -> RenderSet
rt.env_file: str # Δ 2026-10-14 (D105) src/env.js / src/env.py — the env stage's one file,
# declared on languages/base.SceneRuntime; tracks.scene.env_file(ctx) reads it (tracks.scene.ENV_FILES is the typed fallback)
+rt.lib_interface(ws) -> str # Δ D112 src/lib/ as facts: one line per module, exported names +
+ # parameter lists read off the files (_js_lint.export_signatures: `export function` and a const bound to an
+ # arrow / function expression; ast for bpy) — the env recovery's single-shot prompt
+rt.check_env(ws) -> str # Δ D112 "" = the env module alone lints clean, builds with nothing
+ # beside it (scene_threejs: src/_c3v_env_probe.js in probe_scene.mjs; scene_blender: run_wrapper(entry=
+ # ENV_CHECK_REL, zones={})) and lights what it builds (spatial.probes.unlit); else the failure, quoted (bpy: a
+ # raise inside a src/lib helper leads with the env's own calling line, scene_blender.env_frame). A check the
+ # harness cannot run returns "" (never a verdict on the module)
# Δ 2026-09-24 (D102) spatial.probes.run_probe(ws, *, compile=False, timeout_s=None, glb: Path | None = None, facts=None):
# 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;
@@ -586,7 +599,12 @@ from codeverse3d.orchestrator import RoundPolicy, build_refine_instructions, com
# Δ 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
+ n_candidates=1, judge_samples=1, judge_reserve_s=240.0, min_session_s=180.0)
+ # Δ D112 .can_open(budget, *, single_shot=False) = budget.left_s() >= .need_s(single_shot=...) (judge_reserve_s,
+ # + min_session_s unless the generation is single-shot): no refine round, a refine round's transport / stall
+ # retry or a stage retry launches without it (round.skipped_budget → BUDGET; round 0's retry is not gated —
+ # it has no round to fall back on); refine / rebuild tasks carry
+ # GenerationTask.reserve_s = judge_reserve_s (their session's hard deadline ends that much before the budget) # 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
# it; only the clock (BudgetGuard) or a hard failure ends it early. Gone with the judgement stops: StopPolicy /
# StopDecision, pick_best_round, judge_sigma, best_score, last_gain, REWRITE_KIND / DETAIL_KIND /
@@ -594,7 +612,7 @@ RoundPolicy(max_rounds=4, max_refine_tasks=6, max_instructions_per_task=6, paral
# min_delta, target, pairwise_*, judge_model, regression_sigma, marginal_*, detail_*.
from codeverse3d.orchestrator import BudgetGuard, BudgetSnapshot
BudgetGuard(budget, start_time=None, *, soft_fraction=1.0) # THE CLOCK, nothing else (Δ 2026-09-22)
- .check() / .ok() / .elapsed_minutes() / .timeout_s(want_s, *, floor_s, soft) / .soft_exceeded()
+ .check() / .ok() / .elapsed_minutes() / .timeout_s(want_s, *, floor_s, soft) / .soft_exceeded() / .left_s(*, soft=False)
.grant_grace(minutes=) / .snapshot() -> BudgetSnapshot{active_s} / .restore(snap) / .summary() -> {elapsed_min,
max_minutes}
# Δ 2026-09-22: charge / add / mark / stage_summary / spent / billed_usd / by_stage and usage_delta are gone —
@@ -645,9 +663,14 @@ generate(ws, *, agent_id, task, ..., budget=BudgetGuard) -> GenerationResult
# Δ 2026-09-22 GenerationResult.transient / .quota carry the backend's typed class; a call that RAISED is
# GenerationResult.from_error(label, e) — transient = tracks.generation.is_model_outage(e) (ModelError
# retryable or 429/5xx; moved from scene_assets, the one exception classifier)
-from codeverse3d.tracks.steps import RoundFailed # RoundFailed(message, *, transient=False, quota=False);
- # RoundFailed.of(results, default) — the round loop reads .quota (→ agent_quota) and .transient (→ re-run
- # the round once), never the message (looks_transport / looks_quota deleted)
+from codeverse3d.tracks.steps import RoundFailed # RoundFailed(message, *, transient=False, quota=False, stalled=False);
+ # RoundFailed.of(results, default) — the round loop reads .quota (→ agent_quota) and .transient / Δ D112 .stalled
+ # (.of: stalled only when EVERY result hung or died of transport; run_best_of_n's failure carries it too)
+ # (→ re-run the round once, when RoundPolicy.can_open), never the message (looks_transport / looks_quota deleted)
+ # Δ D112 GenerationResult.stalled (AgentResult.stalled, nothing changed); GenerationTask.reserve_s.
+ # BaseTrack._salvage(ctx, rounds) (was _salvage_baseline): on a budget stop, ONE grace (max(5, 15 % of the
+ # budget) min) and a no-generation round — the baseline before round 0, or (Δ D112) the refine edits the clock
+ # stopped (src/ / public/ changed since the last round's commit)
tracks.common.generate_for(ctx: RunContext, task: GenerationTask) -> GenerationResult
# THE call every stage makes (env, zones, rounds, repairs, asset ladder, judged fix): generate()
# with everything ctx knows; Δ D103 no storm fallback (D68's single-shot retry, GenerationResult.storm and
diff --git a/harness/tests/agents/test_agy_activity.py b/harness/tests/agents/test_agy_activity.py
new file mode 100644
index 00000000..70273f46
--- /dev/null
+++ b/harness/tests/agents/test_agy_activity.py
@@ -0,0 +1,108 @@
+"""D112: an agy session that is taking steps is never idle-killed; one that has stalled still is.
+
+Argon loop iteration 5 (2026-10-16): agy prints nothing until it exits, and D111 narrowed a
+``shared_tree`` session's activity watch to its own file — so a session READING was "idle" from
+second 0 and its soft window was a hard kill: 22 of 26 env sessions died at 420-423 s with nothing
+written, and 4 of 21 refines at 901 s. agy records every step under its per-session HOME
+(``AGY_STEP_DIRS``); those writes are the session's activity, for shared_tree and plain sessions.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse3d.agents import cli_common
+from codeverse3d.agents.backends import AGY_STEP_DIRS, AntigravityAgent
+from codeverse3d.config import get_settings
+from codeverse3d.contracts.agent import AgentJob
+from codeverse3d.workspace import Workspace
+
+#: a fake agy that never prints and never writes the workspace; with STEPS=1 it records a step
+#: under its own HOME's brain/ every 0.1 s, the way agy writes brain/<id>/.system_generated/steps/<n>/
+FAKE_AGY_STEPS = r'''
+sys.stdin.read()
+brain = os.path.join(os.environ["HOME"], ".gemini", "antigravity-cli", "brain", "c1", ".system_generated", "steps")
+for n in range(600):
+ if os.environ.get("STEPS") == "1":
+ os.makedirs(os.path.join(brain, str(n)), exist_ok=True)
+ open(os.path.join(brain, str(n), "output.txt"), "w").write("read a file")
+ time.sleep(0.1)
+'''
+
+
[email protected](autouse=True)
+def _fast_clocks(monkeypatch, tmp_path, request):
+ monkeypatch.setattr(get_settings(), "gemini_api_keys", [f"key-{request.node.name}"])
+ monkeypatch.setattr(get_settings(), "cache_dir", tmp_path / "cache")
+ monkeypatch.setattr(cli_common, "IDLE_GRACE_S", 1.0)
+ monkeypatch.setattr(cli_common, "HARD_GRACE_S", 3.0)
+ monkeypatch.setattr(cli_common, "SCAN_S", 0.1)
+
+
+def _env_tree(ws: Workspace) -> None:
+ (ws.root / "src" / "env.js").write_text("// placeholder\n")
+ ws.commit("skeleton")
+
+
[email protected]("shared_tree", [True, False])
+def test_a_session_taking_steps_runs_to_its_hard_limit(tmp_ws: Workspace, fake_bin, monkeypatch, shared_tree):
+ _env_tree(tmp_ws)
+ monkeypatch.setenv("STEPS", "1")
+ a = AntigravityAgent("gemini-4-argon", binary=fake_bin("agy", FAKE_AGY_STEPS))
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="p", label="env", timeout_s=1, spatial_tools=False,
+ files_hint=["src/env.js"], shared_tree=shared_tree))
+ result = (tmp_ws.trajectory_dir("env", 0) / "result.json").read_text()
+ assert '"killed_reason": "hard_timeout"' in result, result
+ assert res.duration_s >= 3.5 # soft 1 s + hard grace 3 s: past the soft window, and bounded
+
+
[email protected]("shared_tree", [True, False])
+def test_a_stalled_session_is_still_killed_at_its_soft_window(tmp_ws: Workspace, fake_bin, monkeypatch, shared_tree):
+ _env_tree(tmp_ws)
+ monkeypatch.setenv("STEPS", "0")
+ a = AntigravityAgent("gemini-4-argon", binary=fake_bin("agy", FAKE_AGY_STEPS))
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="p", label="env", timeout_s=1, spatial_tools=False,
+ files_hint=["src/env.js"], shared_tree=shared_tree))
+ result = (tmp_ws.trajectory_dir("env", 0) / "result.json").read_text()
+ assert '"killed_reason": "idle"' in result, result
+ assert res.duration_s < 3.5
+
+
+def test_the_step_dirs_are_named_not_walked_into():
+ """The watchdog's walk skips ``.gemini`` — the step dirs must be passed themselves."""
+ assert all(d.parts[0] == ".gemini" for d in AGY_STEP_DIRS)
+ assert ".gemini" in cli_common._SKIP_DIRS
+
+
+#: a fake agy that logs one retried 503 at t=0 (or not) and then hangs: no output, no step, no write
+FAKE_AGY_HANG = r'''
+sys.stdin.read()
+args = sys.argv[1:]
+if os.environ.get("LOGGED_503") == "1":
+ from datetime import datetime
+ with open(args[args.index("--log-file") + 1], "w") as f:
+ f.write(datetime.now().strftime("I%m%d %H:%M:%S.%f") + " 284 run.go:395] Run: attempt 1 failed "
+ "(Error 503, Message: busy, Status: UNAVAILABLE, Details: []), retrying in 4s\n")
+time.sleep(60)
+'''
+
+
[email protected]("logged_503", ["0", "1"])
+def test_a_hung_session_ends_the_same_whatever_agys_log_holds(tmp_ws: Workspace, fake_bin, monkeypatch, logged_503):
+ """D112 (fix 8): iteration 5's identical 901 s / zero-file kills were transient (retried) when agy had
+ logged one 4 s 503 and not otherwise. Now: stalled, never transient (the key is not penalised)."""
+ _env_tree(tmp_ws)
+ monkeypatch.setenv("LOGGED_503", logged_503)
+ a = AntigravityAgent("gemini-4-argon", binary=fake_bin("agy", FAKE_AGY_HANG))
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="p", label="refine", timeout_s=1, spatial_tools=False))
+ assert (res.exit_reason, res.transient, res.stalled, res.files_changed) == ("timeout", False, True, [])
+
+
+def test_the_end_rule_reads_the_watchdogs_verdict_not_the_vendors_log():
+ from codeverse3d.agents.cli_common import CompletedProc, classify_end
+
+ idle = CompletedProc(rc=-9, stdout="", stderr="", duration_s=901, timed_out=True, killed_reason="idle")
+ hard = CompletedProc(rc=-9, stdout="", stderr="", duration_s=1200, timed_out=True, killed_reason="hard_timeout")
+ assert classify_end(idle, ok=False, text="") == cli_common.SessionEnd("timeout", stalled=True)
+ assert classify_end(idle, ok=False, text="half an answer") == cli_common.SessionEnd("timeout")
+ assert classify_end(hard, ok=False, text="") == cli_common.SessionEnd("timeout")
diff --git a/harness/tests/agents/test_claude_code.py b/harness/tests/agents/test_claude_code.py
index 7500564b..4f03b854 100644
--- a/harness/tests/agents/test_claude_code.py
+++ b/harness/tests/agents/test_claude_code.py
@@ -183,7 +183,8 @@ def test_a_killed_session_is_booked_from_its_messages_and_its_retries_are_provid
monkeypatch.setattr("codeverse3d.agents.cli_common.IDLE_GRACE_S", 1.0)
a = ClaudeCodeAgent("sonnet", binary=fake_bin("claude", FAKE_KILLED_CLAUDE))
res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="k", timeout_s=1, spatial_tools=False))
- assert not res.ok and res.exit_reason == "timeout" and res.transient and not res.quota
+ # D112: a hung session is ``stalled`` (retried by the clock), never ``transient`` because of its retries
+ assert not res.ok and res.exit_reason == "timeout" and res.stalled and not res.transient and not res.quota
u = res.usage
assert (u.input_tokens, u.cached_tokens, u.output_tokens, u.model) == (2 + 19190 + 20354, 20354, 5, "claude-sonnet-5-5")
assert u.cost_usd == pytest.approx(estimate_cost("anthropic", "claude-sonnet-5-5", u)
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.py
index 16aa420e..6f58b1fe 100644
--- a/harness/tests/orchestrator_tracks/fakes.py
+++ b/harness/tests/orchestrator_tracks/fakes.py
@@ -129,6 +129,17 @@ class FakeRuntime:
out.append(u)
return out
+ #: what the fake env check finds in an env module, and what it reports (D112)
+ ENV_BROKEN = "ENV_BROKEN"
+
+ def lib_interface(self, ws: Workspace) -> str:
+ return "lib/fake.js: makeFake(opts = {})"
+
+ def check_env(self, ws: Workspace) -> str:
+ env = ws.root / self.env_file
+ text = env.read_text() if env.is_file() else ""
+ return f"{self.env_file}: {self.ENV_BROKEN} found" if self.ENV_BROKEN in text else ""
+
def _src_text(self, ws: Workspace) -> str:
return "\n".join(p.read_text() for p in sorted(ws.src.rglob("*")) if p.is_file())
diff --git a/harness/tests/orchestrator_tracks/test_baseline_first.py b/harness/tests/orchestrator_tracks/test_baseline_first.py
index 91b556f3..1def652a 100644
--- a/harness/tests/orchestrator_tracks/test_baseline_first.py
+++ b/harness/tests/orchestrator_tracks/test_baseline_first.py
@@ -125,17 +125,18 @@ def test_refine_session_ends_before_the_run_clock_so_the_round_is_judged(tmp_pat
watchdog let the busy session run its 5-min grace on top, the run clock killed it at 60.0 min and
the round was dropped unbuilt and unjudged ($4.63). The window now ends reserve + grace early."""
from codeverse3d.agents.cli_common import HARD_GRACE_S
- from codeverse3d.tracks.static_object import OBJECT_ROUND_RESERVE_S, REFINE_MIN_WINDOW_S
+ from codeverse3d.tracks.static_object import REFINE_MIN_WINDOW_S
track, ctx = _ctx(tmp_path, settings, Language.BLENDER, _big_plan(8))
+ reserve = ctx.policy.judge_reserve_s # one reserve for every track (D112; was 180 s here)
hard_s = ctx.budget.hard_minutes * 60.0
(early,), _ = track.refine_tasks(ctx, _last(ctx.plan))
- assert early.timeout_s == min(ctx.settings.limits.agent_timeout_s,
- int(hard_s - OBJECT_ROUND_RESERVE_S - HARD_GRACE_S))
+ assert early.timeout_s == max(REFINE_MIN_WINDOW_S, min(ctx.settings.limits.agent_timeout_s,
+ int(hard_s - reserve - HARD_GRACE_S)))
ctx.budget._active_s = hard_s - 34.2 * 60 # 34.2 min left, as in the smoke
(late,), _ = track.refine_tasks(ctx, _last(ctx.plan))
left = ctx.budget.hard_minutes * 60.0 - ctx.budget.elapsed_minutes() * 60.0
- assert late.timeout_s + HARD_GRACE_S <= left - OBJECT_ROUND_RESERVE_S + 1
+ assert late.timeout_s + HARD_GRACE_S <= left - reserve + 1
assert late.timeout_s > 20 * 60 # still a real session
ctx.budget._active_s = hard_s - 60 # one minute left: the floor, the run clock decides
(last_minute,), _ = track.refine_tasks(ctx, _last(ctx.plan))
diff --git a/harness/tests/orchestrator_tracks/test_env_stage_honest.py b/harness/tests/orchestrator_tracks/test_env_stage_honest.py
index 170d9192..03c42e08 100644
--- a/harness/tests/orchestrator_tracks/test_env_stage_honest.py
+++ b/harness/tests/orchestrator_tracks/test_env_stage_honest.py
@@ -101,3 +101,83 @@ def test_a_session_that_wrote_the_env_triggers_no_recovery(tmp_path, settings, m
out = track._env_stage(ctx)
assert out == {"ok": True, "files": [rel], "notes": ""} and labels == ["env"], (out, labels)
assert "env.recover" not in _events(ctx)
+
+
+# ----------------------------------------------------------------------------- D112: a checked recovery
[email protected]("language", LANGUAGES)
+def test_a_recovery_that_fails_its_check_gets_one_repair_with_the_error_and_the_lib_index(tmp_path, settings, monkeypatch,
+ language):
+ """Iteration 5: 7 of 21 recovered env modules were broken or unlit and nothing looked."""
+ track, ctx = _ctx(tmp_path, settings, language)
+ rel = env_file(ctx)
+ prompts: dict[str, str] = {}
+
+ def fake_generate_for(gen: Any, task: Any) -> GenerationResult:
+ prompts[task.label] = task.prompt
+ if task.label == "env":
+ return GenerationResult(ok=False, label=task.label, notes="exit=timeout")
+ body = "# repaired env\n" if task.label.endswith(".repair") else f"# {ctx.runtime.ENV_BROKEN} env\n"
+ (ctx.ws.root / rel).write_text(body)
+ 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"] and out["files"] == [rel] and "+ repair" in out["notes"], out
+ assert list(prompts) == ["env", "env.recover", "env.recover.repair"], list(prompts)
+ assert "lib/fake.js: makeFake(opts = {})" in prompts["env.recover"]
+ assert "lib/fake.js" not in prompts["env"], "the session opens the library itself"
+ repair = prompts["env.recover.repair"]
+ assert f"{rel}: {ctx.runtime.ENV_BROKEN} found" in repair and f"# {ctx.runtime.ENV_BROKEN} env" in repair
+ assert (ctx.ws.root / rel).read_text() == "# repaired env\n"
+ checked = [e for e in ctx.events.read() if e["event"] == "env.checked"]
+ assert [c["ok"] for c in checked] == [False, True]
+
+
[email protected]("language", LANGUAGES)
+def test_a_recovery_that_fails_twice_leaves_the_placeholder_and_a_failed_stage(tmp_path, settings, monkeypatch, language):
+ track, ctx = _ctx(tmp_path, settings, language)
+ rel = env_file(ctx)
+
+ def fake_generate_for(gen: Any, task: Any) -> GenerationResult:
+ if task.label == "env":
+ return GenerationResult(ok=False, label=task.label, notes="exit=timeout")
+ (ctx.ws.root / rel).write_text(f"# {ctx.runtime.ENV_BROKEN} again\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"] is False and out["files"] == [] and "failed its check" in out["notes"], out
+ assert (ctx.ws.root / rel).read_text() == "# PLACEHOLDER env\n", "a broken env would break every zone importing it"
+
+
+def test_the_recovery_never_commits_inside_another_sessions_window(tmp_path, settings, monkeypatch):
+ """Iteration 5, scene_blender r1_10: env.recover committed while an escalated asset session held the
+ workspace; that session's scope check then restored env.py to its own ``head_before``."""
+ import threading
+
+ from codeverse3d.agents.cli_common import begin_session, finish_session
+ from codeverse3d.contracts.agent import AgentJob
+ from codeverse3d.contracts.common import Usage
+
+ track, ctx = _ctx(tmp_path, settings, Language.SCENE_BLENDER)
+ rel = env_file(ctx)
+ session = begin_session(AgentJob(workspace=str(ctx.ws.root), prompt="p", label="asset_burlap", files_hint=["src/assets/lantern.js"],
+ edit_only=True), "agy")
+ wrote = threading.Event()
+
+ def fake_generate_for(gen: Any, task: Any) -> GenerationResult:
+ if task.label == "env":
+ return GenerationResult(ok=False, label=task.label, notes="exit=timeout")
+ (ctx.ws.root / rel).write_text("# the recovered env\n")
+ wrote.set()
+ return GenerationResult(ok=True, files_changed=[FileChange(path=rel, status="modified")], label=task.label)
+
+ monkeypatch.setattr(scene_mod, "generate_for", fake_generate_for)
+ out: dict[str, Any] = {}
+ stage = threading.Thread(target=lambda: out.update(track._env_stage(ctx)))
+ stage.start()
+ assert not wrote.wait(0.5), "the recovery waits for the session that holds the workspace"
+ finish_session(session, ok=True, exit_reason="completed", text="", usage=Usage())
+ stage.join(10)
+ assert out.get("ok"), out
+ assert (ctx.ws.root / rel).read_text() == "# the recovered env\n"
diff --git a/harness/tests/orchestrator_tracks/test_fix_batch2.py b/harness/tests/orchestrator_tracks/test_fix_batch2.py
index 300e7013..eac08fe4 100644
--- a/harness/tests/orchestrator_tracks/test_fix_batch2.py
+++ b/harness/tests/orchestrator_tracks/test_fix_batch2.py
@@ -10,7 +10,7 @@ from codeverse3d.contracts.artifacts import BuildResult, GateReport, Judgment
from codeverse3d.contracts.common import Language, Track
from codeverse3d.contracts.plan import BBox, PartPlan, ScenePlan, StaticPlan
from codeverse3d.contracts.run import RoundRecord, RunStatus
-from codeverse3d.orchestrator import RunState
+from codeverse3d.orchestrator import RoundPolicy, RunState
from codeverse3d.proc import EventLog
from codeverse3d.tracks.planner import plan_example
from codeverse3d.tracks.scene import SceneTrack
@@ -59,14 +59,19 @@ class ScriptedJudge(FakeJudge):
# --------------------------------------------------------------------- finding: finalise with a dirty tree at the last commit
def test_finalise_restores_the_last_round_when_an_aborted_round_dirtied_src(tmp_path, chair_plan, settings):
- """A refine round that died after writing files leaves src/ back on the last judged round."""
+ """A refine round that died after writing files leaves src/ back on the last judged round.
+
+ finalise's own guarantee, so D112's two budget levers are off here: the launch window (4 min are
+ left, under min_session_s + judge_reserve_s) and the refine salvage (which would JUDGE these
+ edits — tests/orchestrator_tracks/test_transport_retry.py pins that path)."""
spec = make_spec(max_rounds=3)
ws = Workspace(tmp_path / "runs" / "r")
# the baseline session's 6 minutes fit the 10-minute clock; the refine session's 6 more
# cross it AFTER its files hit the disk.
track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.55, 0.7), targets=("Seat",)), agent=FakeAgent(_writer, minutes=6.0),
planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
- runtime=FakeRuntime(Language.THREEJS))
+ runtime=FakeRuntime(Language.THREEJS), policy=_NO_RESERVE)
+ track._salvage = lambda ctx, rounds: None # type: ignore[method-assign]
with fake_clock():
rec = track.run(spec, ws)
assert rec.status is RunStatus.BUDGET and len(rec.rounds) == 1
@@ -79,6 +84,10 @@ def test_finalise_restores_the_last_round_when_an_aborted_round_dirtied_src(tmp_
assert rec.extra["aborted_rounds"][0]["cost_usd"] == pytest.approx(0.01, abs=1e-6)
+#: D112's launch window off: these tests drive a refine round past the clock on purpose
+_NO_RESERVE = RoundPolicy(max_rounds=3, judge_reserve_s=0.0, min_session_s=0.0)
+
+
class _RebuildFails(FakeRuntime):
"""Fails the finalise rebuild (the build right after a "back to the last round" commit)
``fails`` times, invalidating the canonical GLB first as the real runtimes do."""
@@ -229,9 +238,12 @@ def test_a_successful_re_finalise_clears_the_stale_rebuild_failed_flag(tmp_path,
runtime = _RebuildFails(Language.THREEJS, fails=1)
def track():
- return StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.7,), targets=("Seat",)),
- agent=FakeAgent(_writer, minutes=6.0), planner_model=_planner(chair_plan.model_dump(mode="json")),
- settings=settings, runtime=runtime)
+ # finalise's own path: D112's launch window and refine salvage are off (see the test above)
+ t = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.7,), targets=("Seat",)),
+ agent=FakeAgent(_writer, minutes=6.0), planner_model=_planner(chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=runtime, policy=_NO_RESERVE)
+ t._salvage = lambda ctx, rounds: None # type: ignore[method-assign]
+ return t
with fake_clock():
rec1 = track().run(spec, ws)
diff --git a/harness/tests/orchestrator_tracks/test_refine_evidence.py b/harness/tests/orchestrator_tracks/test_refine_evidence.py
new file mode 100644
index 00000000..ffe590e9
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_refine_evidence.py
@@ -0,0 +1,32 @@
+"""D112: the scene refine prompt carries the placement evidence itself, as facts.
+
+Iteration 5, scene_threejs r1_07: the refine session read for its whole 15-minute window — 1.96 M input
+tokens, most of them five pages of the 3 772-line ``artifacts/scene_probe.json`` — hunting the rows
+behind "floating 0.05 m" in a scene its prompt calls outdoors, and was killed before its first write.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse3d.contracts.common import Language
+from codeverse3d.contracts.run import RoundRecord
+from codeverse3d.orchestrator import TaskGroup, build_refine_instructions
+from codeverse3d.spatial.scene_placement import placement_findings
+from tests.orchestrator_tracks.test_env_stage_honest import LANGUAGES, _ctx
+from tests.scene_gates.test_placement import _row, _table
+
+
[email protected]("language", LANGUAGES)
+def test_the_refine_prompt_states_each_failed_row_its_gap_and_tolerance(tmp_path, settings, language: Language):
+ track, ctx = _ctx(tmp_path, settings, language)
+ ctx.tool_cards = "(tools)"
+ gate = placement_findings(_table(*[_row(f"Boulder{i}", zone="FernHollow", gap=g) for i, g in enumerate((0.048, 0.046, 0.041))]),
+ indoor=True)
+ tasks = build_refine_instructions(None, [gate], [], ctx.plan, max_tasks=6)
+ group = TaskGroup(label="all", tasks=tasks, targets=sorted({t.target for t in tasks}), files=[])
+ prompt = track._refine_task(ctx, group, RoundRecord(index=0, kind="baseline"), 1, parallel=False).prompt
+ for name, gap in (("FernHollow/Boulder0", "0.048"), ("FernHollow/Boulder1", "0.046"), ("FernHollow/Boulder2", "0.041")):
+ assert f"{name} is floating {gap} m above Ground (touches nothing; indoor tolerance 0.02 m" in prompt, name
+ assert "`artifacts/scene_probe.json` is the probe driver's raw dump" in prompt
+ assert "`check_placement` returns the placement rows" in prompt
diff --git a/harness/tests/orchestrator_tracks/test_transport_retry.py b/harness/tests/orchestrator_tracks/test_transport_retry.py
index a7da0809..0dceb6ad 100644
--- a/harness/tests/orchestrator_tracks/test_transport_retry.py
+++ b/harness/tests/orchestrator_tracks/test_transport_retry.py
@@ -118,3 +118,153 @@ def test_a_vendor_usage_limit_stops_the_run_as_agent_quota_not_no_change(tmp_pat
evs = _events(ws)
assert "round.agent_quota" in evs and "round.transport_retry" not in evs and "round.no_change" not in evs
assert max(j.round for j in agent.jobs) == 1 # the refine round's sessions met the wall; no retry round
+
+
+# --------------------------------------------------------------- D112: one rule for a hung session, a judge reserve,
+# and the edits the clock stopped are judged
+HUNG = AgentResult(ok=False, exit_reason="timeout", usage=Usage(cost_usd=0.01), stalled=True,
+ errors=["killed by watchdog (idle) after 901s"])
+WORKED_TO_THE_LIMIT = AgentResult(ok=False, exit_reason="timeout", usage=Usage(cost_usd=0.01),
+ errors=["killed by watchdog (hard_timeout) after 1200s"])
+
+
+def test_a_hung_refine_session_is_retried_once_whatever_the_vendor_log_said(tmp_path, chair_plan, settings):
+ """Iteration 5: the same 901 s / zero-file kill was retried in r1_05 / r1_09 (a stray 4 s 503 in agy's
+ log) and ended r1_07 / r1_08 as no_change. Now a hang is ``stalled`` and retried by the clock alone."""
+ calls = {"n": 0}
+
+ def writer(job, ws):
+ if job.round == 1:
+ calls["n"] += 1
+ if calls["n"] == 1:
+ return HUNG
+ return _writer(job, ws)
+
+ ws = Workspace(tmp_path / "runs" / "hung")
+ rec = _track(FakeAgent(writer), (0.55, 0.7), chair_plan, settings).run(make_spec(max_rounds=1), ws)
+ retries = [e for e in EventLog(ws.events_path).read() if e["event"] == "round.transport_retry"]
+ assert len(retries) == 1 and retries[0]["stalled"] is True
+ assert [r.score for r in rec.rounds] == pytest.approx([0.55, 0.7])
+
+
+def test_a_session_that_worked_to_its_hard_limit_is_not_retried(tmp_path, chair_plan, settings):
+ ws = Workspace(tmp_path / "runs" / "limit")
+ rec = _track(after_baseline(WORKED_TO_THE_LIMIT), (0.55,), chair_plan, settings).run(make_spec(max_rounds=2), ws)
+ assert rec.status is RunStatus.NO_CHANGE and "round.transport_retry" not in _events(ws)
+
+
+def test_no_refine_round_is_launched_that_could_not_also_be_judged(tmp_path, chair_plan, settings):
+ """The baseline burns the clock down to less than a minimum window + the judge reserve (7 min)."""
+ from tests.orchestrator_tracks.conftest import fake_clock
+
+ agent = FakeAgent(_writer, minutes=4.0)
+ ws = Workspace(tmp_path / "runs" / "reserve")
+ with fake_clock():
+ rec = _track(agent, (0.55,), chair_plan, settings).run(make_spec(max_rounds=3, max_minutes=10.0), ws)
+ assert rec.status is RunStatus.BUDGET and [j.round for j in agent.jobs] == [0]
+ skipped = [e for e in EventLog(ws.events_path).read() if e["event"] == "round.skipped_budget"]
+ assert len(skipped) == 1 and skipped[0]["need_s"] == 420.0 and skipped[0]["left_s"] == pytest.approx(360.0)
+
+
+def test_a_refine_session_leaves_the_judge_reserve_on_the_clock(tmp_path, chair_plan, settings):
+ import time
+
+ left: dict[int, float] = {}
+
+ def writer(job, ws):
+ left[job.round] = job.hard_deadline_s - time.monotonic()
+ return _writer(job, ws)
+
+ ws = Workspace(tmp_path / "runs" / "deadline")
+ _track(FakeAgent(writer), (0.55, 0.6), chair_plan, settings).run(make_spec(max_rounds=1, max_minutes=10.0), ws)
+ assert 560 < left[0] <= 600, "the baseline is not a refine: no reserve"
+ assert 320 < left[1] <= 360, "a refine session's deadline ends judge_reserve_s (240 s) before the budget"
+
+
+def test_refine_edits_the_clock_stopped_are_built_and_judged(tmp_path, chair_plan, settings):
+ """Iteration 5, r1_09: the retry's edits were committed, then the budget stop threw them away and
+ finalise rebuilt round 0. Now ONE bounded grace builds, renders and judges them."""
+ from tests.orchestrator_tracks.conftest import FAKE_CLOCK, fake_clock
+
+ def writer(job, ws):
+ if job.round == 1:
+ FAKE_CLOCK["minutes"] = 10.5 # the session ran to the run's edge
+ return _writer(job, ws)
+
+ ws = Workspace(tmp_path / "runs" / "salvage")
+ with fake_clock():
+ rec = _track(FakeAgent(writer), (0.6, 0.8), chair_plan, settings).run(make_spec(max_rounds=3, max_minutes=10.0), ws)
+ assert rec.status is RunStatus.BUDGET
+ assert [r.score for r in rec.rounds] == pytest.approx([0.6, 0.8])
+ assert rec.rounds[1].kind == "refine" and "salvaged" in rec.rounds[1].notes
+ salvage = [e for e in EventLog(ws.events_path).read() if e["event"] == "budget.salvage"]
+ assert len(salvage) == 1 and "src/object.js" in salvage[0]["files"]
+
+
+def test_a_stop_before_any_refine_edit_salvages_nothing(tmp_path, chair_plan, settings):
+ from tests.orchestrator_tracks.conftest import FAKE_CLOCK, fake_clock
+
+ def writer(job, ws):
+ if job.round == 1:
+ FAKE_CLOCK["minutes"] = 10.5
+ return WORKED_TO_THE_LIMIT
+ return _writer(job, ws)
+
+ ws = Workspace(tmp_path / "runs" / "nothing")
+ with fake_clock():
+ rec = _track(FakeAgent(writer), (0.6,), chair_plan, settings).run(make_spec(max_rounds=3, max_minutes=10.0), ws)
+ assert rec.status is RunStatus.BUDGET and len(rec.rounds) == 1 and "budget.salvage" not in _events(ws)
+
+
+# --------------------------------------------------------------- D112 review: the hang rule on every path
+def test_a_split_round_is_stalled_only_when_every_session_hung():
+ """The round loop retries a round WHOLE: one session that worked to its hard limit and wrote
+ nothing must not be re-run because its sibling hung (D112's rule for the hard-limit kill)."""
+ hung = GenerationResult(ok=False, notes="killed by watchdog (idle)", label="a", stalled=True)
+ worked = GenerationResult(ok=False, notes="killed by watchdog (hard_timeout)", label="b")
+ storm = GenerationResult(ok=False, notes="exit=error", label="c", transient=True)
+ assert RoundFailed.of([hung], "x").stalled
+ assert RoundFailed.of([hung, hung.model_copy(update={"label": "d"})], "x").stalled
+ assert RoundFailed.of([hung, storm], "x").stalled # every session died without working
+ assert not RoundFailed.of([hung, worked], "x").stalled
+ assert not RoundFailed.of([worked], "x").stalled
+
+
+def test_hung_best_of_n_candidates_get_the_round_loops_retry(tmp_path, chair_plan, settings):
+ """``--candidates 2``: every candidate's session hangs. The round's failure must carry ``stalled``
+ like a single-candidate round's does, so round 0 gets its one retry before the run fails."""
+ agent = FakeAgent(lambda job, ws: HUNG)
+ ws = Workspace(tmp_path / "runs" / "hung_n")
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)), agent=agent,
+ planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.THREEJS), n_candidates=2)
+ with pytest.raises(RoundFailed) as err:
+ track.run(make_spec(max_rounds=1), ws)
+ assert err.value.stalled
+ retries = [e for e in EventLog(ws.events_path).read() if e["event"] == "round.transport_retry"]
+ assert len(retries) == 1 and retries[0]["stalled"] is True
+
+
+def test_a_single_shot_refine_needs_only_the_judge_reserve(tmp_path, chair_plan, settings):
+ """The economy profile's refine is one API call, not a session: 270 s left (> the 240 s judge
+ reserve, < the 420 s an agent session needs) still opens the round and gets it judged."""
+ from tests.orchestrator_tracks.conftest import FAKE_CLOCK, fake_clock
+
+ calls = {"n": 0}
+
+ def respond(req):
+ calls["n"] += 1
+ if calls["n"] == 1:
+ FAKE_CLOCK["minutes"] = 5.5 # the baseline call left 270 s of the 10-min clock
+ return (f"=== FILE: src/object.js ===\n// call {calls['n']}\n"
+ "export function build(THREE) { return new THREE.Group(); }\n=== END FILE ===")
+
+ ws = Workspace(tmp_path / "runs" / "economy")
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.55, 0.7)), model=FakeChatModel(respond),
+ planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.THREEJS))
+ with fake_clock():
+ rec = track.run(make_spec(generator="single-shot:gemini:x", max_rounds=1, max_minutes=10.0), ws)
+ assert "round.skipped_budget" not in _events(ws)
+ assert [r.kind for r in rec.rounds] == ["baseline", "refine"]
+ assert [r.score for r in rec.rounds] == pytest.approx([0.55, 0.7])
diff --git a/harness/tests/scene_blender/test_build.py b/harness/tests/scene_blender/test_build.py
index 69a98a6b..7d63c9af 100644
--- a/harness/tests/scene_blender/test_build.py
+++ b/harness/tests/scene_blender/test_build.py
@@ -95,9 +95,17 @@ def test_bpy_facts_reach_the_census(built) -> None:
assert [g.gate for g in res.gates] == ["scene_probe"]
+def _only_unlit(res) -> None:
+ """The skeleton's build: everything built, and the one ERROR is the placeholder env's ``unlit``."""
+ errors = [f for g in res.gates for f in g.errors]
+ assert not res.ok and [(f.data.get("kind"), f.target) for f in errors] == [("unlit", "src/env.py")], res.stdout_tail
+ assert res.error_file == "src/env.py"
+
+
def test_the_skeleton_builds_and_passes(tmp_ws) -> None:
- """plan → skeleton → assemble → build: the starter scene passes its own gates, the fog volume
- is a fact (not matter), the sky a background, the plan's cameras reach the host."""
+ """plan → skeleton → assemble → build: the starter scene fails ONE gate — the placeholder env lights
+ nothing (`unlit`, an ERROR since D112, so round 0's repair is handed the env) — and passes the rest;
+ the plan's cameras reach the host."""
plan = ScenePlan.model_validate(plan_example(Track.SCENE))
rt = _rt()
rt.skeleton(tmp_ws, plan)
@@ -106,7 +114,7 @@ def test_the_skeleton_builds_and_passes(tmp_ws) -> None:
asm = rt.assemble(tmp_ws, plan)
assert set(asm.zones_included) == {"quay", "water"} and not asm.zones_failed
res = rt.build(tmp_ws)
- assert res.ok, res.stdout_tail
+ _only_unlit(res)
c = res.census
# the stub env ships a plate and nothing that passes: no world, no atmosphere, no lamp until the author
# writes the brief's (a placeholder that passed was kept by every author, 2026-10-15)
@@ -132,7 +140,7 @@ def test_the_skeleton_renders_through_the_runtime(tmp_ws, switch) -> None:
rt = _rt()
rt.skeleton(tmp_ws, plan)
rt.assemble(tmp_ws, plan)
- assert rt.build(tmp_ws).ok
+ _only_unlit(rt.build(tmp_ws)) # the placeholder env is unlit (D112); the scene still built and renders
rs = rt.render_scene(tmp_ws, tmp_ws.root / "renders", times=(0.0, 1.5), width=96, height=54, sheet=False)
names = [to_snake(c.name) for c in plan.cameras[:6]]
authored = {(v.name, v.time_s) for v in rs.views if v.name in names}
diff --git a/harness/tests/scene_blender/test_env_check.py b/harness/tests/scene_blender/test_env_check.py
new file mode 100644
index 00000000..20ed337c
--- /dev/null
+++ b/harness/tests/scene_blender/test_env_check.py
@@ -0,0 +1,84 @@
+"""D112: ``SceneBlenderRuntime.check_env`` / ``lib_interface`` — the env module alone (argon loop
+iteration 5: a recovered env.py that did not parse, one that raised on an unknown keyword, one with
+no lamp and no world)."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse3d.config import get_settings
+from codeverse3d.contracts.common import Language
+from codeverse3d.languages import get_runtime
+from codeverse3d.languages.scene_blender import LIB_DIR, lib_interface
+from codeverse3d.workspace import Workspace
+from tests.scene_blender.fixtures import ENV
+
+needs_blender = pytest.mark.skipif(not get_settings().resolve_blender(), reason="no Blender binary")
+
+VARIANTS = {
+ "syntax": (ENV.replace("return 0.0", "noise_ centered = 1\n return 0.0"), "SyntaxError"),
+ "raises": (ENV.replace("return {}", "mineral_surface(roughness=0.5)\n return {}"), "NameError"),
+ "unlit": (ENV.replace(' ctx.scene.world = world\n', "").replace(
+ ' ctx.collection.objects.link(bpy.data.objects.new("Sun", bpy.data.lights.new("Sun", "SUN")))\n', ""),
+ "renders black"),
+}
+
+
+def _ws(tmp_path, env: str) -> Workspace:
+ ws = Workspace(tmp_path / "run").create()
+ ws.src.mkdir(parents=True, exist_ok=True)
+ (ws.src / "env.py").write_text(env)
+ (ws.src / "scene.py").write_text("ZONES = {}\nASSETS = {}\nHEROES = {}\nCAMERAS = []\n")
+ return ws
+
+
+def test_the_lib_interface_lists_signatures_as_written(tmp_path):
+ ws = _ws(tmp_path, ENV)
+ (ws.src / "lib").mkdir()
+ for p in LIB_DIR.glob("*.py"):
+ (ws.src / "lib" / p.name).write_text(p.read_text())
+ rows = lib_interface(ws).splitlines()
+ assert rows and all(r.startswith("lib/") for r in rows)
+ assert not any(r.startswith("lib/__init__.py") for r in rows)
+ assert any(r.startswith("lib/sky.py (lib.sky): ") and "(" in r for r in rows)
+
+
+@needs_blender
+def test_a_good_env_passes_and_each_broken_one_says_why(tmp_path):
+ rt = get_runtime(Language.SCENE_BLENDER)
+ assert rt.check_env(_ws(tmp_path / "good", ENV)) == ""
+ for name, (env, says) in VARIANTS.items():
+ error = rt.check_env(_ws(tmp_path / name, env))
+ assert says in error, (name, error)
+ assert not (tmp_path / "good" / "run" / "src" / "_c3d_env_check.py").exists(), "the check's entry is deleted"
+
+
+def test_a_raise_inside_a_lib_helper_is_quoted_at_the_env_line_that_called_it():
+ """D112 review: iteration 5 blender r1_04's recovered env was reported at ``src/lib/mesh.py:69`` — a file
+ the repair single-shot never sees — while its own bad call (a tuple rotation) was ``env.py:287``."""
+ from codeverse3d.languages.scene_blender import env_frame
+
+ tb = ('Traceback (most recent call last):\n'
+ ' File "/h/wrappers/run_bpy_scene.py", line 199, in run\n out = mod.build_env(ctx)\n'
+ ' File "/w/run/src/env.py", line 457, in build_env\n _build_sky_backdrop(ctx)\n'
+ ' File "/w/run/src/env.py", line 287, in _build_sky_backdrop\n sky_batch.box(\n ~~~~~~^\n'
+ ' File "/w/run/src/lib/mesh.py", line 69, in box_geometry\n c, s = math.cos(rotation), math.sin(rotation)\n'
+ 'TypeError: must be real number, not tuple\n')
+ assert env_frame(tb) == "src/env.py:287 `sky_batch.box(`"
+ assert env_frame(tb.replace("/src/env.py", "/src/lib/env.py")) == "" # a lib module is not the env
+
+
+@needs_blender
+def test_check_env_leads_with_the_env_line_when_a_lib_helper_raised(tmp_path):
+ env = ENV.replace("import bpy\n", "import bpy\nfrom lib.turn import spin\n", 1).replace(
+ " return {}\n", " spin((0.0, 0.0, 1.0))\n return {}\n")
+ ws = _ws(tmp_path, env)
+ (ws.src / "lib").mkdir()
+ (ws.src / "lib" / "__init__.py").write_text("")
+ (ws.src / "lib" / "turn.py").write_text("import math\n\n\ndef spin(rotation):\n return math.cos(rotation)\n")
+ error = get_runtime(Language.SCENE_BLENDER).check_env(ws)
+ line = next(i for i, text in enumerate(env.splitlines(), 1) if "spin((0.0" in text)
+ assert error.startswith(f"src/env.py:{line} `spin((0.0, 0.0, 1.0))` (raised in src/lib/turn.py:5)"), error
+ assert "TypeError" in error
diff --git a/harness/tests/scene_blender/test_layout.py b/harness/tests/scene_blender/test_layout.py
index f7e74e9a..82096609 100644
--- a/harness/tests/scene_blender/test_layout.py
+++ b/harness/tests/scene_blender/test_layout.py
@@ -176,6 +176,22 @@ def test_offline_lamp_check_counts_the_world() -> None:
assert [f for f in dark if "lamps" in f.message][0].target == "src/env.py"
+def test_an_unlit_scene_fails_the_build_in_both_languages() -> None:
+ """D112 (argon loop iteration 5, scene_blender r1_10): the placeholder env — no lamp, no world —
+ passed the build as a WARN and every round-0 frame was black after the full render and judge spend.
+ An ERROR fails the build, so the round's repair is handed the env first. The three.js twin: no
+ light, no background and no environment map."""
+ dark = [f for f in _census_findings(_census(lights=0, background=None), offline=True) if f.data.get("kind") == "unlit"]
+ assert len(dark) == 1 and dark[0].severity is Severity.ERROR and dark[0].target == "src/env.py"
+ three = {"totals": {"meshes": 3, "lights": 0, "draws": 3}, "groups": [], "background": None, "environment": False}
+ dark = [f for f in _census_findings(three) if f.data.get("kind") == "unlit"]
+ assert len(dark) == 1 and dark[0].severity is Severity.ERROR and dark[0].target == "src/env.js"
+ for lit in ({"background": "#88aacc"}, {"environment": True}, {"totals": {"meshes": 3, "lights": 2, "draws": 3}}):
+ assert not [f for f in _census_findings({**three, **lit}) if f.severity is Severity.ERROR], lit
+ # a sky but no light keeps its WARN (MeshStandardMaterial still renders black)
+ assert [f.severity for f in _census_findings({**three, "background": "#88aacc"}) if "no lights" in f.message] == [Severity.WARN]
+
+
def test_each_scene_language_plans_its_own_asset_kinds() -> None:
"""D5: ``bpy`` joins the kinds a plan may hold; the schema a planner is handed stays
scene_threejs's (its prompts are byte-identical), a scene_blender planner swaps its own in."""
diff --git a/harness/tests/scene_gates/test_placement.py b/harness/tests/scene_gates/test_placement.py
index b5b0acab..786770f0 100644
--- a/harness/tests/scene_gates/test_placement.py
+++ b/harness/tests/scene_gates/test_placement.py
@@ -54,7 +54,7 @@ def test_floating_severity_by_gap_then_by_count():
fl = _by_kind(r, "floating")
assert {f.target: f.severity for f in fl} == {"Yard/Lantern": Severity.ERROR, "Yard/Cup": Severity.WARN}
lantern = next(f for f in fl if f.target == "Yard/Lantern")
- assert "floating 0.30 m above Ground" in lantern.message and "lower Yard/Lantern by 0.30 m" in lantern.fix_hint
+ assert "floating 0.300 m above Ground" in lantern.message and "lower Yard/Lantern by 0.300 m" in lantern.fix_hint
assert "userData.placement = 'free'" in lantern.fix_hint
assert not r.passed
# a 9 cm hover is past the strict line (a WARN under the 2026-09 0.15 m)
@@ -194,7 +194,7 @@ def test_check_placement_returns_the_round_gates_verdict(tmp_path):
# Bench was never built: House (its only content) is neither missing it nor empty
assert {"floating", "no_fog"} <= kinds and not {"missing_content", "zone_empty"} & kinds
# an interior plan: the tighter tolerance is named, and the table text is what the agent reads
- ws.plan_path.write_text(plan.model_copy(update={"setting": "a cabin interior"}).model_dump_json())
+ ws.plan_path.write_text(plan.model_copy(update={"setting": "a cabin interior", "interior": True}).model_dump_json())
obs = get_tool("check_placement").call(ToolContext(workspace=ws, language=Language.SCENE_THREEJS.value), {})
assert not obs.ok and "indoor tolerance 2 cm" in obs.text
text = placement_table_text(census["placement"])
@@ -270,6 +270,29 @@ def test_the_typed_interior_flag_wins_over_the_setting_words():
assert not is_interior({"setting": "a mountain meadow at dawn", "interior": False})
assert is_interior({"setting": "a cosy cabin interior at dusk"}) # no flag: the words decide
assert is_interior(_contract_plan().model_copy(update={"interior": True}))
+ assert is_interior({"setting": "a cosy cabin interior at dusk", "interior": None}) # None = no flag
+
+
+def test_an_outdoor_flag_is_not_overruled_by_indoor_sounding_words():
+ """D112, argon loop iteration 5: a zone named GiantTrunkCorridor and a luminance band "inside
+ 0.42-0.62" put two outdoor plans on the 2 cm indoor tolerance."""
+ from codeverse3d.spatial.scene_placement import infer_indoor, is_interior
+
+ redwoods = {"setting": "coastal redwood forest at dawn", "interior": False,
+ "environment": "fog drifts down the GiantTrunkCorridor between the trunks"}
+ canyon = {"setting": "desert slot canyon at noon", "interior": False,
+ "environment": "warm bounce light; hold frame mean luminance inside 0.42-0.62"}
+ assert infer_indoor(redwoods["environment"]) and infer_indoor(canyon["environment"]) # the words alone say indoors
+ assert not is_interior(redwoods) and not is_interior(canyon)
+ plan = _contract_plan().model_copy(update={"interior": False, "environment": canyon["environment"]})
+ assert not is_interior(plan)
+ census = {"background": "#aabbcc", "placement": _table(_row("Boulder", h=1.0, gap=0.045),
+ _row("BoulderB", h=1.0, gap=0.046),
+ _row("BoulderC", h=1.0, gap=0.048))}
+ rep = placement_gate_safe(census, plan=plan)
+ assert _by_kind(rep, "summary")[0].data["thresholds"]["indoor"] is False
+ assert not [f for f in rep.findings if f.severity == Severity.ERROR and "floating" in f.message], \
+ [f.message for f in rep.findings]
def test_fog_that_ends_inside_the_plan_is_warned_for_exteriors_only():
@@ -357,8 +380,8 @@ def test_world_edge_is_a_warn_note_outdoors_and_quiet_when_the_place_continues_o
{"name": "FarFields", "kind": "content", "bbox": {"min": [-40, 0, -40], "max": [40, 5, 40]}}])
rep = placement_gate_safe(continued, plan=_contract_plan(), layouts=None)
assert not [f for f in rep.findings if f.data.get("kind") == "world_edge"]
- # an interior never asks for one
- indoor = _contract_plan().model_copy(update={"setting": "a candlelit library interior"})
+ # an interior never asks for one (the typed flag says so: a ScenePlan always carries one, D112)
+ indoor = _contract_plan().model_copy(update={"setting": "a candlelit library interior", "interior": True})
rep = placement_gate_safe(near_only, plan=indoor, layouts=None)
assert not [f for f in rep.findings if f.data.get("kind") == "world_edge"]
@@ -533,3 +556,22 @@ def test_the_zone_at_a_truncated_tables_cut_is_partly_measured():
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
+
+
+def test_a_floating_row_states_its_gap_to_the_millimetre_and_the_tolerance_applied():
+ """D112, iteration 5 r1_07: "floating 0.05 m" for a 0.048 m gap in a scene the prompt calls
+ outdoors (tolerance 0.05 m) read as a contradiction; the refine session paged the raw probe dump
+ for 15 minutes to resolve it and was killed before writing."""
+ rows = [_row(f"Boulder{i}", gap=g) for i, g in enumerate((0.048, 0.046, 0.041))]
+ indoor = _by_kind(placement_findings(_table(*rows), indoor=True), "floating")
+ assert [f.severity for f in indoor] == [Severity.ERROR] * 3
+ first = next(f for f in indoor if f.target == "Yard/Boulder0")
+ assert "floating 0.048 m above Ground" in first.message and "indoor tolerance 0.02 m" in first.message
+ assert "ERROR because 3 rows float, more than 2" in first.message
+ outdoor = placement_findings(_table(*rows), indoor=False)
+ assert not _by_kind(outdoor, "floating")
+ hover = _by_kind(outdoor, "unsupported")
+ assert len(hover) == 3 and all("within the outdoor tolerance 0.05 m" in f.message for f in hover)
+ assert "hovers 0.048 m" in next(f.message for f in hover if f.target == "Yard/Boulder0")
+ far = _by_kind(placement_findings(_table(_row("Kite", gap=0.3))), "floating")[0]
+ assert "outdoor tolerance 0.05 m; ERROR past 0.08 m" in far.message
diff --git a/harness/tests/scene_runtime/lib/test_environment.py b/harness/tests/scene_runtime/lib/test_environment.py
index 4b285097..f58720c6 100644
--- a/harness/tests/scene_runtime/lib/test_environment.py
+++ b/harness/tests/scene_runtime/lib/test_environment.py
@@ -362,3 +362,26 @@ console.log(JSON.stringify({ seamWorst, maxR, maxY, meanFarY: farLift / nFar, me
assert out["same"] and out["differ"]
assert abs(out["small"] - 984) < 1.5 and abs(out["big"] - 7380) < 2.0
assert abs(out["clamped"] - 984) < 1.5 and abs(out["shorter"] - 600) < 1.5
+
+
+def test_the_sky_dome_keeps_or_sets_the_background_the_gate_reads():
+ """D112: makeSky nulled scene.background ("the dome IS the backdrop") and the harness's own
+ no_background gate then failed three iteration-5 scenes that had set one before calling it."""
+ out = _measure("""
+import * as THREE from 'three';
+import { makeSky } from './lib/sky.js';
+const set = new THREE.Scene();
+const mine = new THREE.Color(0x336699);
+set.background = mine;
+makeSky(set, { elevationDeg: 20 });
+const unset = new THREE.Scene();
+makeSky(unset, { elevationDeg: 20 });
+const night = new THREE.Scene();
+makeSky(night, { elevationDeg: -15 });
+const hsl = (c) => c.getHSL({});
+console.log(JSON.stringify({ kept: set.background === mine, unsetIsColor: !!(unset.background && unset.background.isColor),
+ day: unset.background.toArray(), dayL: hsl(unset.background).l, nightL: hsl(night.background).l }));
+""")
+ assert out["kept"], "a background the caller set survives"
+ assert out["unsetIsColor"], "an unset background becomes a colour the census reports"
+ assert all(0.0 <= v <= 1.0 for v in out["day"]) and out["nightL"] < out["dayL"]
diff --git a/harness/tests/scene_runtime/test_env_check.py b/harness/tests/scene_runtime/test_env_check.py
new file mode 100644
index 00000000..d5532519
--- /dev/null
+++ b/harness/tests/scene_runtime/test_env_check.py
@@ -0,0 +1,65 @@
+"""D112: ``SceneThreeJsRuntime.check_env`` / ``lib_interface`` — the env module alone, checked before a
+recovered env counts as written (argon loop iteration 5: 5 of 21 recovered modules failed only at
+assembly — ``materials.js does not export 'gravel'``, ``pavingPatch is not defined`` — and one more was
+unlit)."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse3d.languages.scene_threejs import LIB_DIR, check_env, lib_interface
+from codeverse3d.workspace import Workspace
+from tests.scene_runtime.conftest import needs_browser
+
+GOOD = """import * as THREE from 'three';
+export function heightAt(x, z) { return 0; }
+export function buildEnv(ctx) {
+ ctx.scene.background = new THREE.Color(0x88aacc);
+ ctx.scene.add(new THREE.DirectionalLight(0xffffff, 2));
+ return {};
+}
+"""
+VARIANTS = {
+ "bad_import": ("import { gravel } from './lib/materials.js';\n" + GOOD, "gravel"),
+ "throws": (GOOD.replace("return {};", "pavingPatch(ctx);\n return {};"), "pavingPatch"),
+ "unlit": (GOOD.replace("ctx.scene.background = new THREE.Color(0x88aacc);", "")
+ .replace("ctx.scene.add(new THREE.DirectionalLight(0xffffff, 2));", ""), "renders black"),
+}
+
+
+def _ws(tmp_path, env: str) -> Workspace:
+ ws = Workspace(tmp_path / "run").create()
+ (ws.src / "lib").mkdir(parents=True, exist_ok=True)
+ for p in LIB_DIR.glob("*.js"):
+ (ws.src / "lib" / p.name).write_text(p.read_text())
+ (ws.src / "env.js").write_text(env)
+ return ws
+
+
+def test_the_lib_interface_is_the_exported_names_with_their_parameters(tmp_path):
+ text = lib_interface(_ws(tmp_path, GOOD))
+ row = next(r for r in text.splitlines() if r.startswith("lib/sky.js: "))
+ assert "makeSky(scene, opts = {})" in row and "SKY_GRADE" in row
+ assert "gravel" not in text.split("lib/materials.js: ")[1].split("\n")[0].split(", ")
+
+
+@needs_browser
+def test_a_good_env_passes_and_each_broken_one_says_why(tmp_path):
+ assert check_env(_ws(tmp_path / "good", GOOD)) == ""
+ for name, (env, says) in VARIANTS.items():
+ error = check_env(_ws(tmp_path / name, env))
+ assert says in error, (name, error)
+ assert not list((tmp_path / "good" / "run" / "src").glob("_c3v_env_probe*")), "the probe entry is deleted"
+
+
+def test_an_arrow_function_export_is_listed_with_its_parameters(tmp_path):
+ """D112 review: the material factories are ``export const asphalt = (o = {}) => …`` — listed as bare
+ names, a single-shot writer could not tell them from constants. A parenthesised value is not a call."""
+ from codeverse3d.languages._js_lint import export_signatures
+
+ row = next(r for r in lib_interface(_ws(tmp_path, GOOD)).splitlines() if r.startswith("lib/materials.js: "))
+ assert "asphalt(o = {})" in row.split(": ", 1)[1].split(", ")
+ src = ("export const a = (x, {y = 1} = {}) => x;\nexport const b = async (p) => p;\nexport const c = q => q;\n"
+ "export let d = function named(m, n) { return m; };\nexport const K = (1 + 2) * 3;\nexport const ARR = [1, 2];\n")
+ assert export_signatures(src) == ["ARR", "K", "a(x, {y = 1} = {})", "b(p)", "c(q)", "d(m, n)"]
diff --git a/harness/tests/scene_runtime/test_update_hooks.py b/harness/tests/scene_runtime/test_update_hooks.py
index 2ae98075..0945fc3b 100644
--- a/harness/tests/scene_runtime/test_update_hooks.py
+++ b/harness/tests/scene_runtime/test_update_hooks.py
@@ -41,6 +41,7 @@ import * as THREE from 'three';
export function createScene() {
const scene=new THREE.Scene(),zone=new THREE.Group(),wing=new THREE.Group();
zone.name='CentralPad';wing.name='Shuttle';scene.add(zone);zone.add(wing);
+ scene.background=new THREE.Color(0x8899aa); // lit enough for the probe (an unlit scene is an ERROR, D112)
wing.add(new THREE.Mesh(new THREE.BoxGeometry(),new THREE.MeshBasicMaterial()));
wing.userData.update=t=>{wing.rotation.y=t;};
zone.userData.update=t=>{FORWARD};
diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.py
index 8b229e07..41072e62 100644
--- a/harness/tests/spatial_tools/test_tools.py
+++ b/harness/tests/spatial_tools/test_tools.py
@@ -370,3 +370,45 @@ def _stool_plan_with_missing_backrest() -> StaticPlan:
parts=[PartPlan(name="Seat", role="r", description="d", bbox=BBox(center=(0, 0, 0.43), extents=(0.4, 0.4, 0.04))),
PartPlan(name="Leg", role="r", description="d", bbox=BBox(center=(0, 0, 0.205), extents=(0.04, 0.04, 0.41)), instances=4),
PartPlan(name="Backrest", role="r", description="d", bbox=BBox(center=(0, 0.18, 0.6), extents=(0.4, 0.03, 0.3)))])
+
+
+class _SceneRuntime:
+ """A scene build whose probe raised ``errors`` (the census was taken: only the verdict differs)."""
+
+ def __init__(self, errors: list[GateFinding]) -> None:
+ self.errors = errors
+
+ def lint(self, ws):
+ return GateReport(gate="lint:scene_blender", passed=True, findings=[])
+
+ def build(self, ws, *, timeout_s=None):
+ first = self.errors[0]
+ res = BuildResult(ok=False, language="scene_blender", error_type=first.data.get("kind") or first.gate,
+ error_message=first.message, error_file=first.target or "", census={"lights": 0, "meshes": 12},
+ gates=[GateReport.of("scene_probe", self.errors)])
+ ws.write_json(ws.artifacts / "build.json", res)
+ return res
+
+
[email protected]("language", ["scene_blender", "scene_threejs"])
+def test_a_session_build_reports_an_unlit_env_above_build_ok(tmp_path: Path, monkeypatch: pytest.MonkeyPatch,
+ language: str) -> None:
+ """D112 review: ``unlit`` is an ERROR so the ROUND's build fails and its repair gets the env — but an
+ asset or zone session building while the env is still the placeholder cannot write the env module, and
+ a BUILD FAILED it cannot clear would spend its window. Its own ``build`` states the error above BUILD
+ OK; any other ERROR beside it is still a BUILD FAILED."""
+ ctx = ToolContext(workspace=Workspace(tmp_path / "ws").create(), language=language, track="scene")
+ unlit = GateFinding(gate="scene_probe", severity=Severity.ERROR, target="src/env.py", data={"kind": "unlit"},
+ message="scene has no lamps and no world: it renders black")
+ _patch_runtime(monkeypatch, _SceneRuntime([unlit]))
+ obs = get_tool("build").call(ctx, {})
+ first, second = obs.text.splitlines()[:2]
+ assert obs.ok and not obs.failed and obs.numbers["env_unlit"] is True
+ assert first.startswith("SCENE UNLIT") and "src/env.py" in first and "renders black" in first
+ assert second.startswith("BUILD OK")
+
+ zone = GateFinding(gate="scene_probe", severity=Severity.ERROR, target="src/zones/quay.py:12",
+ message="zone quay raised NameError: name 'x' is not defined", data={"kind": "zone"})
+ _patch_runtime(monkeypatch, _SceneRuntime([zone, unlit]))
+ obs = get_tool("build").call(ctx, {})
+ assert not obs.ok and obs.text.startswith("BUILD FAILED") and "SCENE UNLIT" not in obs.text