Official Codebase of 3DCodeVerse
Python
rounds: a refine after a regression builds on the best round; the camera repair steps a blocked lens out of its view; the room shell is not a placed thing; rig views hide cloud decks below the eye — D73
gaoypeng7419815163b2
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/environment.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/environment.jsindex 923bb425..bca9b9ef 100644--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/environment.js+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/environment.js@@ -56,6 +56,10 @@ export function roomShell(opts = {}) {const ceilMat = new THREE.MeshStandardMaterial({ color: opts.ceilingColor === undefined ? 0x8d7f6a : opts.ceilingColor, roughness: 0.95 });const group = new THREE.Group();group.name = 'RoomShell';+ // The enclosure is not a placed thing: it defines the floor line. Loop 22's crypt (2026-09-09)+ // read "RoomShell is floating 39.8 m above the ground" against a terrain the env session had+ // sunk to -40 m, and the judge repeated it as critical. Same tag as a bird: not on anything.+ group.userData.placement = 'free';const slab = (name, sx, sy, sz, x, y, z, mat) => {const m = new THREE.Mesh(new THREE.BoxGeometry(sx, sy, sz), mat);m.name = name; m.position.set(x, y, z); m.castShadow = true; m.receiveShadow = true;diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.pyindex 97bea528..b89c2f73 100644--- a/harness/codeverse/tracks/lifecycle.py+++ b/harness/codeverse/tracks/lifecycle.py@@ -652,6 +652,8 @@ class BaseTrack:if rejudge_round(ctx, pipeline, last, previous=prev_j):self._promote_best(ctx, rounds, last.index)continue # decide() re-runs with the recovered score+ last = self._refine_base(ctx, rounds, decision.strategy)+ previous = last.judgmenttasks, instructions = self.refine_tasks(ctx, last, rounds, strategy=decision.strategy)kind = KIND_FOR_STRATEGY.get(decision.strategy, "refine")if not tasks:@@ -701,6 +703,29 @@ class BaseTrack:ctx.state.mark_round_done(index, rec.commit)self._promote_best(ctx, rounds, index)+ @staticmethod+ def _refine_base(ctx: RunContext, rounds: list[RoundRecord], strategy: str) -> RoundRecord:+ """The round the next refine builds on. The last one — unless it regressed past the+ judge's noise (StopPolicy's ``switch``) and a better round exists: then ``src/`` is+ restored to that best round and its record is the base, so the session works from+ the best code and the best verdict's issues rather than from a worse attempt's.+ Measured 2026-09-09 (loop 22): 0.66 → 0.61 → 0.47 and 0.60 → 0.32, each refine+ building on the round before it, the regressions compounding while the best sat in+ git; the finalise restore then delivered r0 after two paid rounds of drift."""+ last = rounds[-1]+ best = ctx.state.best_round+ if strategy != "switch" or best is None or best >= len(rounds) or best == last.index:+ return last+ commit = rounds[best].commit+ if not commit or not ctx.ws.has_commit(commit):+ return last+ if ctx.ws.head() != commit or ctx.ws.changed_files():+ ctx.ws.restore(commit)+ ctx.ws.commit(f"restore best round r{best:02d} before refine")+ ctx.events.emit("round.refine_from_best", round=len(rounds), best=best, regressed=last.index,+ best_score=rounds[best].score, last_score=last.score)+ return rounds[best]+def _promote_best(self, ctx: RunContext, rounds: list[RoundRecord], index: int) -> None:"""Rank round ``index`` in (pairwise tie-break included), promote the best, save."""best = choose_best_round(ctx, rounds, BestSelector(), index)diff --git a/harness/docs/DECISIONS.md b/harness/docs/DECISIONS.mdindex d86330f4..655256b1 100644--- a/harness/docs/DECISIONS.md+++ b/harness/docs/DECISIONS.md@@ -1192,6 +1192,17 @@ written) that were accepted because the code works that way and the tests pin itthan none, because the judge repeats it — precision over recall, and every number names thesurface it was measured against.+* **D73 A refine after a regression builds on the best round, and the plan's cameras are+ repaired out of a blocked view (2026-09-09).** Loop 22: 0.66 → 0.61 → 0.47 and 0.60 → 0.32,+ each refine session handed the round before it while the best sat in git until finalise;+ and `PylonSlopeVista` stayed cut by a snow bank for three rounds because cameras belong to+ the plan and no session moved one. After StopPolicy's `switch` (a regression past the+ judge's noise) `src/` is restored to the best round and the tasks come from ITS verdict+ (`round.refine_from_best`); `repairCameraSpec` counts a lens staring at a surface+ (`near_rays`), a sightline cut before half the distance and a terrain overhead as "not+ clear" and searches back, up and sideways out of it. Same rule as D72's: the harness fixes+ what it can measure, deterministically, before a session is paid to guess.+## Rejected / deferred* A versioned `Spec`/`RunRecord`/`RunState` load-normaliser (rejected 2026-08-30: of the sevendiff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.mdindex 73456fa8..39d80662 100644--- a/harness/docs/INTERFACES.md+++ b/harness/docs/INTERFACES.md@@ -273,6 +273,8 @@ frame_gate_from_renders(renders) -> GateReport # gate "scene_frames"; da# render per GLB per camera, occlusion included) · hero_small_in_its_camera (WARN: < 2 % in the camera named for it)# Δ scene_placement stamped_ring (WARN): census groups[].stamps — per family of ≥ 8 copies {n, radius_m, radius_cv,# gap_cv, size_cv}; ≥ 8 same-size copies evenly on a ring at ≥ 0.6 × the plan's half-extent (host_census stampStats)+ # Δ census.camera_repair rows carry moved_side_m, blocked_before, cut_before, under_before (D73); the overview rig+ # (noFog views) hides see-through sky layers whose box lies below the eye; roomShell tags userData.placement='free'from codeverse.spatial.measure import measure_glb # link-hierarchy rule: metadata["links"] → each link is its own part# Δ Measurement.extra["complexity"] = ComplexityVector.model_dump() (additive, best-effort, never raises)from codeverse.spatial.complexity import (ComplexityVector, COMPLEXITY_WEIGHTS, COMPLEXITY_VERSION,diff --git a/harness/runtime_js/lib/host_metrics.mjs b/harness/runtime_js/lib/host_metrics.mjsindex 27cfccf5..66af9efd 100644--- a/harness/runtime_js/lib/host_metrics.mjs+++ b/harness/runtime_js/lib/host_metrics.mjs@@ -229,37 +229,62 @@ export function nearGeometry(scene, camera, THREE, limitM = 0.3, lookAt = null)* Pure: no renderer, raycasts only. `makeCam(spec)` is supplied by the host so* near/far/aspect match the real render exactly.*/+// [back, up, side] metres along the view axis, world up, and the camera's right; the search+// takes the first that clears. Sideways moves are what step out from behind a pillar or a+// snow bank — a retreat alone only backs into the same line of sight.const REPAIR_OFFSETS = [- [0, 0], [0, 0.5], [0.5, 0], [0.5, 0.5], [1, 0.5], [1, 1], [2, 1], [2, 2], [3, 2], [4, 2],+ [0, 0, 0], [0, 0.5, 0], [0.5, 0, 0], [0.5, 0.5, 0], [1, 0.5, 0], [1, 1, 0], [0, 1, 1.5], [0, 1, -1.5],+ [2, 1, 0], [1, 1.5, 2], [1, 1.5, -2], [2, 2, 0], [2, 2, 2.5], [2, 2, -2.5], [3, 2, 0], [3, 3, 3], [3, 3, -3], [4, 2, 0],];const REPAIR_CLEAR_M = 0.5;const EYE_ABOVE_GROUND_M = 1.6;+const REPAIR_BLOCKED_RAYS = 6; // of the 9 sight rays within BLOCKED_M: the frame is a surface+const REPAIR_CUT_FRAC = 0.5; // the line of sight to lookAt cut before this fraction of the distance++/** Is this lens clear: not in geometry, nothing within REPAIR_CLEAR_M, not staring at a surface,+ * and its line of sight to the plan's lookAt not cut short? */+function lensClear(n) {+ if (n.camera_in_geometry) return false;+ if (n.nearest_hit_m !== null && n.nearest_hit_m < REPAIR_CLEAR_M) return false;+ if (n.near_rays >= REPAIR_BLOCKED_RAYS) return false;+ if (n.target_hit_m !== null && n.target_distance_m && n.target_hit_m < REPAIR_CUT_FRAC * n.target_distance_m) return false;+ return true;+}export function repairCameraSpec(scene, spec, THREE, makeCam) {const dir = new THREE.Vector3(spec.position[0] - spec.lookAt[0], spec.position[1] - spec.lookAt[1], spec.position[2] - spec.lookAt[2]);if (dir.lengthSq() < 1e-9) dir.set(0, 0, 1);dir.normalize();- let before = null;+ const right = new THREE.Vector3().crossVectors(new THREE.Vector3(0, 1, 0), dir);+ if (right.lengthSq() < 1e-9) right.set(1, 0, 0);+ right.normalize();+ const lookAt = Array.isArray(spec.lookAt) ? spec.lookAt : null;// A lens under a ground surface (terrain overhead) is lifted to eye level above it first —// no backward retreat clears that, and the plan's camera is nobody else's to move.+ const before = nearGeometry(scene, makeCam(spec), THREE, undefined, lookAt);let lift = 0;let underBefore = '';- {- const n0 = nearGeometry(scene, makeCam(spec), THREE);- before = n0;- if (n0.ground_above_m !== null) { lift = n0.ground_above_m + EYE_ABOVE_GROUND_M; underBefore = n0.ground_above_name; }- }- for (const [back, up] of REPAIR_OFFSETS) {- const pos = [spec.position[0] + dir.x * back, spec.position[1] + dir.y * back + up + lift, spec.position[2] + dir.z * back];+ if (before.ground_above_m !== null) { lift = before.ground_above_m + EYE_ABOVE_GROUND_M; underBefore = before.ground_above_name; }+ // A lens staring at a surface (loop 22's crypt: 9 of 9 rays on a well 0.75 m away, a black+ // frame for a round) or whose line of sight to its subject is cut (loop 22's ski station: a+ // snow bank at 44 % of the way, three rounds of "the view is blocked" while no refine session+ // could move the plan's camera) is searched out of it the same way.+ const blockedBefore = before.near_rays >= REPAIR_BLOCKED_RAYS;+ const cutBefore = before.target_hit_m !== null && before.target_distance_m+ && before.target_hit_m < REPAIR_CUT_FRAC * before.target_distance_m ? before.target_hit_name : '';+ for (const [back, up, side] of REPAIR_OFFSETS) {+ const pos = [spec.position[0] + dir.x * back + right.x * side, spec.position[1] + dir.y * back + up + lift,+ spec.position[2] + dir.z * back + right.z * side];const candidate = { ...spec, position: pos };- const n = lift === 0 && back === 0 && up === 0 ? before : nearGeometry(scene, makeCam(candidate), THREE);- const clear = !n.camera_in_geometry && (n.nearest_hit_m === null || n.nearest_hit_m >= REPAIR_CLEAR_M);- if (clear) {- if (back === 0 && up === 0 && lift === 0) return null; // the authored camera is fine: no repair+ const authored = lift === 0 && back === 0 && up === 0 && side === 0;+ const n = authored ? before : nearGeometry(scene, makeCam(candidate), THREE, undefined, lookAt);+ if (lensClear(n)) {+ if (authored) return null; // the authored camera is fine: no repairreturn { spec: candidate, name: spec.name || '', moved_back_m: back, moved_up_m: +(up + lift).toFixed(3),- nearest_before: before.nearest_hit_m, inside_before: before.inside_mesh_bbox,- under_before: underBefore, nearest_after: n.nearest_hit_m };+ moved_side_m: side, nearest_before: before.nearest_hit_m, inside_before: before.inside_mesh_bbox,+ under_before: underBefore, blocked_before: blockedBefore, cut_before: cutBefore,+ nearest_after: n.nearest_hit_m };}}return null; // nothing within the retreat budget clears it: keep the authored shotdiff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjsindex 6a69337e..b2c42bc5 100644--- a/harness/runtime_js/lib/scene_host.mjs+++ b/harness/runtime_js/lib/scene_host.mjs@@ -21,6 +21,7 @@ import { sceneCensus } from './host_census.mjs';import { placementTable, settleScene } from './host_placement.mjs';import { frameStats, nearGeometry, repairCameraSpec } from './host_metrics.mjs';import { frameCoverage, glbCoverage } from './host_coverage.mjs';+import { classifyBackdrop, nonSolid } from './backdrop.mjs';import { installShaderErrorHook } from './host_shader_errors.mjs';import { attributeErrors, captured, captureMaterialSources, materialAudit } from './host_compile.mjs';import { makeRenderer, rendererString } from './browser/renderer.js';@@ -378,8 +379,10 @@ function buildCamera(spec) {try { fix = repairCameraSpec(state.scene, spec, THREE, buildCameraRaw); } catch (e) { fix = null; }state.repairedSpecs.set(key, fix ? fix.spec : null);if (fix) state.cameraRepairs.push({ name: fix.name, moved_back_m: fix.moved_back_m, moved_up_m: fix.moved_up_m,- nearest_before: fix.nearest_before, inside_before: fix.inside_before,- under_before: fix.under_before || '', nearest_after: fix.nearest_after });+ moved_side_m: fix.moved_side_m || 0, nearest_before: fix.nearest_before,+ inside_before: fix.inside_before, under_before: fix.under_before || '',+ blocked_before: !!fix.blocked_before, cut_before: fix.cut_before || '',+ nearest_after: fix.nearest_after });}const fixed = state.repairedSpecs.get(key);if (fixed) return buildCameraRaw(fixed);@@ -438,6 +441,27 @@ function renderOnce(cam) {try { const gl = state.renderer.getContext(); if (gl && gl.finish) gl.finish(); } catch (e) { /* ignore */ }}+/** Visible see-through meshes classified 'sky' (backdrop.mjs) whose whole box lies below `eye`. */+function skyLayersBelow(eye) {+ const out = [];+ const box = new THREE.Box3();+ state.scene.traverse((o) => {+ if (!(o.isMesh || o.isInstancedMesh) || !o.visible || !o.geometry || !nonSolid(o)) return;+ if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();+ if (o.geometry.boundingBox.isEmpty()) return;+ box.copy(o.geometry.boundingBox).applyMatrix4(o.matrixWorld);+ if (o.frustumCulled === false && o.geometry.isInstancedBufferGeometry) {+ // an instanced billboard deck keeps its quad at the origin and offsets it in the shader:+ // its instance offsets are the only honest extent+ const off = o.geometry.getAttribute('iOff');+ if (off) { box.makeEmpty(); for (let i = 0; i < off.count; i++) box.expandByPoint(new THREE.Vector3(off.getX(i), off.getY(i), off.getZ(i))); }+ }+ if (box.isEmpty() || box.max.y >= eye.y) return;+ if (classifyBackdrop(o, box) === 'sky' || /cloud|cumulus|cirrus/i.test(o.name || '')) out.push(o);+ });+ return out;+}+/** Render camera spec at time t; returns {dataUrl, ms}. */function renderAt(spec, t) {if (!state.booted) throw new Error('host not booted');@@ -447,10 +471,16 @@ function renderAt(spec, t) {const t0 = performance.now();const savedFog = state.scene.fog;if (spec.noFog) state.scene.fog = null; // overview rig: structure over atmosphere+ // …and no see-through sky layer under the lens: a billboard cloud deck seen from above+ // is a grid of white discs over the sea, and the judge read it as "a polka-dot sea+ // shader" on two lighthouse runs (2026-09-09). The authored cameras keep their clouds.+ const hiddenLayers = spec.noFog ? skyLayersBelow(cam.position) : [];+ for (const o of hiddenLayers) o.visible = false;try {renderOnce(cam);} finally {state.scene.fog = savedFog;+ for (const o of hiddenLayers) o.visible = true;}const ms = Math.round(performance.now() - t0);// the camera actually used: differs from spec.position when camera repair fireddiff --git a/harness/tests/orchestrator_tracks/test_round_economics.py b/harness/tests/orchestrator_tracks/test_round_economics.pyindex 606b4776..cad96852 100644--- a/harness/tests/orchestrator_tracks/test_round_economics.py+++ b/harness/tests/orchestrator_tracks/test_round_economics.py@@ -27,6 +27,7 @@ from codeverse.tracks.generation import (run_agent_task,turn_capped,)+from codeverse.tracks.lifecycle import BaseTrackfrom codeverse.tracks.static_object import StaticObjectTrackfrom codeverse.workspace import Workspacefrom tests.orchestrator_tracks.conftest import fake_clock, make_spec@@ -491,3 +492,31 @@ def test_a_run_past_its_hard_ceiling_cannot_start_another_session(tmp_ws):task=GenerationTask(label="baseline", prompt="p", round=0, kind="baseline"),budget=g)assert agent.jobs == [] # the treadmill ends BEFORE the agent is invoked+++# ----------------------------------------------------------------------------- refine from the best round+def test_a_refine_after_a_regression_restores_the_best_round_and_plans_from_its_verdict(tmp_path):+ """Loop 22 (2026-09-09): 0.66 → 0.61 → 0.47, each refine building on the round before it while+ the best sat in git. After StopPolicy's ``switch`` the working tree is the BEST round again+ and the tasks come from its verdict; a same-shape refine keeps building on the last round."""+ from types import SimpleNamespace++ from codeverse.workspace import Workspace++ ws = Workspace(tmp_path / "run").create()+ (ws.src / "scene.js").write_text("// r0: the good one\n")+ c0 = ws.commit("r00")+ (ws.src / "scene.js").write_text("// r1: the regression\n")+ c1 = ws.commit("r01")+ rounds = [_round(0, 0.66), _round(1, 0.47)]+ rounds[0].commit, rounds[1].commit = c0, c1+ events: list[dict] = []+ ctx = SimpleNamespace(ws=ws, state=SimpleNamespace(best_round=0), events=SimpleNamespace(emit=lambda name, **kw: events.append({"event": name, **kw})))+ same = BaseTrack._refine_base(ctx, rounds, "same")+ assert same is rounds[1] and ws.head() == c1 and not events # no regression: the last round+ base = BaseTrack._refine_base(ctx, rounds, "switch")+ assert base is rounds[0] and (ws.src / "scene.js").read_text() == "// r0: the good one\n"+ assert ws.head() != c1 and events[0]["event"] == "round.refine_from_best" and events[0]["best"] == 0 and events[0]["regressed"] == 1+ # the best IS the last round (nothing regressed past it): nothing to restore+ ctx.state.best_round = 1+ assert BaseTrack._refine_base(ctx, rounds, "switch") is rounds[1]diff --git a/harness/tests/scene_runtime/lib/test_room_shell.py b/harness/tests/scene_runtime/lib/test_room_shell.pyindex 50cf4a96..9ee423d1 100644--- a/harness/tests/scene_runtime/lib/test_room_shell.py+++ b/harness/tests/scene_runtime/lib/test_room_shell.py@@ -24,12 +24,13 @@ import { roomShell } from './lib/environment.js';const g = roomShell({ center: [0, 3, 0], extents: [14, 6, 16], thickness: 0.3,openings: [{ face: 'west', center: [8, 2.5], size: [6, 3] }] });const names = g.children.map((m) => m.name);+const placement = g.userData.placement;const box = new THREE.Box3().setFromObject(g);const west = g.children.filter((m) => m.name.startsWith('Wall_west'));// the opening: no west panel covers (x = -7.15, y = 2.5, z = 0) — 8 m along the face from z = -8const covered = west.some((m) => new THREE.Box3().setFromObject(m).containsPoint(new THREE.Vector3(-7.15, 2.5, 0)));const sill = west.some((m) => new THREE.Box3().setFromObject(m).containsPoint(new THREE.Vector3(-7.15, 0.5, 0)));-console.log(JSON.stringify({ names, min: box.min.toArray(), max: box.max.toArray(), westPanels: west.length, covered, sill,+console.log(JSON.stringify({ names, placement, min: box.min.toArray(), max: box.max.toArray(), westPanels: west.length, covered, sill,shadows: g.children.every((m) => m.castShadow && m.receiveShadow) }));"""@@ -42,6 +43,8 @@ def test_the_shell_is_walls_and_ceiling_on_the_bounds_faces_with_openings_cut():assert got["min"][0] == pytest.approx(-7.3, abs=1e-6) and got["max"][0] == pytest.approx(7.3, abs=1e-6)assert got["min"][1] == pytest.approx(0.0, abs=1e-6) and got["max"][1] == pytest.approx(6.3, abs=1e-6)assert got["shadows"]+ # the enclosure is not a placed thing (loop 22's crypt: "RoomShell floating 39.8 m" over a sunk terrain)+ assert got["placement"] == "free", gotdef test_the_skeleton_env_carries_the_shell_only_for_an_interior_plan():diff --git a/harness/tests/scene_runtime/test_camera_repair.py b/harness/tests/scene_runtime/test_camera_repair.pyindex 65bfd390..141ee340 100644--- a/harness/tests/scene_runtime/test_camera_repair.py+++ b/harness/tests/scene_runtime/test_camera_repair.py@@ -42,7 +42,15 @@ scene.updateMatrixWorld(true);const buried = { name: 'SlipwaySurge', position: [5, 1.6, -40], lookAt: [0, 4.0, -30], fov: 45 };const lifted = repairCameraSpec(scene, buried, THREE, makeCam);const liftedAfter = lifted ? nearGeometry(scene, makeCam(lifted.spec), THREE) : null;-console.log(JSON.stringify({ fix, after, noFix, lifted, liftedAfter }));+// a squat pillar 0.8 m before the lens, the subject 4 m behind it (loop 22's crypt: 9 of 9 rays on a+// well, a black frame): stepped out of it sideways / up, and the line of sight to lookAt is open after+const pillar = new THREE.Mesh(new THREE.BoxGeometry(1.2, 3.2, 1.2), mat);+pillar.name = 'StonePillar_3'; pillar.position.set(20, 1.6, 18.6); scene.add(pillar);+scene.updateMatrixWorld(true);+const staring = { name: 'AthanorDetail', position: [20, 1.6, 20], lookAt: [20, 1.2, 16], fov: 45 };+const stepped = repairCameraSpec(scene, staring, THREE, makeCam);+const steppedAfter = stepped ? nearGeometry(scene, makeCam(stepped.spec), THREE, undefined, staring.lookAt) : null;+console.log(JSON.stringify({ fix, after, noFix, lifted, liftedAfter, stepped, steppedAfter }));"""@@ -71,3 +79,11 @@ def test_a_lens_under_a_ground_surface_is_lifted_to_eye_level_above_it(result):assert abs(lifted["spec"]["position"][1] - (3.0 + 1.6)) < 1e-6, lifted # terrain at 3 m + 1.6 m eyeafter = result["liftedAfter"]assert after["ground_above_m"] is None and abs(after["ground_below_m"] - 1.6) < 1e-3, after+++def test_a_lens_staring_at_a_surface_is_stepped_out_of_it_and_its_line_of_sight_opened(result):+ stepped = result["stepped"]+ assert stepped is not None and stepped["blocked_before"] is True and stepped["cut_before"] == "StonePillar_3", stepped+ after = result["steppedAfter"]+ assert after["near_rays"] < 6 and not after["camera_in_geometry"], after+ assert after["target_hit_m"] is None or after["target_hit_m"] >= 0.5 * after["target_distance_m"], after