Skip to content

Official Codebase of 3DCodeVerse

Python

b10: ledger/guard agree on zone-layout, copied runs read themselves, tools filter by track

gaoypeng52edf902025e
diff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.py
index 9a3cf85a..d3ffd5a0 100644
--- a/harness/codeverse/agents/materialize.py
+++ b/harness/codeverse/agents/materialize.py
@@ -61,7 +61,7 @@ GEMINI_CONTEXT_SETTINGS = {"fileFiltering": {"respectGitIgnore": False, "respect
# --------------------------------------------------------------------------- body
-def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str]) -> str:
+def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str], ws: Workspace | None = None) -> str:
if not spatial_tools:
return (
"## Spatial tools\n\n"
@@ -69,9 +69,23 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str])
"code carefully and keeping every dimension explicit; the harness builds, measures "
"and renders after you finish.\n"
)
- from codeverse.spatial.registry import tool_cards
+ from codeverse.spatial.registry import list_tools
- cards = tool_cards() or "(the tool registry is empty in this environment)"
+ # the same track/language filter the MCP server applies (mcp_server.build_context):
+ # this file is agy's ONLY tool documentation and its shell fallback is unscoped, so
+ # documenting the whole registry taught scene/graphics agents dead-end object tools
+ track = language = ""
+ if ws is not None and ws.spec_path.is_file():
+ try:
+ spec = json.loads(ws.spec_path.read_text())
+ track, language = str(spec.get("track", "")), str(spec.get("language", ""))
+ except (OSError, json.JSONDecodeError) as e:
+ log.warning("could not read %s for tool filtering: %s", ws.spec_path, e)
+ tools = list_tools(track=track, language=language)
+ names = {t.name for t in tools}
+ cards = "\n".join(t.card() for t in tools) or "(the tool registry is empty in this environment)"
+ look = [n for n in ("render_views", "render_sheet", "scene_views", "gl_frames") if n in names]
+ prove = [n for n in ("measure", "check_contract", "scene_probe", "gl_probe") if n in names]
if agent_kind == "claude-code":
how = "Tools are exposed by the MCP server `3dcv`; their names appear as `mcp__c3v__<name>` (e.g. `mcp__c3v__build`)."
elif agent_kind == "agy":
@@ -87,17 +101,22 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str])
)
else:
how = f"Tools are exposed by the MCP server `{MCP_SERVER_NAME}` (command: `{' '.join(mcp_command)}`); call them by name."
+ workflow = (
+ "Workflow: edit → `build` → read the errors/numbers → fix → `build` again."
+ + (f" Use {' / '.join(f'`{n}`' for n in look)} to LOOK at what you made before declaring it finished;" if look else "")
+ + (f" use {' / '.join(f'`{n}`' for n in prove)} to prove it." if prove else "")
+ + " Never finish on a failing build."
+ )
return (
"## Spatial tools (3dcv)\n\n"
f"{how}\n\n"
- "Workflow: edit → `build` → read the errors/numbers → fix → `build` again. Use `render_views` / "
- "`render_sheet` to LOOK at what you made before declaring it finished; use `measure` / "
- "`check_contract` to prove dimensions. Never finish on a failing build.\n\n"
+ f"{workflow}\n\n"
f"{cards}\n"
)
-def _body(agent_kind: str, contract_md: str, cookbook_note: str, spatial_tools: bool, mcp_command: list[str]) -> str:
+def _body(agent_kind: str, contract_md: str, cookbook_note: str, spatial_tools: bool, mcp_command: list[str],
+ ws: Workspace | None = None) -> str:
return (
"# 3dcv workspace — rules for the coding agent\n\n"
"You are working inside a harness-managed workspace. Read this whole file before acting.\n\n"
@@ -112,7 +131,7 @@ def _body(agent_kind: str, contract_md: str, cookbook_note: str, spatial_tools:
"4. Keep dimensions explicit and in meters; follow the coordinate frame stated in the contract.\n"
"5. When you are done, reply with a SHORT summary of what you changed and what you verified. "
"Do not ask questions — there is no human in the loop; make a reasonable decision and proceed.\n\n"
- f"{_tool_section(agent_kind, spatial_tools, mcp_command)}\n"
+ f"{_tool_section(agent_kind, spatial_tools, mcp_command, ws)}\n"
f"## Cookbook\n\n{cookbook_note}\n\n"
f"## Language contract\n\n{contract_md.strip()}\n"
)
@@ -217,7 +236,7 @@ def materialize_workspace(
log.warning("cookbook not found: %r — the %s session gets the contract only", cookbook_rel, agent_kind)
cookbook_note = "No cookbook is available in this session; rely on the contract below."
- body = _body(agent_kind, contract_md, cookbook_note, spatial_tools, mcp_command)
+ body = _body(agent_kind, contract_md, cookbook_note, spatial_tools, mcp_command, ws)
for name in ("AGENTS.md", "GEMINI.md", "CLAUDE.md"):
(ws.root / name).write_text(body)
diff --git a/harness/codeverse/cost/types.py b/harness/codeverse/cost/types.py
index 574c2484..07d13442 100644
--- a/harness/codeverse/cost/types.py
+++ b/harness/codeverse/cost/types.py
@@ -80,6 +80,9 @@ _LABEL_STAGES: tuple[tuple[str, Stage], ...] = (
("detail", Stage.REFINE),
("candidate", Stage.CANDIDATE),
("cand", Stage.CANDIDATE),
+ # the zone-layout planner calls (tracks/zone_layout.py) charge the guard as "plan";
+ # unclassified, their ledger rows said other/other while the guard said plan
+ ("zone-layout", Stage.PLAN),
("plan", Stage.PLAN),
("judge", Stage.JUDGE),
("texture", Stage.TEXTURE),
diff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.py
index 4aca02bf..93328c47 100644
--- a/harness/codeverse/spatial/tools.py
+++ b/harness/codeverse/spatial/tools.py
@@ -241,12 +241,18 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
return text_observation(lines, ok=ok, numbers=numbers, limit=3000)
+#: the object-GLB toolset (everything that reads artifacts/object.glb): scene and
+#: graphics builds never write that file, so serving these there was a dead-end loop
+_OBJECT_TRACKS = (Track.STATIC_OBJECT.value, Track.ARTICULATED_OBJECT.value)
+
+
# --------------------------------------------------------------------------- measure
class MeasureArgs(BaseModel):
parts: list[str] = Field(default=[], description="limit the table to these part names (empty = all)")
-@tool("measure", MeasureArgs, "Measure the built object: overall bbox/extents, ground gap, per-part size/tris/islands (Y-up meters).")
+@tool("measure", MeasureArgs, "Measure the built object: overall bbox/extents, ground gap, per-part size/tris/islands (Y-up meters).",
+ tracks=_OBJECT_TRACKS)
def measure(ctx: ToolContext, args: MeasureArgs) -> Observation:
glb = glb_path(ctx)
try:
@@ -268,7 +274,8 @@ def measure(ctx: ToolContext, args: MeasureArgs) -> Observation:
# --------------------------------------------------------------------------- gates
-@tool("check_connectivity", NoArgs, "Contact graph of all parts: floating parts (with the exact gap vector to close), interpenetration, stray islands.")
+@tool("check_connectivity", NoArgs, "Contact graph of all parts: floating parts (with the exact gap vector to close), interpenetration, stray islands.",
+ tracks=_OBJECT_TRACKS)
def check_connectivity(ctx: ToolContext, args: NoArgs) -> Observation:
glb = glb_path(ctx)
plan = load_plan(ctx.workspace.plan_path) if ctx.workspace.plan_path.is_file() else None
@@ -281,7 +288,8 @@ def check_connectivity(ctx: ToolContext, args: NoArgs) -> Observation:
return gate_observation(report)
-@tool("check_contract", NoArgs, "Compare the built object with plan.json: missing parts, bbox deltas per part, overall size, ground contact.")
+@tool("check_contract", NoArgs, "Compare the built object with plan.json: missing parts, bbox deltas per part, overall size, ground contact.",
+ tracks=_OBJECT_TRACKS)
def check_contract(ctx: ToolContext, args: NoArgs) -> Observation:
glb = glb_path(ctx)
plan = load_plan(ctx.workspace.plan_path)
@@ -302,7 +310,8 @@ class CrossSectionArgs(BaseModel):
parts: list[str] = Field(default=[], description="only slice these parts (empty = all)")
-@tool("cross_section", CrossSectionArgs, "Slice the object with an axis-aligned plane → labelled section image + loops/area/hollow ratio.")
+@tool("cross_section", CrossSectionArgs, "Slice the object with an axis-aligned plane → labelled section image + loops/area/hollow ratio.",
+ tracks=_OBJECT_TRACKS)
def cross_section(ctx: ToolContext, args: CrossSectionArgs) -> Observation:
glb = glb_path(ctx)
axis = args.axis.lower()
@@ -341,7 +350,8 @@ def _render(ctx: ToolContext, tool_name: str, *, views: list[str], mode: str, is
return render_observation(rs, ctx.workspace.root, note=note)
-@tool("render_views", RenderViewsArgs, "Render the built object from named camera views (contact sheet + views). Use to SEE what you built.", cost_hint="slow")
+@tool("render_views", RenderViewsArgs, "Render the built object from named camera views (contact sheet + views). Use to SEE what you built.",
+ tracks=_OBJECT_TRACKS, cost_hint="slow")
def render_views(ctx: ToolContext, args: RenderViewsArgs) -> Observation:
note = f"{args.mode} render" + (f", isolate={args.isolate}" if args.isolate else "") + (f", explode={args.explode:g}" if args.explode else "")
return _render(ctx, "render_views", views=args.views, mode=args.mode, isolate=args.isolate, explode=args.explode, size=args.size, note=note)
@@ -351,7 +361,8 @@ class RenderSheetArgs(BaseModel):
mode: str = Field(default="shaded", description=_MODE_DESC)
-@tool("render_sheet", RenderSheetArgs, "One labelled 14-view contact sheet of the built object (all canonical views).", cost_hint="slow")
+@tool("render_sheet", RenderSheetArgs, "One labelled 14-view contact sheet of the built object (all canonical views).",
+ tracks=_OBJECT_TRACKS, cost_hint="slow")
def render_sheet(ctx: ToolContext, args: RenderSheetArgs) -> Observation:
obs = _render(ctx, "render_sheet", views=[v.name for v in OBJECT_VIEWS], mode=args.mode, isolate=[], explode=0.0, size=512,
note=f"{args.mode} 14-view sheet")
@@ -365,7 +376,8 @@ class IsolateArgs(BaseModel):
views: list[str] = Field(default=list(_DEFAULT_VIEWS), description="view names")
-@tool("isolate", IsolateArgs, "Render ONE part alone (others hidden) + its measurement row — inspect a single part's shape and placement.", cost_hint="slow")
+@tool("isolate", IsolateArgs, "Render ONE part alone (others hidden) + its measurement row — inspect a single part's shape and placement.",
+ tracks=_OBJECT_TRACKS, cost_hint="slow")
def isolate(ctx: ToolContext, args: IsolateArgs) -> Observation:
glb = glb_path(ctx)
try:
@@ -400,7 +412,8 @@ class CompareSilhouetteArgs(BaseModel):
reference_index: int = Field(default=0, ge=0, description="index into spec.references")
-@tool("compare_silhouette", CompareSilhouetteArgs, "Silhouette IoU / aspect-ratio error between a rendered view and a reference image (+ diff image).", cost_hint="slow")
+@tool("compare_silhouette", CompareSilhouetteArgs, "Silhouette IoU / aspect-ratio error between a rendered view and a reference image (+ diff image).",
+ tracks=_OBJECT_TRACKS, cost_hint="slow")
def compare_silhouette(ctx: ToolContext, args: CompareSilhouetteArgs) -> Observation:
glb = glb_path(ctx)
ref_path, _ref = reference_path(ctx, args.reference_index, tool="compare_silhouette")
@@ -650,9 +663,6 @@ def gl_frames(ctx: ToolContext, args: GlFramesArgs) -> Observation:
# ===================================================================== texturing
-_OBJECT_TRACKS = (Track.STATIC_OBJECT.value, Track.ARTICULATED_OBJECT.value)
-
-
class TexturePassArgs(BaseModel):
judge: bool = Field(default=True, description="run the before/after VLM ship gate (False = ship on seam gate only)")
model: str = Field(default="", description="planner chat model id for the material plan (default: spec planner)")
@@ -754,7 +764,7 @@ class CompareReferenceArgs(BaseModel):
@tool("compare_reference", CompareReferenceArgs,
"Put the REFERENCE image and a render of your object side by side (+ outline diff and IoU). Use it to check "
- "you built the right thing: part inventory, counts, proportions, profiles.", cost_hint="slow")
+ "you built the right thing: part inventory, counts, proportions, profiles.", tracks=_OBJECT_TRACKS, cost_hint="slow")
def compare_reference(ctx: ToolContext, args: CompareReferenceArgs) -> Observation:
glb = glb_path(ctx)
ref_path, ref = reference_path(ctx, args.reference_index, tool="compare_reference")
diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.py
index c65ba717..ad553bc6 100644
--- a/harness/codeverse/workspace.py
+++ b/harness/codeverse/workspace.py
@@ -124,22 +124,24 @@ class Workspace:
the breakage partial and therefore silent.
Relative paths join the root (what the old ``_judge.resolve_paths`` did, and the
- only case it handled). An absolute path that still exists is returned as-is. An
- absolute path that does NOT exist is re-rooted by finding its longest trailing
- segment that does exist under this root — the run was moved, so the tail is
- intact even though the prefix is not. Nothing matches: the original is returned
- so the caller reports a real missing file rather than a silently wrong one.
+ only case it handled). An absolute path under another root is re-rooted FIRST,
+ by its longest trailing segment that exists under this root — for a moved run the
+ tail is intact even though the prefix is not, and for a COPIED/rsynced run this
+ workspace's own file must win even while the original still exists (readers used
+ to read, and a retexture to write past, the original's files until that directory
+ was deleted). A path already under this root, or with no local tail match, is
+ returned as-is — an existing original still resolves, and a missing one is
+ reported as a real missing file rather than a silently wrong one.
"""
p = Path(stored)
if not p.is_absolute():
return self.root / p
- if p.exists():
- return p
- parts = p.parts
- for i in range(1, len(parts)):
- candidate = self.root.joinpath(*parts[i:])
- if candidate.exists():
- return candidate
+ if not p.is_relative_to(self.root):
+ parts = p.parts
+ for i in range(1, len(parts)):
+ candidate = self.root.joinpath(*parts[i:])
+ if candidate.exists():
+ return candidate
return p
@property
diff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.py
index d91cef7b..d1b20473 100644
--- a/harness/tests/agents/test_materialize.py
+++ b/harness/tests/agents/test_materialize.py
@@ -29,6 +29,28 @@ def test_writes_three_bodies_same_content(tmp_ws: Workspace):
assert "Spatial tools (3dcv)" in body
+def test_bodies_document_only_this_tracks_tools(tmp_ws: Workspace):
+ """AGENTS.md used to list all 19 tools + the object workflow for every track — for
+ agy (no MCP) this file is the ONLY tool documentation and its shell fallback is
+ unscoped, so scene/graphics agents were taught dead-end object-GLB tools (V11a)."""
+ tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "scene", "language": "scene_threejs", "prompt": "p"}))
+ _mat(tmp_ws, kind="agy")
+ body = (tmp_ws.root / "AGENTS.md").read_text()
+ for absent in ("`joint_sweep`", "`gl_probe`", "`texture_pass`", "`render_sheet`", "`check_contract`", "`cross_section`"):
+ assert absent not in body, absent
+ assert "`scene_views`" in body and "`scene_probe`" in body and "`build`" in body
+ assert "check_contract` to prove" not in body, "the object workflow sentence must not survive filtering"
+ # an object workspace keeps the full object toolset and its workflow sentence
+ tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "static_object", "language": "blender", "prompt": "p"}))
+ _mat(tmp_ws, kind="agy")
+ body = (tmp_ws.root / "AGENTS.md").read_text()
+ assert "`render_sheet`" in body and "`measure`" in body and "`check_contract`" in body
+ # no spec.json (bare workspaces in tests/tools): unfiltered fallback, nothing crashes
+ tmp_ws.spec_path.unlink()
+ _mat(tmp_ws, kind="agy")
+ assert "`joint_sweep`" in (tmp_ws.root / "AGENTS.md").read_text()
+
+
def test_no_mcp_server_is_written_into_the_workspace(tmp_ws: Workspace):
"""Only the ``context`` block goes into the agent-writable ws/.gemini/settings.json;
3dcv reaches each CLI through a harness-owned per-session file (audit 2026-08-27)."""
diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.py
index 56aaa619..ba548617 100644
--- a/harness/tests/core/test_run_layout.py
+++ b/harness/tests/core/test_run_layout.py
@@ -142,6 +142,29 @@ def test_a_relocated_run_still_resolves_its_stored_paths(tmp_path):
assert ws.rebase(str(missing)) == missing
+def test_a_copied_run_reads_its_own_files_while_the_original_still_exists(tmp_path):
+ """rebase returned any stored absolute path that still EXISTED as-is, so a
+ copied/rsynced run silently read — and a retexture wrote past — the ORIGINAL's
+ files for as long as that directory lived (V10f). This root's copy must win."""
+ import shutil
+
+ from codeverse.workspace import Workspace
+
+ a = tmp_path / "A" / "run1"
+ (a / "artifacts" / "renders" / "r01").mkdir(parents=True)
+ sheet_a = a / "artifacts" / "renders" / "r01" / "sheet.png"
+ sheet_a.write_bytes(b"ORIGINAL")
+ b = tmp_path / "B" / "run1"
+ b.parent.mkdir(parents=True)
+ shutil.copytree(a, b) # copy: the original stays alive
+ (b / "artifacts" / "renders" / "r01" / "sheet.png").write_bytes(b"COPY")
+ got = Workspace(b).rebase(str(sheet_a))
+ assert got == b / "artifacts" / "renders" / "r01" / "sheet.png"
+ assert got.read_bytes() == b"COPY", "the copy's own file must win over the live original"
+ # ...and a path already under THIS root is untouched, existing or not
+ assert Workspace(a).rebase(str(sheet_a)) == sheet_a
+
+
def test_show_prints_the_sheet_that_exists_after_a_move(tmp_path):
"""The user-visible half: `3dcv show` must not print a path that is not there."""
from codeverse.cli._common import print_record_summary
diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.py
index 7f98289b..854fb09c 100644
--- a/harness/tests/cost/test_instrument.py
+++ b/harness/tests/cost/test_instrument.py
@@ -442,6 +442,20 @@ def test_a_hedge_losers_tokens_reach_the_ledger_when_it_lands(tmp_path: Path):
logical.cost_usd + loser.cost_usd), "the loser is in the total exactly once"
+def test_zone_layout_rows_agree_with_the_guard(tmp_path: Path):
+ """tracks/zone_layout.py labels its planner calls 'zone-layout' and charges the
+ guard as stage='plan' — unclassified, the ledger filed the same dollars under
+ other/other, so the two owners disagreed on every zone-layout cent (V10c)."""
+ from codeverse.cost.types import role_for_stage, stage_for_label
+
+ assert stage_for_label("zone-layout") is Stage.PLAN
+ assert role_for_stage(stage_for_label("zone-layout")) is Role.PLANNER
+ with run_ledger(tmp_path, run="r1"):
+ record_call(_usage(cost_usd=0.02), label="zone-layout")
+ row, = load_ledger(tmp_path)
+ assert row.stage is Stage.PLAN and row.role is Role.PLANNER
+
+
def test_a_late_hedge_loser_keeps_its_stage_role_and_round(tmp_path: Path):
"""The loser lands AFTER generate() returned, from its own thread with empty
contextvars: its 'extra' row used to fall back to what the label alone says
diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.py
index 4b5106da..1105e804 100644
--- a/harness/tests/spatial_tools/test_tools.py
+++ b/harness/tests/spatial_tools/test_tools.py
@@ -47,6 +47,14 @@ def test_registry_has_every_tool() -> None:
assert not {"texture_pass", "texture_preview"} & {t.name for t in list_tools(track="scene")}
graphics = {t.name for t in list_tools(track="graphics", language="glsl_shader")}
assert {"gl_probe", "gl_frames"} <= graphics and "texture_pass" not in graphics and "scene_probe" not in graphics
+ # V11a: the object-GLB toolset never reaches scene/graphics agents — their builds
+ # never write artifacts/object.glb, so every one of these was a dead-end refusal
+ object_glb_tools = {"measure", "check_connectivity", "check_contract", "cross_section", "isolate",
+ "render_views", "render_sheet", "compare_silhouette", "compare_reference"}
+ assert not object_glb_tools & scene and not object_glb_tools & graphics
+ assert "build" in scene and "build" in graphics # build itself stays universal
+ articulated = {t.name for t in list_tools(track="articulated_object", language="urdf_blender")}
+ assert object_glb_tools | {"joint_sweep"} <= articulated # articulated keeps the object toolset
texture_card = get_tool("texture_pass").card()
assert "judge" in texture_card and "texture_pass" in texture_card
for t in list_tools():