Skip to content

Official Codebase of 3DCodeVerse

Python

D110: objects are baseline-first — one session drafts the whole object, each round one session edits it in place

gaoypeng924c442d8b33
diff --git a/harness/codeverse3d/agents/backends.py b/harness/codeverse3d/agents/backends.py
index 7c499662..5a6d1665 100644
--- a/harness/codeverse3d/agents/backends.py
+++ b/harness/codeverse3d/agents/backends.py
@@ -329,7 +329,7 @@ class ClaudeCodeAgent(_CliAgent):
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,
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,
+ 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", ""),
model_usage=(env or {}).get("modelUsage", {}),
usage_from="envelope" if env else "stream messages" if stream.messages else "none",
@@ -533,7 +533,7 @@ class CodexAgent(_CliAgent):
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,
- rc=proc.rc, killed_reason=proc.killed_reason, thread_id=events.thread_id,
+ 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,
)
finally:
@@ -542,12 +542,14 @@ class CodexAgent(_CliAgent):
# ===================================================================== antigravity
-def api_model_effort(model: str) -> tuple[str, str]:
- """``gemini-4-argon-low`` → ``('gemini-4-argon', 'low')``; a bare id runs at ``AGY_API_EFFORT``."""
+def api_model_effort(model: str, asked: str | None = None) -> tuple[str, str]:
+ """``gemini-4-argon-low`` → ``('gemini-4-argon', 'low')``. Precedence: the model id's
+ ``-low/-medium/-high`` suffix, then ``asked`` (``AgentJob.effort`` — a caller's explicit ask),
+ then ``AGY_API_EFFORT``. No caller asks today, so a bare id runs at high (owner, 2026-10-15)."""
for effort in EFFORTS:
if model.endswith(f"-{effort}"):
return model[: -len(effort) - 1], effort
- return model, AGY_API_EFFORT
+ return model, asked or AGY_API_EFFORT
def parse_agy_json(stdout: str) -> dict[str, Any] | None:
@@ -575,8 +577,9 @@ AGY_API_SETTINGS = {"modelProvider": "gemini"}
#: key serves, listed by ``agy models`` or not (gemini-4-argon) — and ``--effort`` sets its
#: thinking level (low → 1, high → 3 in the CLI log, 2026-10-13)
AGY_API_SCHEME = "gemini-api://"
-#: the effort an API-mode id without a ``-low/-medium/-high`` suffix runs at: the Gemini API's
-#: own default thinking level
+#: the effort an API-mode id without a ``-low/-medium/-high`` suffix runs at when the job asks for
+#: none (``AgentJob.effort`` is None): the Gemini API's own default thinking level. Every track's
+#: argon sessions run here — owner, 2026-10-15: "argon 强度就直接设置high" (D110)
AGY_API_EFFORT = "high"
#: the model an ``agy`` generator with no model runs (owner, 2026-10-13)
DEFAULT_AGY_MODEL = "gemini-4-argon"
@@ -765,9 +768,12 @@ class AntigravityAgent(_CliAgent):
"""The API model id the session is booked under (the effort suffix stripped)."""
return api_model_effort(self.model)[0]
- def model_args(self) -> list[str]:
- name, effort = api_model_effort(self.model)
- return ["--model", f"{AGY_API_SCHEME}{name}", "--effort", effort]
+ def effort_for(self, job: AgentJob) -> str:
+ """The ``--effort`` this job's session runs at (:func:`api_model_effort`)."""
+ return api_model_effort(self.model, job.effort)[1]
+
+ def model_args(self, job: AgentJob) -> list[str]:
+ return ["--model", f"{AGY_API_SCHEME}{self.served_model()}", "--effort", self.effort_for(job)]
def build_argv(self, s: Session) -> list[str]:
"""No ``--print``: agy reads the prompt from a piped stdin, byte for byte, and still
@@ -780,7 +786,7 @@ class AntigravityAgent(_CliAgent):
return [self.binary, "--dangerously-skip-permissions",
"--print-timeout", f"{minutes}m", "--output-format", "json",
"--add-dir", str(s.ws.root), "--disable-slash-commands", "--log-file", str(s.traj.dir / AGY_LOG),
- *self.model_args()]
+ *self.model_args(s.job)]
def build_home(self, s: Session) -> Path:
"""A fresh HOME for one session: the API-mode settings and, when the job has
@@ -836,8 +842,9 @@ class AntigravityAgent(_CliAgent):
except KeyPoolExhausted as e: # every key throttled for the whole wait budget
return failed(s, "budget", f"Gemini key pool exhausted: {e}")
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, key_tail=key[-4:])
+ 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 ""))
@@ -872,7 +879,7 @@ class AntigravityAgent(_CliAgent):
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,
provider_wait_s=provider_wait([(t, b) for t, b, _ in retries], ended),
- rc=proc.rc, killed_reason=proc.killed_reason, agy_error=died,
+ 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),
)
finally:
diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.py
index ef263d96..c7de387e 100644
--- a/harness/codeverse3d/agents/cli_common.py
+++ b/harness/codeverse3d/agents/cli_common.py
@@ -486,13 +486,15 @@ def finish_session(
quota: bool = False,
provider_wait_s: float = 0.0,
usage_estimated: bool = False,
+ effort: str = "",
**extra: Any,
) -> AgentResult:
"""Commit the agent's work, compute ``files_changed`` via git (attributed to this
session — see :func:`attribute_changes`), write result.json. ``turns`` is the
backend's own count (``AgentResult.turns``); ``transient`` / ``quota`` its typed
failure class and ``provider_wait_s`` the time its CLI lost to provider errors
- (:func:`provider_wait`); ``extra`` lands in result.json only.
+ (:func:`provider_wait`); ``effort`` what the backend passed its CLI (``AgentResult.effort``);
+ ``extra`` lands in result.json only.
Write scope is enforced here for the CLI backends (they have no write-time gate):
writes outside ``write_roots`` (and, for ``edit_only``, outside ``files_hint``) are
@@ -517,7 +519,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,
- usage_estimated=usage_estimated,
+ 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,
head_before=s.head_before, head_after=s.ws.head(), notes=s.notes, **extra)
@@ -575,7 +577,7 @@ def invoke(
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,
- plus ``invoke_extra`` (agy in API mode adds ``model`` and ``key_tail``).
+ plus ``invoke_extra`` (agy in API mode adds ``model``, the ``effort`` it passed and ``key_tail``).
"""
soft = float(s.job.timeout_s)
hard = soft + HARD_GRACE_S
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index 455ca5b7..a00a504f 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -334,8 +334,6 @@ class Settings(BaseSettings):
"(object tracks)")
plan_restart: Flag = Field(default=True, description="re-sample a degenerate plan from the original "
"prompt instead of editing it in context (docs/COST.md §30)")
- scoped_parts: Flag = Field(default=True, description="per-part scoped baseline sessions for an object "
- "of 8+ parts")
reference_diff: Flag = Field(default=True, description="the judge's reference-image mismatch pass")
zone_layouts: Flag = Field(default=True, description="scene track: the L2 zone-layout planner calls")
scene_textures: Flag = Field(default=False, description="scene track: generate a texture pack before "
diff --git a/harness/codeverse3d/contracts/agent.py b/harness/codeverse3d/contracts/agent.py
index 82553041..ad1c538b 100644
--- a/harness/codeverse3d/contracts/agent.py
+++ b/harness/codeverse3d/contracts/agent.py
@@ -8,6 +8,8 @@ runtimes, ``agents/cli_common.hardened_env`` for the coding-agent CLIs).
from __future__ import annotations
+from typing import Literal
+
from pydantic import BaseModel, Field
from codeverse3d.contracts.common import Usage
@@ -15,6 +17,9 @@ from codeverse3d.contracts.common import Usage
#: one agent session's wall clock — ``Settings.limits.agent_timeout_s`` defaults to it
AGENT_TIMEOUT_S = 1800
+#: the thinking effort a caller may ask an agent session for (``AgentJob.effort``)
+AgentEffort = Literal["low", "medium", "high"]
+
class FileChange(BaseModel):
path: str
@@ -35,6 +40,13 @@ class AgentJob(BaseModel):
"remaining hard clock before queuing. Shared by retries; recomputed on resume. "
"None preserves the standalone CLI's session grace",
)
+ effort: AgentEffort | None = Field(
+ default=None,
+ description="the thinking effort a caller explicitly asked for (GenerationTask.thinking); None = the "
+ "backend's own default. Read by agy only (``--effort``; a ``-low/-medium/-high`` model suffix still "
+ "wins, and with neither the session runs at AGY_API_EFFORT = high — owner, 2026-10-15). claude-code "
+ "and codex take their effort from Settings.agents (claude_effort / codex_reasoning_effort) and ignore it",
+ )
#: consumed only by claude-code (``--max-turns``); codex / agy have no
#: turn flag and run unbounded except by ``timeout_s`` and the run's wall clock
max_turns: int = 60
@@ -101,6 +113,9 @@ class AgentResult(BaseModel):
"killed before its turn completed reports none (backends.CodexEvents.estimated_usage); its ledger "
"row says source=\"estimate\"",
)
+ effort: str = Field(
+ default="", description="the effort the backend actually passed its CLI (agy ``--effort``, claude-code "
+ "``--effort``, codex ``model_reasoning_effort``); '' = none passed, the CLI's own default")
tool_calls: int = 0
turns: int = Field(
default=0, description="model turns as the backend counts them (claude-code num_turns, codex "
diff --git a/harness/codeverse3d/contracts/artifacts.py b/harness/codeverse3d/contracts/artifacts.py
index 88f64cd7..321917ee 100644
--- a/harness/codeverse3d/contracts/artifacts.py
+++ b/harness/codeverse3d/contracts/artifacts.py
@@ -43,6 +43,12 @@ class LintKind(StrEnum):
CENSUS = "census" # INFO: what the lint saw
+#: ``GateFinding.data["kind"]`` of a plan part that is still the skeleton's placeholder box
+#: (``spatial.contract``, D110) — the one gate ERROR the next refine round puts ahead of every
+#: other (``orchestrator.build_refine_instructions``): nothing else about a part matters until it exists
+PLACEHOLDER_PART = "placeholder_part"
+
+
class GateFinding(BaseModel):
gate: str
severity: Severity
diff --git a/harness/codeverse3d/cost/instrument.py b/harness/codeverse3d/cost/instrument.py
index 69c8b81e..47aab454 100644
--- a/harness/codeverse3d/cost/instrument.py
+++ b/harness/codeverse3d/cost/instrument.py
@@ -239,7 +239,9 @@ class MeteredAgent(_Proxy):
outcome="ok" if result.ok else (result.exit_reason or "error"),
latency_ms=usage.latency_ms or ms,
n_calls=max(1, int(result.tool_calls or 1)),
- source="estimate" if result.usage_estimated else "session")
+ source="estimate" if result.usage_estimated else "session",
+ # the effort the CLI was given (agy --effort): a loop splits by it (D110)
+ **({"effort": result.effort} if result.effort else {}))
except Exception as e: # pragma: no cover
log.debug("cost: could not record agent session %s: %s", job.label, e)
diff --git a/harness/codeverse3d/orchestrator.py b/harness/codeverse3d/orchestrator.py
index 46cea34e..099b2b28 100644
--- a/harness/codeverse3d/orchestrator.py
+++ b/harness/codeverse3d/orchestrator.py
@@ -22,7 +22,7 @@ from typing import Any, Literal, TypeVar
from pydantic import BaseModel, Field, ValidationError
-from codeverse3d.contracts.artifacts import GateReport, Judgment
+from codeverse3d.contracts.artifacts import PLACEHOLDER_PART, GateReport, Judgment
from codeverse3d.contracts.common import Budget
from codeverse3d.contracts.plan import AcceptanceItem, Plan
from codeverse3d.contracts.run import RoundRecord, RunStatus, StepTime
@@ -259,7 +259,8 @@ def build_refine_instructions(
max_tasks: int = 6,
extra: Sequence[RefineTask] = (),
) -> list[RefineTask]:
- """Gate ERRORS first (with fix hints), then ``extra`` harness-derived tasks
+ """Gate ERRORS first (with fix hints) — a part still the skeleton's placeholder
+ (``PLACEHOLDER_PART``) ahead of every other gate ERROR —, then ``extra`` harness-derived tasks
(e.g. reference-silhouette mismatch), then failed *must* acceptance items,
then the judge's improvement plan; de-duplicated by (target, kind), capped.
Gate/acceptance/extra tasks are never dropped by the cap unless they alone exceed it."""
@@ -277,10 +278,11 @@ def build_refine_instructions(
t.files = list(file_for_target(t.target))
tasks.append(t)
- for g in gates:
- for f in g.errors:
- _add(RefineTask(target=f.target or "overall", kind=f"gate:{g.gate}", instruction=f.as_line(),
- priority=0, source="gate"))
+ errors = [(g, f) for g in gates for f in g.errors]
+ errors.sort(key=lambda gf: gf[1].data.get("kind") != PLACEHOLDER_PART) # stable: placeholders first
+ for g, f in errors:
+ _add(RefineTask(target=f.target or "overall", kind=f"gate:{g.gate}", instruction=f.as_line(),
+ priority=0, source="gate"))
for t in extra:
_add(t.model_copy())
for a in acceptance_failures:
diff --git a/harness/codeverse3d/prompts/system/role_scope.j2 b/harness/codeverse3d/prompts/system/role_scope.j2
deleted file mode 100644
index 3a003626..00000000
--- a/harness/codeverse3d/prompts/system/role_scope.j2
+++ /dev/null
@@ -1,3 +0,0 @@
-For this task you own {{ n_parts }} part(s) of a larger object: {{ names }}. Other sessions
-own the rest and run at the same time — never write a file outside your list. Real detail
-inside your parts beats a correctly sized box.
diff --git a/harness/codeverse3d/prompts/tracks/assemble_static.j2 b/harness/codeverse3d/prompts/tracks/assemble_static.j2
deleted file mode 100644
index 21b38ee8..00000000
--- a/harness/codeverse3d/prompts/tracks/assemble_static.j2
+++ /dev/null
@@ -1,53 +0,0 @@
-# Assemble `{{ object_name }}` — you own placement, not geometry
-
-{{ n_parts }} part{{ 's' if n_parts > 1 else '' }} were written in parallel, one session per group, each into its own file.
-You own the ENTRY file the wrapper runs: it imports every part builder and calls each once.
-You are the only session that sees the whole object, so **assembly is your responsibility**:
-every part present, nothing floating, nothing interpenetrating, the whole thing standing on the ground.
-
-## FILES YOU MAY WRITE — nothing else
-{% for f in files %}- `{{ f }}`
-{% endfor %}
-Part files belong to the sessions that wrote them. If a part is in the wrong place, fix the call /
-placement from the entry file where the language allows it; only if that is impossible may you make
-a MINIMAL placement edit inside that one part file — never rewrite its geometry.
-
-## The object
-{{ spec_prompt }}
-{{ plan_summary }}
-Overall bbox: {{ overall_bbox }}
-{{ frame_doc }}
-
-## Every part and where it must end up
-{{ parts_table }}
-
-## What you must do, in order
-1. Make the entry file import and call EVERY part builder in the table, once, in plan order.
-2. Run `build`. Fix every build/lint error. An error inside a part file that stops the whole build
- IS yours to fix — make the smallest change that makes it build.
-3. Run `measure`. Compare each measured part box with the table above.
-4. Run `check_connectivity` and `check_contract`. Every ERROR must be gone before you finish:
- - a **floating** part → apply the finding's translation, or extend it by the printed mm, so the
- surfaces touch (gap ≤ 2 mm, overlap ≤ 2 mm);
- - an **interpenetrating** pair → pull one back to its plan box;
- - a **missing** part → the builder was not called, or it built under a parent Empty
- (instances must be TOP-LEVEL objects), or its name does not match the table exactly;
- - the object not standing on the ground → shift the whole assembly, never rescale it.
-5. Run `render_sheet` and look at it. Anything obviously detached or duplicated, fix now.
-
-## Contract
-{{ contract }}
-
-## Acceptance checklist (the judge verifies each item)
-{{ acceptance }}
-
-## Detail
-{{ detail_advice }}
-
-{% if tool_cards and not single_shot %}
-## Tools
-{{ tool_cards }}
-{% endif %}
-
-## Output
-{{ output_format }}
diff --git a/harness/codeverse3d/prompts/tracks/generate_articulated.j2 b/harness/codeverse3d/prompts/tracks/generate_articulated.j2
index 1944f9c7..cdd0dbd7 100644
--- a/harness/codeverse3d/prompts/tracks/generate_articulated.j2
+++ b/harness/codeverse3d/prompts/tracks/generate_articulated.j2
@@ -39,6 +39,20 @@ are WORLD points at rest:
## Acceptance checklist
{{ acceptance }}
+## The whole object first
+Every link exists at its planned box and the URDF names every planned joint before any link gets
+detail: a session can be stopped at its window, and what it leaves must still be the whole object.
+Measured: a link still the skeleton's box (≤ 12 triangles, a closed solid filling its
+box, within 1 mm of the plan box) is a `placeholder_part` ERROR in `check_contract`; a link that does
+not meet its parent is an ERROR (the gaps are stated under DON'T below).
+{% if not single_shot %}
+
+Both files already exist (the skeleton). Replace a placeholder in one write, then change a file only
+with targeted edits — never rewrite a whole file to change a few lines. Measured on this harness:
+a dining chair whose files were rewritten whole (8 rewrites over 9 files) wrote ~136k characters,
+drafted with each file written once ~49k, and a session's time follows the tokens it generates.
+{% endif %}
+
## DO
- Build every link at its WORLD rest pose to the plan's bbox (`check_contract`: max(10 mm, 10 %) per
axis); one object named exactly as the link, with any helper objects parented under it (the
diff --git a/harness/codeverse3d/prompts/tracks/generate_static.j2 b/harness/codeverse3d/prompts/tracks/generate_static.j2
index d6e24fe6..618753c2 100644
--- a/harness/codeverse3d/prompts/tracks/generate_static.j2
+++ b/harness/codeverse3d/prompts/tracks/generate_static.j2
@@ -32,6 +32,20 @@ Construction notes per part:
## Acceptance checklist (the judge verifies each item; build so every item is visibly true)
{{ acceptance }}
+## The whole object first
+Every row of the table exists at its planned box and is joined to the part it attaches to before any
+part gets detail: a session can be stopped at its window, and what it leaves must still be the whole
+object. Measured: a part still the skeleton's box (≤ 12 triangles, a closed solid filling its
+box, within 1 mm of the plan box) is a `placeholder_part` ERROR in `check_contract`; a part not joined
+to the ground-touching component is a floating ERROR in `check_connectivity`.
+{% if not single_shot %}
+
+Every file already exists (the skeleton). Replace a file's placeholder in one write, then change it
+only with targeted edits — never rewrite a whole file to change a few lines. Measured on this harness:
+a dining chair whose files were rewritten whole (8 rewrites over 9 files) wrote ~136k characters,
+drafted with each file written once ~49k, and a session's time follows the tokens it generates.
+{% endif %}
+
## DO
- Place each part so its bounding box CENTRE and EXTENTS equal the plan row. Compute
positions from the numbers in the table; do not re-invent the layout.
diff --git a/harness/codeverse3d/prompts/tracks/generate_static_part.j2 b/harness/codeverse3d/prompts/tracks/generate_static_part.j2
deleted file mode 100644
index cd5dc6f3..00000000
--- a/harness/codeverse3d/prompts/tracks/generate_static_part.j2
+++ /dev/null
@@ -1,63 +0,0 @@
-# Build the `{{ scope_names }}` part{{ 's' if n_scope_parts > 1 else '' }} of `{{ object_name }}` in raw {{ language }}
-
-You own **{{ n_scope_parts }} part{{ 's' if n_scope_parts > 1 else '' }}** of a {{ n_parts }}-part object.
-Other sessions are building the other parts RIGHT NOW, in their own files, from the same plan.
-Your job is to make YOUR parts genuinely good — real geometry, real detail, exact placement — not
-to build the whole object. Do not create, rename or edit any part that is not yours.
-
-## The object this belongs to (context only — you build only your parts)
-{{ spec_prompt }}
-{{ plan_summary }}
-Overall bbox: {{ overall_bbox }}
-Style: {{ style_notes }}
-
-## The contract (hard rules — the build fails or the gate rejects when broken)
-{{ frame_doc }}
-{{ contract }}
-
-## FILES YOU MAY WRITE — nothing else
-{% for f in files %}- `{{ f }}`
-{% endfor %}
-The entry file and every other part file belong to other sessions. Touching them loses their work.
-## YOUR parts (build every row; object names must match EXACTLY — they become GLB node names)
-{{ parts_table }}
-
-Construction notes:
-{{ part_details }}
-
-## Interfaces — the neighbours you must physically meet
-{{ interfaces }}
-
-Those neighbour boxes are the truth another session is building to. Where your part attaches to
-one, overlap it by at most 2 mm and leave no gap over 2 mm (flush counts) — the connectivity gate's
-contact band; where a neighbour attaches to yours, leave a real surface for it at the stated box —
-no recess it cannot reach, no shape that would make it interpenetrate.
-
-## Detail
-{{ detail_advice }}
-
-## DO
-- Place each part so its bounding box CENTRE and EXTENTS equal the plan row.
-- Build what the description says at its numbers and counts: the judge's checklist marks a
- named feature that is not there (a scaled cube where the plan says "fluted cylindrical body with
- 6 flutes").
-- Material per part with the stated colour, roughness and metalness.
-- Instances (`{{ '{' }}Name{{ '}' }}_0 … _N-1`) are built inside YOUR file, each TOP-LEVEL.
-
-## DON'T
-- Do not build, rename, move or "fix" a part that is not in your table — even if it looks wrong.
-- Do not write the entry file, a README, notes or tests.
-- No placeholders ("TODO", "simplified"), no unit-cube stand-ins, no part off its plan bbox by more
- than the contract tolerance (max(1 cm, 10 %) per axis).
-- No environment sniffing, no DOM/texture loading/network/file IO, no camera/light/render/export.
-
-{% if tool_cards and not single_shot %}
-## Tools available to you
-{{ tool_cards }}
-Run `build` after writing your files and fix every error it reports before you finish. The build
-compiles the WHOLE object, so an error in someone else's file is not yours to fix — fix only errors
-that name your files.
-{% endif %}
-
-## Output
-{{ output_format }}
diff --git a/harness/codeverse3d/prompts/tracks/refine_object.j2 b/harness/codeverse3d/prompts/tracks/refine_object.j2
index fa9d55a1..6ecfde8f 100644
--- a/harness/codeverse3d/prompts/tracks/refine_object.j2
+++ b/harness/codeverse3d/prompts/tracks/refine_object.j2
@@ -10,13 +10,20 @@ THIS round. Make exactly these changes, keep everything else as it is, and keep
Targets: {{ targets | join(', ') }}
{% if edit_only_these %}
-EDIT ONLY THESE FILES — the write tool refuses to overwrite any other existing part file this round.
-You may still create new files and edit the entry file (to import a new part). If a fix truly needs a
-file outside this list, finish without it and say so in your summary.
-{% for f in files %}- `{{ f }}`
-{% endfor %}
+Change only these files (shown below) and the entry file; any other existing part file is refused:
+{% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}
+
{% else %}
-Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}
+Files in scope (the whole object; a change names its target's file where it has one):
+{% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}
+
+{% endif %}
+{% if not single_shot %}
+
+Edit in place: change only the lines a task needs, with targeted edits — never rewrite a whole file to
+change a few lines. Measured on this harness: a dining chair whose files were rewritten whole (8
+rewrites over 9 files) wrote ~136k characters, drafted with each file written once ~49k, and a
+session's time follows the tokens it generates.
{% endif %}
## What the judge saw
@@ -50,6 +57,7 @@ Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}
{% if current_files %}
{% if single_shot %}## Current file contents (edit these; return each edited file COMPLETE){% else %}## Current file contents (already in the workspace — edit them in place; do NOT read_file them first){% endif %}
+
{% for path, body in current_files.items() %}
--- {{ path }} ---
```
diff --git a/harness/codeverse3d/spatial/contract.py b/harness/codeverse3d/spatial/contract.py
index 46ee5921..3da83474 100644
--- a/harness/codeverse3d/spatial/contract.py
+++ b/harness/codeverse3d/spatial/contract.py
@@ -10,6 +10,11 @@ prompts that speak the language's frame.
Severity policy (``tol = max(tol_m, REL_TOL × plan extent)`` per axis):
* plan part missing in the GLB → ERROR
+* plan part still the skeleton's placeholder box (:func:`is_placeholder`: every measured row at
+ most ``PLACEHOLDER_MAX_TRIS`` triangles, a closed solid filling its box, and within
+ ``PLACEHOLDER_TOL_M`` of the plan box) → ERROR
+ ``data["kind"] == "placeholder_part"`` (D110): it passes every box check by construction, so
+ without this a session cut off mid-draft shipped stand-ins the gates called perfect
* bbox centre / extents off by > tol → WARN (exact delta in the hint);
> ``ERROR_FACTOR × tol`` → ERROR
* overall bbox vs ``overall_bbox`` → same policy
@@ -20,7 +25,7 @@ Severity policy (``tol = max(tol_m, REL_TOL × plan extent)`` per axis):
footprint off-centre → WARN
* GLB parts the plan never mentioned → INFO
-Every WARN/ERROR carries ``data["kind"]`` (missing_part · instance_count · part_bbox ·
+Every WARN/ERROR carries ``data["kind"]`` (missing_part · placeholder_part · instance_count · part_bbox ·
instance_bbox · overall_bbox · orientation · ground_gap · footprint_offset): the rubric
caps and the skill router key on it, never on the message.
"""
@@ -33,6 +38,7 @@ from dataclasses import dataclass
import numpy as np
from codeverse3d.contracts.artifacts import (
+ PLACEHOLDER_PART,
GateFinding,
GateReport,
Measurement,
@@ -86,6 +92,19 @@ ORIENT_THIRD = float(np.log(1.5))
ORIENT_ANISO = 1.5
ORIENT_OVER = 1.4
+#: The skeleton's stand-in for a part is ONE axis-aligned box at the plan box — blender
+#: ``add_box`` / urdf ``box`` (``primitive_cube_add``, scale applied), three.js ``BoxGeometry``,
+#: cadquery ``Workplane.box`` — which every exporter writes as 12 triangles. A part whose every
+#: measured row is that small, that exactly placed and a closed solid FILLING its box is the
+#: placeholder, whatever its name says (no source grep, Law 4). 1 mm is a tenth of the contract
+#: tolerance (max(10 mm, 10 %)). The fill test keeps real 12-triangle hexahedra built to plan
+#: (a tapered cadquery fretboard, fill 0.879; wedges; open panes) out: over 942 measured part rows
+#: of loop_argon iter_00/01, the 68 true placeholders were all watertight at fill 1.000. A real
+#: part is taken for one only when it is itself a bare box built to the plan's millimetre.
+PLACEHOLDER_MAX_TRIS = 12
+PLACEHOLDER_TOL_M = 0.001
+PLACEHOLDER_MIN_FILL = 1.0 - 1e-3
+
# --------------------------------------------------------------------------- frames
def frame_label(language: str) -> str:
@@ -141,6 +160,31 @@ def match_parts(plan_parts: list[PartPlan], measured: list[PartMeasure]) -> tupl
return matched, list(remaining.values())
+def is_placeholder(rows: list[PartMeasure], plan_box: BBox) -> bool:
+ """Is this plan part (its measured rows, one per instance) still the skeleton's box?
+
+ ``plan_box`` is in the GLB frame (:func:`plan_bbox_to_glb`). Every row must carry at most
+ ``PLACEHOLDER_MAX_TRIS`` triangles (0 = not measured: never a placeholder), be watertight
+ with a volume of at least ``PLACEHOLDER_MIN_FILL`` of its own box (not measured / open: never
+ a placeholder) and have the plan's extents within ``PLACEHOLDER_TOL_M`` per axis; a single
+ instance must also sit at the plan centre — the skeleton places instance copies by the
+ symmetry hint, so only their size is the plan's."""
+ if not rows:
+ return False
+ ext, ctr = np.asarray(plan_box.extents, dtype=float), np.asarray(plan_box.center, dtype=float)
+ for r in rows:
+ if not 0 < r.tri_count <= PLACEHOLDER_MAX_TRIS or not r.watertight or r.volume_m3 is None:
+ return False
+ lo, hi = np.asarray(r.bbox_min, dtype=float), np.asarray(r.bbox_max, dtype=float)
+ if np.any(np.abs((hi - lo) - ext) > PLACEHOLDER_TOL_M):
+ return False
+ if abs(r.volume_m3) < PLACEHOLDER_MIN_FILL * float(np.prod(hi - lo)):
+ return False
+ if len(rows) == 1 and np.any(np.abs((hi + lo) / 2 - ctr) > PLACEHOLDER_TOL_M):
+ return False
+ return True
+
+
def planned_joins(plan: Plan | None, measurement: Measurement | None) -> list[tuple[str, tuple[str, ...]]]:
"""The plan's ``attach_to`` edges spelled in the GLB's part names, for the connectivity ledger.
@@ -324,6 +368,17 @@ def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: f
))
continue
box = plan_bbox_to_glb(pp.bbox, language)
+ if is_placeholder(rows, box):
+ joined = f", joined to {pp.attach_to}" if pp.attach_to else ""
+ findings.append(GateFinding(
+ gate=GATE, severity=Severity.ERROR, target=target,
+ message=f"plan part '{pp.name}' is still the skeleton's placeholder box "
+ f"({max(r.tri_count for r in rows)} triangles at its plan box)",
+ fix_hint=f"build the real '{pp.name}' ({pp.role}) in place of the box, at its planned size "
+ f"{fmt_extent_cm(pp.bbox.extents)} cm{joined}",
+ data={"kind": PLACEHOLDER_PART, "tri_count": sum(r.tri_count for r in rows), "instances": len(rows)},
+ ))
+ continue
if pp.instances > 1 and len(rows) != pp.instances:
findings.append(GateFinding(
gate=GATE, severity=Severity.WARN, target=target,
diff --git a/harness/codeverse3d/tracks/depth.py b/harness/codeverse3d/tracks/depth.py
index b18ebd30..5ce0f75e 100644
--- a/harness/codeverse3d/tracks/depth.py
+++ b/harness/codeverse3d/tracks/depth.py
@@ -1,4 +1,4 @@
-"""Generation depth: complexity budgets and per-part scoped generation.
+"""Generation depth: complexity budgets.
Measured on the recorded corpus (183 judged rounds / 81 runs, see the wave's
``complexity_baseline.md``), three facts shape this module:
@@ -26,22 +26,17 @@ Hence: :func:`depth_budget` (how many triangles / how much build time this *plan
deserves, checked by :func:`budget_gate`; the generate / refine briefs get the numberless
:data:`DETAIL_ADVICE`, and each object language's ``contract.md`` states the gate's per-object
constants as a measured requirement (D107, pinned in ``prompts/_claims.toml``); how many PARTS a prompt deserves is
-``tracks.planner.plan_budget``, which also owns the thin-plan re-ask), and :func:`scope_groups` (how to split one plan into sessions small
-enough that each part gets real attention) with :func:`interfaces_text` handing
-each session the exact numbers of the parts it must touch but may not edit.
+``tracks.planner.plan_budget``, which also owns the thin-plan re-ask). The per-part scoped
+baseline that lived here (``scope_groups`` / ``interfaces_text``) was deleted by D110: one session
+drafts the whole object.
"""
from __future__ import annotations
-import logging
-from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any
-from codeverse3d.config import get_settings
-from codeverse3d.conventions import MAX_TRIS_OBJECT, fmt3, to_pascal, to_snake
-
-log = logging.getLogger(__name__)
+from codeverse3d.conventions import MAX_TRIS_OBJECT
# --------------------------------------------------------------------------- triangle / time budget
#: triangles a well-detailed single part is worth. Corpus: median tri/part ≈ 430, and the
@@ -99,191 +94,6 @@ def _clamp(v: float, lo: float, hi: float) -> int:
return int(max(lo, min(hi, v)))
-# --------------------------------------------------------------------------- scoped generation
-#: below this many plan parts one session handles the whole object fine (and fan-out only
-#: adds coordination cost): the corpus shows the ceiling biting from ~8 parts up
-MIN_PARTS_FOR_SCOPED = 8
-#: parts one scoped session owns. Small enough that every part gets real attention,
-#: large enough that a part and the neighbour it must weld to usually land together.
-DEFAULT_PARTS_PER_SCOPE = 3
-
-
-def scoped_generation_enabled() -> bool:
- """``C3D_SCOPED_PARTS=off`` turns per-part scoped baselines off (A/B, debugging)."""
- return get_settings().scoped_parts
-
-
-@dataclass(frozen=True)
-class PartScope:
- """One scoped generation session: a few plan parts and the files that hold them."""
-
- parts: tuple[Any, ...]
- files: tuple[str, ...]
-
- @property
- def names(self) -> list[str]:
- return [str(p.name) for p in self.parts]
-
- @property
- def label(self) -> str:
- return "+".join(to_snake(n) for n in self.names[:3]) or "parts"
-
-
-def scope_groups(
- plan: Any,
- *,
- files_for: Any,
- max_groups: int = 6,
- parts_per_scope: int = DEFAULT_PARTS_PER_SCOPE,
- min_parts: int = MIN_PARTS_FOR_SCOPED,
-) -> list[PartScope]:
- """Split a plan into per-part scoped sessions, or ``[]`` when one session suffices.
-
- Parts are partitioned along the ``attach_to`` tree, so a part and the parts it
- carries land in the SAME session wherever possible — that is where the
- assembly-fit penalty for extra parts comes from, and a contact both sides of
- which are written by one session is a contact that gets welded. Subtrees are
- then packed into at most ``max_groups`` groups of ``parts_per_scope``.
- """
- parts = list(getattr(plan, "parts", None) or [])
- if len(parts) < max(2, min_parts) or max_groups < 2:
- return []
- units = _attachment_units(parts, parts_per_scope)
- groups = _pack(units, max_groups=max_groups, parts_per_scope=parts_per_scope)
- if len(groups) < 2:
- return []
- out: list[PartScope] = []
- for g in groups:
- files: list[str] = []
- for p in g:
- for f in _files_for(files_for, p.name):
- if f not in files:
- files.append(f)
- if not files: # a language with no per-part file ownership cannot be scoped
- return []
- out.append(PartScope(parts=tuple(g), files=tuple(files)))
- return out
-
-
-def _files_for(files_for: Any, name: str) -> list[str]:
- if not callable(files_for):
- return []
- try:
- got = files_for(name)
- except Exception as e: # noqa: BLE001 — a mapper failure must not kill generation
- log.warning("file_for_target failed for %s: %s", name, e)
- return []
- if not got:
- return []
- return [str(got)] if isinstance(got, str) else [str(x) for x in got]
-
-
-def _attachment_units(parts: Sequence[Any], parts_per_scope: int) -> list[list[Any]]:
- """Attachment subtrees, each split down to ``parts_per_scope`` at most."""
- by_key = {to_snake(str(p.name)): p for p in parts}
- children: dict[str, list[str]] = {k: [] for k in by_key}
- roots: list[str] = []
- for p in parts:
- key = to_snake(str(p.name))
- parent = to_snake(str(getattr(p, "attach_to", None) or ""))
- if parent and parent in by_key and parent != key:
- children[parent].append(key)
- else:
- roots.append(key)
- seen: set[str] = set()
- units: list[list[Any]] = []
-
- def subtree(key: str) -> list[Any]:
- out, stack = [], [key]
- while stack:
- k = stack.pop()
- if k in seen:
- continue
- seen.add(k)
- out.append(by_key[k])
- stack.extend(children.get(k, ()))
- return out
-
- for r in roots:
- if r in seen:
- continue
- seen.add(r)
- units.append([by_key[r]]) # the root itself is its own unit (it is the datum)
- for c in children.get(r, ()):
- got = subtree(c)
- if got:
- units.append(got)
- for k, p in by_key.items(): # cycles / unreachable parts
- if k not in seen:
- seen.add(k)
- units.append([p])
- out: list[list[Any]] = []
- for u in units:
- for i in range(0, len(u), parts_per_scope):
- out.append(u[i:i + parts_per_scope])
- return out
-
-
-def _pack(units: list[list[Any]], *, max_groups: int, parts_per_scope: int) -> list[list[Any]]:
- """First-fit-decreasing pack of subtrees into ≤ ``max_groups`` groups."""
- if not units:
- return []
- cap = max(parts_per_scope, -(-sum(len(u) for u in units) // max_groups))
- groups: list[list[Any]] = []
- for u in sorted(units, key=len, reverse=True):
- target = next((g for g in groups if len(g) + len(u) <= cap), None)
- if target is None and len(groups) < max_groups:
- groups.append(list(u))
- elif target is None:
- min(groups, key=len).extend(u)
- else:
- target.extend(u)
- return [g for g in groups if g]
-
-
-# --------------------------------------------------------------------------- scoped prompt text
-def interfaces_text(plan: Any, scope: PartScope) -> str:
- """The exact numbers of every part OUTSIDE this scope that touches a part inside it.
-
- This is the whole point of scoping: the session never sees the other 20 parts,
- but it must weld to the ones it borders, so it gets their planned box and the
- 2 mm overlap rule for each contact — deterministically, from the plan.
- """
- parts = list(getattr(plan, "parts", None) or [])
- by_key = {to_snake(str(p.name)): p for p in parts}
- inside = {to_snake(n) for n in scope.names}
- rows: list[str] = []
- seen: set[tuple[str, str]] = set()
-
- def _row(mine: Any, other: Any, direction: str) -> None:
- key = (to_snake(str(mine.name)), to_snake(str(other.name)))
- if key in seen:
- return
- seen.add(key)
- rows.append(f"| {to_pascal(str(mine.name))} | {direction} | {to_pascal(str(other.name))} | "
- f"({fmt3(other.bbox.center)}) | ({fmt3(other.bbox.extents)}) | "
- f"x [{other.bbox.min[0]:.3f}, {other.bbox.max[0]:.3f}] "
- f"y [{other.bbox.min[1]:.3f}, {other.bbox.max[1]:.3f}] "
- f"z [{other.bbox.min[2]:.3f}, {other.bbox.max[2]:.3f}] |")
-
- for p in scope.parts:
- parent = by_key.get(to_snake(str(getattr(p, "attach_to", None) or "")))
- if parent is not None and to_snake(str(parent.name)) not in inside:
- _row(p, parent, "attaches TO")
- for other in parts:
- if to_snake(str(other.name)) in inside:
- continue
- parent_key = to_snake(str(getattr(other, "attach_to", None) or ""))
- if parent_key in inside:
- _row(by_key[parent_key], other, "carries")
- if not rows:
- return "(no parts outside this scope touch yours — build to the plan boxes and the ground plane)"
- head = ("| your part | relation | neighbour (owned by another session — DO NOT create or edit it) | "
- "neighbour centre (m) | neighbour extents (m) | neighbour box |\n|---|---|---|---|---|---|")
- return head + "\n" + "\n".join(rows)
-
-
-
# --------------------------------------------------------------------------- the budget gate
BUDGET_GATE = "detail_budget"
diff --git a/harness/codeverse3d/tracks/generation.py b/harness/codeverse3d/tracks/generation.py
index 3176727e..1e6f4106 100644
--- a/harness/codeverse3d/tracks/generation.py
+++ b/harness/codeverse3d/tracks/generation.py
@@ -38,12 +38,12 @@ import shutil
import time
from collections.abc import Callable, Collection
from pathlib import Path, PurePosixPath
-from typing import Any
+from typing import Any, Literal, get_args
from pydantic import BaseModel, Field
from codeverse3d.config import get_settings
-from codeverse3d.contracts.agent import AgentJob, AgentResult, FileChange
+from codeverse3d.contracts.agent import AgentEffort, AgentJob, AgentResult, FileChange
from codeverse3d.contracts.chat import ChatMessage, ChatRequest, ImagePart
from codeverse3d.contracts.common import (
ENTRY_FILE,
@@ -270,6 +270,16 @@ def turn_capped(res: Any) -> bool:
return any("max_turns" in str(e) for e in (getattr(res, "errors", None) or []))
+#: what a single-shot call thinks at when its task asks for nothing (``GenerationTask.thinking`` '')
+SINGLE_SHOT_THINKING = "medium"
+
+
+def session_effort(task: GenerationTask) -> AgentEffort | None:
+ """``AgentJob.effort`` for ``task``: its ``thinking`` when the caller explicitly asked for an
+ agent effort, else None — the backend's default (agy: ``AGY_API_EFFORT`` = high)."""
+ return task.thinking if task.thinking in get_args(AgentEffort) else None # type: ignore[return-value]
+
+
class GenerationTask(BaseModel):
"""One unit of code-writing work (baseline, refine group, asset, zone, repair)."""
@@ -285,7 +295,13 @@ class GenerationTask(BaseModel):
kind: str = "generate"
images: list[ImagePart] = Field(default_factory=list)
temperature: float = 0.6
- thinking: str = "medium"
+ thinking: Literal["", "off", "low", "medium", "high"] = Field(
+ default="",
+ description="'' = the caller asks for nothing: a single-shot call thinks at SINGLE_SHOT_THINKING, an "
+ "agent session runs at its backend's default (agy: high, owner 2026-10-15). Anything else is an "
+ "explicit ask — the single-shot call uses it, and an agent session gets it as AgentJob.effort "
+ "(``off`` reaches no agent). No track asks for less than high today (D110)",
+ )
max_output_tokens: int = 65_536 # the model's declared ceiling; unused tokens cost nothing
timeout_s: int | None = None
write_roots: list[str] = Field(default_factory=lambda: ["src", "public"])
@@ -300,16 +316,6 @@ class GenerationTask(BaseModel):
"A task whose files_hint names the entry owns it implicitly; part / zone / detail / asset "
"tasks default to False so parallel scoped sessions cannot race on the entry file",
)
- phase: int = Field(
- default=0,
- ge=0,
- description=(
- "execution phase inside ONE round: tasks run in parallel WITHIN a phase and phases run "
- "in ascending order. Everything is phase 0 unless a track says otherwise — the only "
- "current user is per-part scoped generation, where the assembly session (phase 1) must "
- "see the part files the scoped sessions (phase 0) wrote."
- ),
- )
class GenerationResult(BaseModel):
@@ -411,7 +417,7 @@ def generate_files(
messages=[ChatMessage.user(task.prompt, images=task.images or None)],
system=system,
temperature=task.temperature,
- thinking=task.thinking, # type: ignore[arg-type]
+ thinking=task.thinking or SINGLE_SHOT_THINKING,
max_output_tokens=task.max_output_tokens,
# the RUN's remaining wall clock AND the task's own window, not the models' 1800 s
# default — and past the hard ceiling this refuses to buy the call at all
@@ -428,8 +434,8 @@ def generate_files(
resp = ask(req)
usage = resp.usage
# the clock is not enforced here: the response is already paid for, and raising would
- # discard it before transcript/parse/write_files — the round's phase boundary does
- # (steps._run_phase)
+ # discard it before transcript/parse/write_files — the round's generate step does
+ # (steps.run_generation_tasks)
retry = False
if _is_truncated(resp):
# cut off by max_output_tokens: the envelope is unterminated — one retry with a
@@ -558,6 +564,7 @@ def run_agent_task(
track=track,
files_hint=list(task.files_hint),
edit_only=task.edit_only,
+ effort=session_effort(task),
always_writable=_always_writable(language, task),
read_only=_read_only(language),
**({"max_turns": turns_cap} if turns_cap > 0 else {}),
diff --git a/harness/codeverse3d/tracks/graphics.py b/harness/codeverse3d/tracks/graphics.py
index f4b1f856..0ebb4c87 100644
--- a/harness/codeverse3d/tracks/graphics.py
+++ b/harness/codeverse3d/tracks/graphics.py
@@ -169,5 +169,5 @@ class GraphicsTrack(BaseTrack):
current_files=refine_inline_files(ctx, files)))
ctx.record_prompt("refine", prompt)
return GenerationTask(label="refine", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,
- kind="refine", temperature=0.5, thinking="medium", owns_entry=True,
+ kind="refine", temperature=0.5, owns_entry=True,
images=reference_images(ctx) + judged_sheet(last))
diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.py
index 8063b66d..f376a4e3 100644
--- a/harness/codeverse3d/tracks/lifecycle.py
+++ b/harness/codeverse3d/tracks/lifecycle.py
@@ -206,7 +206,8 @@ class BaseTrack:
stages: Stages = (SKELETON, MATERIALIZE)
generate_template: str = ""
refine_template: str = ""
- #: refine fan-out (graphics is always ONE whole-program task)
+ #: refine fan-out — the scene's zones / assets / env only: graphics is ONE whole-program task and the
+ #: object tracks ONE whole-object session (D110)
allow_refine_fanout: bool = True
#: share of the run budget the BASELINE may use (1.0 = no soft cap). The scene
#: track lowers it so the refine rounds always inherit money and minutes.
@@ -248,7 +249,7 @@ class BaseTrack:
ctx, skeleton_files=skeleton_files(ctx) if ctx.single_shot else {}, previous_error=""))
ctx.record_prompt("generate", prompt)
return [GenerationTask(label="baseline", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=0,
- kind="baseline", temperature=self.baseline_temperature, thinking="medium", owns_entry=True,
+ kind="baseline", temperature=self.baseline_temperature, owns_entry=True,
images=reference_images(ctx))]
def system_prompt(self, ctx: RunContext) -> str:
diff --git a/harness/codeverse3d/tracks/prompting.py b/harness/codeverse3d/tracks/prompting.py
index 032148fc..d316240c 100644
--- a/harness/codeverse3d/tracks/prompting.py
+++ b/harness/codeverse3d/tracks/prompting.py
@@ -26,13 +26,7 @@ from codeverse3d.conventions import LANGUAGE_FRAME, fmt3, frame_doc, to_authorin
from codeverse3d.prompts import render
from codeverse3d.prompts.catalog import contract_sections, language_prompt, language_text
from codeverse3d.tracks.common import RunContext
-from codeverse3d.tracks.depth import (
- DETAIL_ADVICE,
- DepthBudget,
- PartScope,
- depth_budget,
- interfaces_text,
-)
+from codeverse3d.tracks.depth import DETAIL_ADVICE, DepthBudget, depth_budget
log = logging.getLogger(__name__)
@@ -41,11 +35,7 @@ MAX_SKELETON_CHARS = 14_000
def parts_table(plan: Plan) -> str:
"""Markdown table of parts with exact bboxes (meters, 3 decimals)."""
- return parts_table_for(getattr(plan, "parts", None) or ())
-
-
-def parts_table_for(parts: Sequence[Any]) -> str:
- """``parts_table`` for an explicit part subset (one scoped session's parts)."""
+ parts = getattr(plan, "parts", None) or ()
if not parts:
return "(no parts)"
rows = [
@@ -60,17 +50,13 @@ def parts_table_for(parts: Sequence[Any]) -> str:
def part_details(plan: Plan) -> str:
- return part_details_for(getattr(plan, "parts", None) or [])
-
-
-def part_details_for(parts: Sequence[Any]) -> str:
"""Per-part construction notes, including the sub-parts an ASSEMBLY part is made of.
Sub-parts (``PartPlan.children``) are a planning device — the parent is still ONE
named export node — but they are where the depth lives, so the builder must see
them with their own boxes, not just a sentence."""
out: list[str] = []
- for p in parts:
+ for p in getattr(plan, "parts", None) or ():
sym = p.symmetry if getattr(p, "symmetry", "none") != "none" else "no symmetry"
line = f"- **{p.name}** ({sym}): {p.description}"
hint = getattr(p, "detail_hint", "") or ""
@@ -199,7 +185,7 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
return d
-# ----------------------------------------------------------------------------- depth / scoping
+# ----------------------------------------------------------------------------- depth
def budget_for(ctx: RunContext) -> DepthBudget:
"""This run's complexity-aware triangle + build-time budget (cached on ctx.extra)."""
got = ctx.extra.get("depth_budget")
@@ -211,24 +197,6 @@ def budget_for(ctx: RunContext) -> DepthBudget:
return b
-def scope_context(ctx: RunContext, scope: PartScope, **extra: Any) -> dict[str, Any]:
- """Template context for ONE scoped part session: only its parts, plus the exact
- numbers of the neighbours it must weld to but may not write."""
- d = base_prompt_context(ctx, **extra)
- d.update(
- {
- "scope_label": scope.label,
- "scope_names": ", ".join(scope.names),
- "parts_table": parts_table_for(scope.parts),
- "part_details": part_details_for(scope.parts),
- "interfaces": interfaces_text(ctx.plan, scope),
- "n_scope_parts": len(scope.parts),
- }
- )
- d.update(extra)
- return d
-
-
def reference_images(ctx: RunContext, limit: int = 3) -> list[ImagePart]:
"""The spec's reference images as inline image parts (single-shot prompts)."""
out: list[ImagePart] = []
diff --git a/harness/codeverse3d/tracks/repair.py b/harness/codeverse3d/tracks/repair.py
index 2f1f8921..eec1e670 100644
--- a/harness/codeverse3d/tracks/repair.py
+++ b/harness/codeverse3d/tracks/repair.py
@@ -191,7 +191,7 @@ def make_repair_task(ctx: RunContext, build: BuildResult, lint: GateReport, *, r
failing_files=sorted(files) if files else [build.error_file] if build.error_file else files_hint))
ctx.record_prompt("repair", prompt)
temperature = min(1.0, 0.3 + 0.25 * repeats)
- thinking = ("medium", "high", "high")[min(repeats, 2)]
+ thinking = ("", "high", "high")[min(repeats, 2)] # "": the single-shot default (medium), agy its own (high)
return GenerationTask(label=label, prompt=prompt, system=_repair_system(ctx), files_hint=sorted(files) or files_hint,
round=round_index, kind="repair", temperature=temperature, thinking=thinking, timeout_s=timeout_s)
diff --git a/harness/codeverse3d/tracks/static_object.py b/harness/codeverse3d/tracks/static_object.py
index 69f808ba..a1154f81 100644
--- a/harness/codeverse3d/tracks/static_object.py
+++ b/harness/codeverse3d/tracks/static_object.py
@@ -1,8 +1,12 @@
-"""StaticObjectTrack: plan → skeleton → baseline → refine rounds → finalise.
-
-Languages: blender (bpy) · cadquery · threejs. Per-part parallel refinement
-is used when the language owns one file per part (threejs, blender) and ≥ 2
-file-disjoint task groups exist; otherwise one whole-object refine task.
+"""StaticObjectTrack: plan → skeleton → draft → refine rounds → finalise (D110, baseline-first).
+
+Languages: blender (bpy) · cadquery · threejs (articulated_object subclasses it for urdf_blender).
+Round 0 is ONE agent session that drafts the WHOLE object — every part file and the entry
+(``BaseTrack.baseline_tasks`` over ``generate_static.j2``); every refine round is ONE session that
+edits the whole object in place (``allow_refine_fanout = False``), driven by the gate ERRORs
+(placeholder parts first), the failed must-acceptance items and the judge's improvement plan.
+No per-part scoped baseline and no parallel part sessions: they ran serially behind the
+per-workspace session lock since 2026-08-28 and left 13-14 of 15 argon runs with placeholder parts.
"""
from __future__ import annotations
@@ -11,6 +15,7 @@ import logging
from collections.abc import Sequence
from pathlib import Path
+from codeverse3d.agents.cli_common import HARD_GRACE_S
from codeverse3d.contracts.artifacts import (
BuildResult,
GateFinding,
@@ -32,12 +37,7 @@ from codeverse3d.prompts import render
from codeverse3d.spatial.contract import planned_joins
from codeverse3d.spatial.silhouette import measure_reference
from codeverse3d.tracks.common import RunContext
-from codeverse3d.tracks.depth import (
- PartScope,
- budget_gate,
- scope_groups,
- scoped_generation_enabled,
-)
+from codeverse3d.tracks.depth import budget_gate
from codeverse3d.tracks.generation import GenerationTask
from codeverse3d.tracks.lifecycle import BaseTrack
from codeverse3d.tracks.prompting import (
@@ -45,11 +45,9 @@ from codeverse3d.tracks.prompting import (
budget_for,
judge_digest,
judged_sheet,
- language_system_prompt,
measurement_vs_plan,
reference_images,
refine_inline_files,
- scope_context,
)
from codeverse3d.workspace import Workspace
@@ -148,107 +146,13 @@ class StaticObjectTrack(BaseTrack):
plan_model = StaticPlan
generate_template = "tracks/generate_static.j2"
refine_template = "tracks/refine_object.j2"
- part_template = "tracks/generate_static_part.j2"
- assemble_template = "tracks/assemble_static.j2"
+ #: ONE whole-object refine session per round (D110): the part files interlock, and a split
+ #: round ran its sessions one after another behind the workspace lock anyway
+ allow_refine_fanout = False
def make_pipeline(self) -> ObjectPipeline:
return ObjectPipeline()
- # ------------------------------------------------------------------ baseline
- def baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:
- return self.scoped_baseline_tasks(ctx) or super().baseline_tasks(ctx)
-
- # ------------------------------------------------------------------ scoped baseline
- def scopes(self, ctx: RunContext) -> list[PartScope]:
- """Per-part generation scopes, or ``[]`` when one session should own the object.
-
- Requires a language that owns one file per part (blender / threejs) and an
- agent session per scope — a single-shot envelope has no session to split.
- """
- if ctx.single_shot or not scoped_generation_enabled():
- return []
- cached = ctx.extra.get("scopes")
- if isinstance(cached, list):
- return cached
- got = scope_groups(
- ctx.plan,
- files_for=self.refine_file_for_target(ctx),
- max_groups=max(2, int(getattr(ctx.settings.limits, "max_parallel_agents", 6) or 6)),
- )
- ctx.extra["scopes"] = got
- return got
-
- def scoped_baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:
- """Fan the baseline out: one session per few parts (phase 0), then ONE assembly
- session that owns the entry file and the placement gates (phase 1).
-
- Measured motivation (wave "generation-depth"): within a fixed difficulty tier
- more built parts buy detail (ρ(n_built, geometry_detail) = +0.34 on static_v2
- r00) but also buy gate errors (+0.45), and a single session over 10+ parts
- spends its attention on the plan, not on the parts. Each scoped session sees
- only its own parts plus the deterministic interface boxes of the neighbours it
- must weld to; the assembly session is the only one that sees the whole object.
- """
- scopes = self.scopes(ctx)
- if not scopes:
- return []
- images = reference_images(ctx)
- tasks: list[GenerationTask] = []
- for scope in scopes:
- files = list(scope.files)
- prompt = render(
- self.part_template, **scope_context(ctx, scope, files=files, expected_files=files)
- )
- ctx.record_prompt("generate", prompt)
- tasks.append(
- GenerationTask(
- label=f"baseline_{scope.label}",
- prompt=prompt,
- system=self.scope_system_prompt(ctx, scope),
- files_hint=files,
- round=0,
- kind="baseline",
- phase=0,
- temperature=0.5,
- thinking="medium",
- images=images,
- # scope.files is this session's whole world; the entry belongs to assemble
- edit_only=True,
- )
- )
- entry = ctx.runtime.expected_files(ctx.plan)[:1] # the assembly session's files: the entry, nothing else
- assemble = render(
- self.assemble_template, **base_prompt_context(ctx, files=entry, expected_files=entry)
- )
- ctx.record_prompt("assemble", assemble)
- tasks.append(
- GenerationTask(
- label="assemble",
- prompt=assemble,
- system=self.system_prompt(ctx),
- files_hint=entry,
- round=0,
- kind="baseline",
- phase=1,
- temperature=0.3,
- thinking="high",
- images=images,
- owns_entry=True, # the assembly session is the entry file's one owner
- )
- )
- ctx.events.emit(
- "generate.scoped",
- round=0,
- n_scopes=len(scopes),
- n_parts=sum(len(s.parts) for s in scopes),
- scopes=[{"label": s.label, "parts": s.names, "files": list(s.files)} for s in scopes],
- )
- return tasks
-
- def scope_system_prompt(self, ctx: RunContext, scope: PartScope) -> str:
- return language_system_prompt(ctx.language, role="scope",
- n_parts=len(scope.parts), names=", ".join(scope.names))
-
# ------------------------------------------------------------------ refine (scaffold hooks)
def extra_refine_tasks(self, ctx: RunContext, last: RoundRecord) -> Sequence[RefineTask]:
# NB: the `detail_budget` WARN is deliberately NOT turned into a refine task. Measured:
@@ -259,10 +163,15 @@ class StaticObjectTrack(BaseTrack):
def _refine_task(
self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool
) -> GenerationTask:
- # scope is real whenever the judge's targets resolved to files — parallel or not.
- # A group whose targets did not resolve (target "overall") keeps the whole tree.
- scoped = parallel or bool(group.files)
- files = group.files if scoped else ctx.runtime.expected_files(ctx.plan)
+ """The round's ONE whole-object session: every file in scope, edited in place; each
+ instruction line names the files its target owns. ``group`` is the round's single group
+ (no fan-out), its tasks already ordered gate ERRORs → acceptance → judge plan.
+
+ A single-shot call has no read tool: it sees only the files inlined for it, so when the
+ tasks name files it is fenced to them (``edit_only``, the entry still writable) — a model
+ told "the whole object" once could rewrite a part file it was never shown."""
+ fenced = ctx.single_shot and bool(group.files)
+ files = list(group.files) if fenced else ctx.runtime.expected_files(ctx.plan)
lines = compact_instructions(group.tasks, max_lines=ctx.policy.max_instructions_per_task)
prompt = render(
self.refine_template,
@@ -272,28 +181,51 @@ class StaticObjectTrack(BaseTrack):
tasks=lines,
targets=group.targets,
files=files,
- edit_only_these=scoped,
+ edit_only_these=fenced,
judge_summary=judge_digest(last),
measurement_notes=measurement_vs_plan(last, ctx.plan, ctx.language),
- current_files=refine_inline_files(ctx, files), # single-shot only
+ # single-shot only: the files the tasks name (all of them for an "overall" task)
+ current_files=refine_inline_files(ctx, files),
),
)
ctx.record_prompt("refine", prompt)
return GenerationTask(
- label=f"refine_{group.label}" if parallel else "refine",
+ label="refine",
prompt=prompt,
system=self.system_prompt(ctx),
files_hint=files,
round=index,
kind="refine",
temperature=0.4,
- thinking="medium",
images=reference_images(ctx) + judged_sheet(last),
- edit_only=scoped,
- owns_entry=True, # refine_object.j2 promises entry-file access even when scoped
+ edit_only=fenced,
+ owns_entry=True,
+ timeout_s=None if ctx.single_shot else object_session_window_s(ctx),
)
+#: 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
+
+
+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.
+
+ 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
+ return int(max(REFINE_MIN_WINDOW_S, min(float(ctx.settings.limits.agent_timeout_s), left)))
+
+
# ===================================================================== reference images
SILHOUETTE_GATE = "reference_silhouette"
IOU_REFINE_THRESHOLD = 0.6
diff --git a/harness/codeverse3d/tracks/steps.py b/harness/codeverse3d/tracks/steps.py
index 4ffa9987..7a2d6715 100644
--- a/harness/codeverse3d/tracks/steps.py
+++ b/harness/codeverse3d/tracks/steps.py
@@ -117,51 +117,17 @@ def load_round_journal(ws: Workspace) -> list[RoundRecord]:
def run_generation_tasks(ctx: RunContext, tasks: Sequence[GenerationTask], *,
steps: list[StepTime] | None = None) -> list[GenerationResult]:
- """Run tasks (parallel when > 1). Raises ``RoundFailed`` when none succeeded.
-
- ``GenerationTask.phase`` sequences the round: tasks run in parallel WITHIN a
- phase, phases in ascending order. Every task is phase 0 unless a track says
- otherwise, so this is a no-op for every existing caller; per-part scoped
- generation uses it so the assembly session sees the part files first. Each
- phase is one ``generate`` step in ``steps``.
- """
+ """Run tasks side by side — one ``generate`` step: its sessions share one clock. Raises
+ ``RoundFailed`` when none succeeded."""
if not tasks:
return []
- phases = sorted({t.phase for t in tasks})
- if len(phases) > 1:
- out: dict[int, GenerationResult] = {}
- ok_any = False
- for ph in phases:
- picked = [(i, t) for i, t in enumerate(tasks) if t.phase == ph]
- try:
- got = _run_phase(ctx, [t for _, t in picked], steps)
- except RoundFailed as e:
- # a phase in which nothing succeeded is not automatically a dead round:
- # the earlier phases may have written the parts. Record the failures
- # (and why they failed) and let the final check below decide.
- got = [GenerationResult(ok=False, notes="phase produced no change", label=t.label,
- transient=e.transient, quota=e.quota) for _, t in picked]
- for (i, _), r in zip(picked, got, strict=True):
- out[i] = r
- ok_any = ok_any or any(r.ok for r in got)
- results_seq = [out[i] for i in range(len(tasks))]
- if not ok_any:
- raise RoundFailed.of(results_seq, "no generation task succeeded")
- return results_seq
- return _run_phase(ctx, list(tasks), steps)
-
-
-def _run_phase(ctx: RunContext, tasks: Sequence[GenerationTask],
- steps: list[StepTime] | None = None) -> list[GenerationResult]:
- """One parallel batch of generation tasks — one ``generate`` step: its sessions run side
- by side, so they share one clock."""
def _one(task: GenerationTask) -> GenerationResult:
return generate_for(ctx, task)
# fan_out also for ONE task: a crashing generator (503 storm, parse error) becomes a failed
# result → RoundFailed (a refine round then stops the run as no_change) instead of killing it.
- with timed("generate", [] if steps is None else steps, round_index=tasks[0].round if tasks else None):
+ with timed("generate", [] if steps is None else steps, round_index=tasks[0].round):
results = fan_out(list(tasks), _one, max_workers=ctx.settings.limits.max_parallel_agents,
label="generate", item_name=lambda t: t.label)
out: list[GenerationResult] = []
@@ -176,9 +142,9 @@ def _run_phase(ctx: RunContext, tasks: Sequence[GenerationTask],
out.append(r)
if not any(r.ok for r in out):
if budget_stop is not None:
- raise budget_stop # nothing usable survived the phase
+ raise budget_stop # nothing usable survived the batch
raise RoundFailed.of(out, "no generation task succeeded")
- ctx.budget.check() # phase boundary: single-shot money is booked non-enforcing upstream
+ ctx.budget.check() # step boundary: single-shot money is booked non-enforcing upstream
return out
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 0f5b57c7..3ca44320 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -497,11 +497,11 @@ Best-of-N, refine planning and the asset ladder are sized at run time; they stay
```
round 0 "baseline": generate → build_with_repair → measure → gates → render → post-render gates → judge
- (object tracks, ≥ 8 plan parts, a language with one file per part, an agent backend: the baseline FANS OUT
- per part — phase 0 = one scoped session per attachment subtree (its parts + the planned boxes of the
- neighbours it must weld to + the shared detail advice, its own files only), phase 1 = ONE "assemble"
- session that owns the entry file, placement and the connectivity/contract gates. $C3D_SCOPED_PARTS=off
- restores the single whole-object session; single-shot always uses it.)
+ (object tracks, every language — D110 baseline-first: ONE session drafts the WHOLE object, every part
+ file + the entry (BaseTrack.baseline_tasks over generate_static.j2 / generate_articulated.j2), the brief
+ requiring every planned part at its box and joined before any detail, each file written once and then
+ edited; a part still the skeleton's box is a `placeholder_part` contract ERROR. The per-part scoped
+ baseline — 3-5 scope sessions + an "assemble" session, serial behind the workspace lock — is deleted.)
(--candidates N: N parallel baselines in <ws>/_cand/c<k>, quick 4-view judge, crashed candidate retried once,
selection build_ok → quick score → fewer gate errors → the earlier candidate; winner copied back, normal r00 follows)
then max_rounds refine rounds, EACH built on the round before it — FIXED rounds (owner, 2026-09-22): no pass,
@@ -509,7 +509,13 @@ plateau, regression or diminishing-returns stop, no rewrite or surface-detail ro
refine tasks = the previous round's gate ERRORS (fix hints, authoring-frame numbers) ∪ failed must-acceptance
∪ its judge improvement plan
(≤ 6 tasks, ≤ 6 compacted instruction lines each; reference runs add an IoU task when silhouette IoU < 0.6)
- fan out when ≥ 2 file-disjoint groups AND every task maps to files (threejs/blender parts, scene zones/assets/env)
+ (a placeholder part's ERROR first of all — orchestrator.build_refine_instructions)
+ 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
+ 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),
the other vendor CLIs have no turn cap at all; 28 was A/B'd and rejected, +$0.02/−0.21 score, docs/COST.md §17;
a cap the machine sets (C3D_AGENT_MAX_TURNS / limits.agent_max_turns; no profile sets one) still buys a wrap-up session
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index f22c970c..596f10ae 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -249,7 +249,9 @@ session grace. Process termination and final packaging can finish after the dead
expected to touch — used to attribute `files_changed`; harness-owned paths are dropped;
sessions on one workspace are serialised, so there is no sibling filter),
`edit_only` / `always_writable` (a scoped refine may overwrite only its hinted files +
-the entry file), `read_only: list[str]` (harness-owned files INSIDE the write roots the
+the entry file), **Δ D110** `effort: AgentEffort | None` (`Literal["low","medium","high"]`; filled from
+`GenerationTask.thinking` only when the caller asked — `tracks.generation.session_effort`; None = the
+backend's default; agy alone reads it, claude-code / codex keep their `Settings.agents` effort), `read_only: list[str]` (harness-owned files INSIDE the write roots the
session may read but never write — `contracts.common.HARNESS_OWNED_SRC[language]`, i.e.
`src/lib/` for scene_threejs / scene_blender (Δ D107: glsl_shader's seeded `src/recipes.glsl` is gone); `tracks/generation.py`
sets it on every job of the run and `agents/cli_common._enforce_scope` reverts a
@@ -267,7 +269,10 @@ live session per key machine-wide while keys last), outcome reported back
`<cache_dir>/agy_homes/` holds `.gemini/antigravity-cli/settings.json` = `{"modelProvider": "gemini"}` (without
it agy ignores `GEMINI_API_KEY` and asks for a login) + the MCP config, and is deleted after the session (the
tool trace is read from its conversation db first); argv `--model gemini-api://<bare id> --effort <e>`, effort
-from a `-low/-medium/-high` suffix, default `high`; usage priced at Gemini list price with
+(**Δ D110**, `backends.api_model_effort(model, job.effort)`): the id's `-low/-medium/-high` suffix, else
+`AgentJob.effort`, else `AGY_API_EFFORT` = `high` — no track asks for less, so every argon session runs at high
+(owner, 2026-10-15); the effort used is on the `invoke` transcript line, in `result.json` / `AgentResult.effort`
+and on the session's `cost.jsonl` row (`effort`, an extra column; claude-code / codex record theirs too); usage priced at Gemini list price with
output = output − thinking, thoughts = thinking (agy's output already includes thinking). KeyPoolExhausted never escapes
`run()` (→ `exit_reason=budget`). No retry loop in the backend: agy retries its own calls; a transient
death goes to the round loop's one retry, which takes a fresh key.
@@ -415,6 +420,11 @@ from codeverse3d.spatial.contract import check_contract # frame of fix
# (Δ 2026-08-30) check_contract adds ONE orientation finding on a StaticPlan (data.kind="orientation", pose lying|stood → ERROR,
# turned → WARN; planned_up_m, measured_up_m, best_axis): an extents-permutation test in the plan frame, 0 flags over
# 629 corpus measurements, fires on brilliana's c-clamp / gate-valve.
+ # (Δ D110) check_contract ERROR data.kind="placeholder_part" (contracts.artifacts.PLACEHOLDER_PART; tri_count, instances)
+ # when spatial.contract.is_placeholder(rows, plan_box_glb): every measured row ≤ PLACEHOLDER_MAX_TRIS (12) triangles,
+ # watertight with volume_m3 ≥ PLACEHOLDER_MIN_FILL (0.999) × its own box (open / unmeasured never fires),
+ # extents within PLACEHOLDER_TOL_M (1 mm) of the plan's, a single instance also at the plan centre — the skeleton's box
+ # in every object language, measured, never grepped. build_refine_instructions routes it ahead of every gate ERROR.
from codeverse3d.spatial.measure import measure_glb, world_transform, node_name_findings # (Δ 2026-08-30) world frames are composed
# by walking the graph's edge matrices (trimesh's get() dropped a root pivot's rotation); a GLB with duplicate / unnamed nodes
# lands a finding in Measurement.extra["findings"] — trimesh re-parents renamed nodes and the numbers are approximate
@@ -581,17 +591,13 @@ from codeverse3d.tracks.candidates import run_best_of_n, quick_render # N para
# candidates[])
from codeverse3d.tracks.articulated_object import default_motion_checks, expected_direction # gate "motion_direction"
from codeverse3d.tracks.static_object import silhouette_gate, reference_refine_tasks # gate "reference_silhouette" (IoU<0.6 → WARN + refine task)
-from codeverse3d.tracks.depth import depth_budget, DepthBudget, DETAIL_ADVICE, scope_groups, PartScope, \
- interfaces_text, scoped_generation_enabled # complexity-aware budgets + per-part scoped generation
+from codeverse3d.tracks.depth import depth_budget, DepthBudget, DETAIL_ADVICE # complexity-aware budgets
+ # (Δ D110: scope_groups / PartScope / interfaces_text / scoped_generation_enabled deleted with the scoped baseline)
depth_budget(plan, *, build_timeout_s=300) -> DepthBudget # min/target/max triangles + max_build_s sized from
# the plan's LEAF count (parts × instances × children); only budget_gate reads it — no prompt states it.
# DETAIL_ADVICE: the numberless "spend detail inside the planned parts" bullet the generate/refine
# templates show as {{ detail_advice }}
-scope_groups(plan, *, files_for, max_groups=6, parts_per_scope=3, min_parts=8) -> [PartScope]
- # [] = one session owns the object (small plan, no per-part file ownership, or $C3D_SCOPED_PARTS=off);
- # otherwise attachment-subtree groups whose files are disjoint, so the sessions run in parallel
-interfaces_text(plan, scope) -> str # the planned boxes of the neighbours this scope must weld to
-from codeverse3d.tracks.prompting import base_prompt_context, reference_images, scope_context, budget_for # Δ split out of
+from codeverse3d.tracks.prompting import base_prompt_context, reference_images, budget_for # Δ split out of
# Δ D107: select_cookbook_chapters / is_always_chapter / COOKBOOK_SYNONYMS and the graphics recipe seeding
# (tracks/graphics.seed_recipes, cookbook_functions, the "recipes" stage, Settings.limits.seed_recipes /
# C3D_SEED_RECIPES) are deleted with the cookbooks; base_prompt_context carries no cookbook_excerpt
@@ -608,10 +614,10 @@ from codeverse3d.tracks.generation import write_files # (ws, files, *, al
from codeverse3d.agents.cli_common import find_json_object, default_mcp_command # THE one JSON-envelope finder behind
# parse_claude_json / parse_agy_json; default_mcp_command(ws, *, language, track, round_index)
from codeverse3d.tracks.generation import generate, run_agent_task, parse_multifile, is_single_shot
-GenerationTask.phase: int = 0 # tasks run in parallel WITHIN a phase, phases in ascending order
- # (tracks.steps.run_generation_tasks). Only user: the scoped baseline — phase 0 = one session per
- # part group (`baseline_<parts>`, own files only), phase 1 = ONE `assemble` session that owns the
- # entry file and the placement gates. Every other caller is phase 0, i.e. unchanged.
+GenerationTask.thinking: Literal["", "off", "low", "medium", "high"] = "" # Δ D110: '' = nobody asked —
+ # a single-shot call thinks at SINGLE_SHOT_THINKING ("medium"), an agent session at its backend's default;
+ # anything else is explicit and also becomes AgentJob.effort (session_effort). GenerationTask.phase is
+ # deleted with its one user (the scoped baseline): run_generation_tasks runs one side-by-side batch.
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
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
index d0587212..4579f739 100644
--- a/harness/docs/RUNBOOK.md
+++ b/harness/docs/RUNBOOK.md
@@ -92,8 +92,11 @@ round, then ≈ $0.36 / ~7 min per refine (give scenes `--max-minutes 60`).
after the session; the tool trace is read from its conversation db first. `PUPPETEER_CACHE_DIR`
points the agent's shell at the real Chrome cache.
* argv `--model gemini-api://<bare id> --effort <low|medium|high>`: the id goes to the API
- verbatim (any model the key serves); effort from an agy-style `-low/-medium/-high` suffix,
- default `high` (the Gemini API's own default).
+ verbatim (any model the key serves); effort from an agy-style `-low/-medium/-high` suffix, else
+ `AgentJob.effort` (a task that explicitly asks — none does today), else `high` (the Gemini API's own
+ default; owner, 2026-10-15: argon runs at high on every track, D110). The effort used is on the
+ transcript's `invoke` line, in `result.json` and on the session's `cost.jsonl` row. An effort A/B is
+ the id suffix: `--generator agy:gemini-4-argon-medium`.
* Cost: priced at Gemini list price; agy's `output_tokens` already include `thinking_tokens`, so
output = output − thinking, thoughts = thinking (billed once).
* `--print-timeout` = `timeout_s` + the watchdog's `HARD_GRACE_S` (5 min) + 1 min, so the watchdog
diff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.md
index 8143b651..eb517d16 100644
--- a/harness/docs/SKILLS.md
+++ b/harness/docs/SKILLS.md
@@ -711,7 +711,7 @@ so; the rest are live.
routed set size fixed or it measures the cap, not the copy.
* **The prompt corpus no longer contradicts the connectivity gate on weld overlap (D107).**
`tracks/generate_static.j2` ("overlap neighbours by ≥ 0.002 m"), `tracks/assemble_static.j2`,
- `generate_static_part.j2`, `system/harness_contract.md` ("seams overlap by ≥ 2 mm") and three
+ `generate_static_part.j2` (both deleted by D110), `system/harness_contract.md` ("seams overlap by ≥ 2 mm") and three
cookbooks taught 2–5 mm, at or above `PENETRATION_WARN_M`; all of them now state the gate's
band (gap ≤ 2 mm, overlap ≤ 2 mm) and the cookbooks are gone. It was the single most likely
reason `c3d-part-contact` failed to move the number it targets: re-run that A/B on a
diff --git a/harness/tests/agents/test_agent_job_wiring.py b/harness/tests/agents/test_agent_job_wiring.py
index 058958de..9c984188 100644
--- a/harness/tests/agents/test_agent_job_wiring.py
+++ b/harness/tests/agents/test_agent_job_wiring.py
@@ -100,3 +100,26 @@ def test_empty_usage_cannot_bypass_the_clock_and_start_a_retry(tmp_ws: Workspace
with pytest.raises(BudgetExceeded):
run_agent_task(tmp_ws, agent=agent, task=GenerationTask(label="baseline", prompt="p"), budget=guard)
assert len(agent.jobs) == 1
+
+
[email protected]("thinking, effort", [("", None), ("off", None), ("low", "low"), ("medium", "medium"),
+ ("high", "high")])
+def test_the_task_effort_reaches_the_job_only_when_asked(tmp_ws: Workspace, thinking, effort):
+ """``GenerationTask.thinking`` '' (the default) leaves the backend's own effort — agy: high."""
+ agent = StubAgent()
+ run_agent_task(tmp_ws, agent=agent, task=GenerationTask(label="t", prompt="p", thinking=thinking))
+ assert agent.jobs[0].effort == effort
+
+
+def test_the_session_ledger_row_carries_the_effort_the_cli_ran_at(tmp_ws: Workspace):
+ from codeverse3d.cost.instrument import metered_agent, run_ledger
+ from codeverse3d.cost.ledger import load_ledger
+
+ class Ran(StubAgent):
+ def run(self, job):
+ return super().run(job).model_copy(update={"effort": "high"})
+
+ with run_ledger(tmp_ws.root, run="r"):
+ metered_agent(Ran()).run(AgentJob(workspace=str(tmp_ws.root), prompt="p", label="baseline"))
+ (row,) = load_ledger(tmp_ws.root)
+ assert row.model_extra.get("effort") == "high"
diff --git a/harness/tests/agents/test_antigravity.py b/harness/tests/agents/test_antigravity.py
index a9b44d37..c93f4ec6 100644
--- a/harness/tests/agents/test_antigravity.py
+++ b/harness/tests/agents/test_antigravity.py
@@ -172,7 +172,8 @@ def test_a_session_runs_on_a_pool_key_in_a_home_of_its_own(tmp_ws: Workspace, fa
assert res.usage.model == "gemini-4-argon" and res.usage.cost_usd > 0
# a bare id runs at the API's own default effort; no model at all is argon
assert AntigravityAgent("").model == DEFAULT_AGY_MODEL == "gemini-4-argon"
- assert AntigravityAgent("gemini-4-argon").model_args() == ["--model", "gemini-api://gemini-4-argon", "--effort", "high"]
+ bare = AgentJob(workspace=str(tmp_ws.root), prompt="p")
+ assert AntigravityAgent("gemini-4-argon").model_args(bare) == ["--model", "gemini-api://gemini-4-argon", "--effort", "high"]
# a 429 cools the key in the shared pool
monkeypatch.setenv("FAKE_MODE", "429")
res2 = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="api429", timeout_s=30, spatial_tools=False))
@@ -189,3 +190,40 @@ def test_without_keys_agy_is_unavailable_and_never_starts(tmp_ws: Workspace, fak
assert not ok and "API keys" in why
res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="nokey", timeout_s=30))
assert not res.ok and res.exit_reason == "error" and not (tmp_ws.src / "hello.txt").exists()
+
+
+def _effort_job(tmp_ws: Workspace, **kw) -> AgentJob:
+ return AgentJob(workspace=str(tmp_ws.root), prompt="hello", timeout_s=30, spatial_tools=False, **kw)
+
+
[email protected]("model, asked, runs_at", [
+ ("gemini-4-argon", None, "high"), # every track today: no ask → AGY_API_EFFORT (owner, 2026-10-15)
+ ("gemini-4-argon", "medium", "medium"), # an explicit ask reaches --effort
+ ("gemini-4-argon-low", "medium", "low"), # the model id's suffix still wins
+ ("gemini-4-argon-high", None, "high"),
+])
+def test_effort_reaches_the_argv_the_invoke_line_and_the_result(tmp_ws: Workspace, fake_bin, model, asked, runs_at):
+ a = AntigravityAgent(model, binary=fake_bin("agy", FAKE_AGY_API))
+ res = a.run(_effort_job(tmp_ws, label=f"e_{asked}", effort=asked))
+ assert res.ok, res.errors
+ assert json.loads((tmp_ws.src / "seen.json").read_text())["effort"] == runs_at
+ assert res.effort == runs_at
+ tdir = Path(res.transcript_path).parent
+ invoke = next(json.loads(ln) for ln in (tdir / "transcript.jsonl").read_text().splitlines()
+ if json.loads(ln)["kind"] == "invoke")
+ assert invoke["effort"] == runs_at and invoke["argv"][invoke["argv"].index("--effort") + 1] == runs_at
+ assert json.loads((tdir / "result.json").read_text())["effort"] == runs_at
+
+
+def test_object_and_scene_tasks_run_argon_at_high(tmp_ws: Workspace, fake_bin):
+ """The object tracks' draft / refine and the scene's zone task ask for no effort, so a bare
+ ``agy:gemini-4-argon`` session runs at high on every track (owner, 2026-10-15)."""
+ from codeverse3d.tracks.generation import GenerationTask, session_effort
+
+ a = AntigravityAgent("gemini-4-argon", binary=fake_bin("agy", FAKE_AGY_API))
+ for task in (GenerationTask(label="baseline", prompt="p", kind="baseline"),
+ GenerationTask(label="refine", prompt="p", kind="refine", temperature=0.4),
+ GenerationTask(label="zone_quay", prompt="p", kind="zone")):
+ assert session_effort(task) is None
+ res = a.run(_effort_job(tmp_ws, label=task.label, effort=session_effort(task)))
+ assert res.ok and json.loads((tmp_ws.src / "seen.json").read_text())["effort"] == "high"
diff --git a/harness/tests/orchestrator_tracks/test_baseline_first.py b/harness/tests/orchestrator_tracks/test_baseline_first.py
new file mode 100644
index 00000000..91b556f3
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_baseline_first.py
@@ -0,0 +1,142 @@
+"""D110 baseline-first: ONE session drafts the whole object, ONE session refines it in place per
+round, gate ERRORs first — a part still the skeleton's placeholder before anything else."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse3d.contracts.artifacts import (
+ PLACEHOLDER_PART,
+ BuildResult,
+ GateFinding,
+ GateReport,
+ ImprovementItem,
+ Judgment,
+ Severity,
+)
+from codeverse3d.contracts.common import Language, Track
+from codeverse3d.contracts.plan import ArticulatedPlan
+from codeverse3d.contracts.run import RoundRecord
+from codeverse3d.orchestrator import RunState
+from codeverse3d.proc import EventLog
+from codeverse3d.tracks.articulated_object import ArticulatedObjectTrack
+from codeverse3d.tracks.generation import session_effort
+from codeverse3d.tracks.planner import plan_example
+from codeverse3d.tracks.static_object import StaticObjectTrack
+from codeverse3d.workspace import Workspace
+
+from .conftest import make_spec
+from .fakes import FakeAgent, FakeJudge, FakeRuntime, FakeServices, _planner
+from .test_write_scope import _big_plan
+
+
+def _ctx(tmp_path, settings, language: Language, plan):
+ ws = Workspace(tmp_path / "runs" / "d").create()
+ track = StaticObjectTrack(services=FakeServices(), agent=FakeAgent(lambda job, ws: None), settings=settings,
+ runtime=FakeRuntime(language))
+ ctx = track.build_context(make_spec(language=language, generator="fake-agent:m"), ws,
+ EventLog(ws.events_path), RunState(slug="d"))
+ ctx.plan = plan
+ return track, ctx
+
+
[email protected]("language", [Language.THREEJS, Language.BLENDER, Language.CADQUERY])
+def test_round0_is_one_session_owning_every_part_file_and_the_entry(tmp_path, settings, language):
+ """An 8-part plan was split into 3-5 serial scope sessions + an assemble session before D110."""
+ track, ctx = _ctx(tmp_path, settings, language, _big_plan(10))
+ (draft,) = track.baseline_tasks(ctx)
+ files = ctx.runtime.expected_files(ctx.plan)
+ assert draft.label == "baseline" and draft.kind == "baseline" and draft.round == 0
+ assert draft.files_hint == files and draft.owns_entry and not draft.edit_only
+ if language is not Language.CADQUERY: # one file per part + the entry
+ assert len(files) == 1 + len(ctx.plan.parts)
+ # the object tasks ask for no effort: the session runs at the backend's default (agy: high)
+ assert draft.thinking == "" and session_effort(draft) is None
+ assert "The whole object first" in draft.prompt and "placeholder_part" in draft.prompt
+ assert "targeted edits" in draft.prompt
+
+
+def _last(plan) -> RoundRecord:
+ body, fitting = plan.parts[0].name, plan.parts[3].name
+ gates = [
+ GateReport.of("connectivity", [GateFinding(gate="connectivity", severity=Severity.ERROR, target=body,
+ message=f"{body} floats 12 mm", data={"kind": "floating"})]),
+ GateReport.of("contract", [GateFinding(gate="contract", severity=Severity.ERROR, target=fitting,
+ message=f"plan part '{fitting}' is still the skeleton's placeholder box",
+ data={"kind": PLACEHOLDER_PART})]),
+ ]
+ j = Judgment(rubric="r", scores={}, overall=0.55, passed=False, improvement_plan=[
+ ImprovementItem(target=plan.parts[1].name, kind="geometry", instruction="add the bolt heads", priority=1),
+ ImprovementItem(target=plan.parts[2].name, kind="material", instruction="darker steel", priority=2)])
+ return RoundRecord(index=0, kind="baseline", judgment=j, gates=gates, commit="c0",
+ build=BuildResult(ok=True, language="threejs"))
+
+
+def test_refine_round_is_one_whole_object_session_with_placeholder_errors_first(tmp_path, settings):
+ """Four targets in four different part files used to fan out into four sessions."""
+ track, ctx = _ctx(tmp_path, settings, Language.THREEJS, _big_plan(8))
+ last = _last(ctx.plan)
+ tasks, lines = track.refine_tasks(ctx, last)
+ (refine,) = tasks
+ assert refine.label == "refine" and refine.kind == "refine" and refine.round == 1
+ assert refine.files_hint == ctx.runtime.expected_files(ctx.plan) and not refine.edit_only
+ assert refine.owns_entry and session_effort(refine) is None
+ # gate ERRORs (the placeholder before the floating part) → judge plan, in that order
+ assert "placeholder" in lines[0] and "floats" in lines[1]
+ assert "bolt heads" in lines[2] and "darker steel" in lines[3]
+ body = refine.prompt
+ assert body.index("placeholder box") < body.index("floats 12 mm") < body.index("bolt heads")
+ assert "Edit in place" in body and "never rewrite a whole file" in body
+ assert "Measured vs planned" in body
+
+
+def test_articulated_runs_one_draft_and_one_refine_session_end_to_end(tmp_path, settings):
+ """urdf_blender inherits the shape: one ``baseline`` session, then one ``refine`` session per round."""
+ plan = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))
+ agent = FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label}\n",
+ "src/robot.urdf": "<robot name='x'/>\n"})
+ judge = FakeJudge(scores=(0.6, 0.8), targets=tuple(p.name for p in plan.parts[:2]))
+ track = ArticulatedObjectTrack(services=FakeServices(), judge=judge, agent=agent,
+ planner_model=_planner(plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.URDF_BLENDER))
+ rec = track.run(make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER, max_rounds=1),
+ Workspace(tmp_path / "runs" / "art"))
+ assert [r.kind for r in rec.rounds] == ["baseline", "refine"]
+ sessions = [j.label for j in agent.jobs]
+ assert sessions == ["baseline", "refine"], sessions
+ assert all(j.effort is None for j in agent.jobs) # the backend's default effort (agy: high)
+
+
+def test_single_shot_refine_is_fenced_to_the_files_it_is_shown(tmp_path, settings):
+ """A single-shot call has no read tool and sees only the inlined files: told "the whole object"
+ it could rewrite a part file it was never shown, so it keeps the files its tasks name."""
+ track, ctx = _ctx(tmp_path, settings, Language.THREEJS, _big_plan(8))
+ ctx.agent_id = "single-shot:gemini:x"
+ (refine,), _ = track.refine_tasks(ctx, _last(ctx.plan))
+ named = {f for p in ctx.plan.parts[:4] for f in ctx.runtime.files_for(ctx.plan, p.name)}
+ assert set(refine.files_hint) == named and refine.edit_only and refine.owns_entry
+ assert len(refine.files_hint) < len(ctx.runtime.expected_files(ctx.plan))
+ assert "Change only these files" in refine.prompt and "the whole object;" not in refine.prompt
+ assert refine.timeout_s is None # a single-shot call's own wait applies
+
+
+def test_refine_session_ends_before_the_run_clock_so_the_round_is_judged(tmp_path, settings):
+ """The baseline-first smoke's blender refine started at 25.8 of 60 min with a 30-min window: the
+ 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
+
+ track, ctx = _ctx(tmp_path, settings, Language.BLENDER, _big_plan(8))
+ 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))
+ 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 > 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))
+ assert last_minute.timeout_s == REFINE_MIN_WINDOW_S
diff --git a/harness/tests/orchestrator_tracks/test_generation_depth.py b/harness/tests/orchestrator_tracks/test_generation_depth.py
deleted file mode 100644
index c6b016e5..00000000
--- a/harness/tests/orchestrator_tracks/test_generation_depth.py
+++ /dev/null
@@ -1,86 +0,0 @@
-"""Complexity-aware depth budgets and scoped baselines."""
-
-from __future__ import annotations
-
-from codeverse3d.contracts.common import Language
-from codeverse3d.conventions import to_snake
-from codeverse3d.tracks.depth import (
- PartScope,
- interfaces_text,
- scope_groups,
-)
-
-from .conftest import make_spec
-from .fakes import FakeAgent, FakeRuntime, FakeServices
-
-
-def _files_for(name):
- return [f"src/parts/{to_snake(name)}.py"]
-
-
-# ----------------------------------------------------------------------------- scoping
-def test_scope_groups_partition_the_attachment_tree_and_name_the_outside_neighbours(chair_plan):
- scopes = scope_groups(chair_plan, files_for=_files_for, max_groups=6, min_parts=3)
- assert len(scopes) >= 2
- names = [n for s in scopes for n in s.names]
- assert sorted(names) == sorted(p.name for p in chair_plan.parts) # every part owned exactly once
- files = [f for s in scopes for f in s.files]
- assert len(files) == len(set(files)) # file-disjoint: safe in parallel
- # Backrest and Armrest both hang off BackLeg → the subtree stays together
- by_part = {n: i for i, s in enumerate(scopes) for n in s.names}
- assert by_part["Backrest"] == by_part["BackLeg"] == by_part["Armrest"]
- assert scope_groups(chair_plan, files_for=_files_for, min_parts=99) == [] # small plan
- assert scope_groups(chair_plan, files_for=None, min_parts=3) == [] # no per-part files
- assert scope_groups(chair_plan, files_for=_files_for, max_groups=1, min_parts=3) == []
- # the interface table names only the neighbours outside the scope
- backleg = next(s for s in scopes if "BackLeg" in s.names)
- text = interfaces_text(chair_plan, backleg)
- rows = [ln for ln in text.splitlines() if ln.startswith("| ") and "---" not in ln][1:]
- assert rows and all("Seat" in r for r in rows) # BackLeg attaches to Seat, owned elsewhere
- inside = set(backleg.names)
- for row in rows: # a neighbour is never a part of this scope
- assert row.split("|")[3].strip() not in inside
- empty = interfaces_text(chair_plan, PartScope(parts=tuple(chair_plan.parts), files=("x",)))
- assert "no parts outside this scope" in empty
-
-
-# ----------------------------------------------------------------------------- the track wiring
-def _ctx(tmp_path, plan, settings, *, language=Language.THREEJS, agent_id="fake-agent:m"):
- from codeverse3d.orchestrator import RunState
- from codeverse3d.proc import EventLog
- from codeverse3d.tracks.static_object import StaticObjectTrack
- from codeverse3d.workspace import Workspace
-
- ws = Workspace(tmp_path / "runs" / "d").create()
- track = StaticObjectTrack(services=FakeServices(), agent=FakeAgent(lambda job: None), settings=settings,
- runtime=FakeRuntime(language))
- spec = make_spec(language=language, generator=agent_id)
- ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState(slug="d"))
- ctx.plan = plan
- return track, ctx
-
-
-def test_phases_run_in_order_and_a_failed_phase_does_not_kill_the_round(tmp_path, chair_plan, settings):
- """``run_generation_tasks`` is the only place that knows about phases."""
- from codeverse3d.tracks.generation import GenerationResult, GenerationTask
- from codeverse3d.tracks.steps import run_generation_tasks
-
- track, ctx = _ctx(tmp_path, chair_plan, settings)
- order: list[str] = []
-
- def fake_generate(ws, *, agent_id, task, **kw):
- order.append(task.label)
- return GenerationResult(ok=task.label != "b", label=task.label, notes="")
-
- import codeverse3d.tracks.common as common # the one seam every stage generates through
- orig = common.generate
- common.generate = fake_generate
- try:
- tasks = [GenerationTask(label="a", prompt="p", phase=0), GenerationTask(label="b", prompt="p", phase=0),
- GenerationTask(label="z", prompt="p", phase=1)]
- out = run_generation_tasks(ctx, tasks)
- finally:
- common.generate = orig
- assert order.index("z") == 2 # phase 1 ran last
- assert [r.label for r in out] == ["a", "b", "z"] # results keep the caller's order
- assert [r.ok for r in out] == [True, False, True]
diff --git a/harness/tests/orchestrator_tracks/test_write_scope.py b/harness/tests/orchestrator_tracks/test_write_scope.py
index 9f980dd1..308b7d20 100644
--- a/harness/tests/orchestrator_tracks/test_write_scope.py
+++ b/harness/tests/orchestrator_tracks/test_write_scope.py
@@ -1,4 +1,4 @@
-"""Write-scope enforcement at the task layer: envelope scope, harness-owned paths, scoped constructors."""
+"""Write-scope enforcement at the task layer: envelope scope, harness-owned paths, the constructors' scopes."""
from __future__ import annotations
@@ -134,20 +134,19 @@ def _round(i: int, score: float) -> RoundRecord:
build=BuildResult(ok=True, language="threejs"))
-def test_scoped_static_constructors_enforce_their_file_sets(tmp_path, settings):
+def test_static_constructors_own_the_whole_object(tmp_path, settings):
+ """D110: round 0 is ONE draft session over every part file + the entry, and the refine round's
+ one session edits the whole object in place — nothing is fenced to a part subset."""
track, ctx = _static_ctx(tmp_path, settings)
- tasks = track.baseline_tasks(ctx)
- parts, assemble = tasks[:-1], tasks[-1]
- assert len(parts) >= 2
- assert all(t.edit_only and not t.owns_entry for t in parts), "part sessions are scoped"
- assert assemble.owns_entry and not assemble.edit_only, "assemble owns the entry"
+ (draft,) = track.baseline_tasks(ctx)
+ assert draft.owns_entry and not draft.edit_only
+ assert draft.files_hint == ctx.runtime.expected_files(ctx.plan)
last = _round(2, 0.62)
- # refine keeps entry access: the prompt promises it ("edit the entry file to import a new part")
group = TaskGroup(tasks=[RefineTask(target="Body", kind="geometry", instruction="thicken",
priority=2, files=["src/parts/body.js"])],
files=["src/parts/body.js"])
- rt = track._refine_task(ctx, group, last, 2, parallel=True)
- assert rt.edit_only and rt.owns_entry
+ rt = track._refine_task(ctx, group, last, 2, parallel=False)
+ assert rt.owns_entry and not rt.edit_only and rt.files_hint == ctx.runtime.expected_files(ctx.plan)
def test_scene_constructors_enforce_their_file_sets(tmp_path, settings, monkeypatch):
diff --git a/harness/tests/prompts/manifest.py b/harness/tests/prompts/manifest.py
index ca427b5a..2c9f9db3 100644
--- a/harness/tests/prompts/manifest.py
+++ b/harness/tests/prompts/manifest.py
@@ -366,7 +366,8 @@ class Rig:
# ============================================================================ the scenarios
def machine() -> StaticPlan:
- """An 11-part object: past the scoped-baseline threshold, with a real attachment tree."""
+ """An 11-part object with a real attachment tree: still ONE draft session and ONE refine session (D110 —
+ the deleted scoped baseline split it into four sessions)."""
parts = [PartPlan(name="Body", role="main mass", description="the shell", bbox=BBox(center=(0, 0.5, 0), extents=(0.6, 1.0, 0.4)))]
parts += [PartPlan(name=f"Fitting{i}", role=f"fitting {i}", description="a fitting with a bevel", attach_to="Body",
bbox=BBox(center=(0.05 * i, 0.2 + 0.05 * i, 0.1), extents=(0.05, 0.05, 0.05))) for i in range(10)]
@@ -420,8 +421,8 @@ SCENARIOS: dict[str, tuple[Track, Language, dict[str, Any], Callable[[Rig], None
"static_object.threejs.agent.fresh": (S, Language.THREEJS, {"services_kw": {"contract_errors": 1}},
lambda r: r.run(rounds=2)),
"static_object.threejs.agent.resume": (S, Language.THREEJS, {}, _two_runs(0, 1)),
- "static_object.threejs.agent.scoped": (S, Language.THREEJS, {"plan": machine(), "targets": ("Body", "Fitting0", "Fitting5")},
- lambda r: r.run(rounds=1)),
+ "static_object.threejs.agent.many_parts": (S, Language.THREEJS, {"plan": machine(), "targets": ("Body", "Fitting0", "Fitting5")},
+ lambda r: r.run(rounds=1)),
"static_object.blender.agent.best_of_2": (S, Language.BLENDER, {}, lambda r: r.run(rounds=1, candidates=2)),
"static_object.cadquery.agent.rebuild": (S, Language.CADQUERY, {"fail": REBUILD, "services_kw": {"contract_errors": 2}},
lambda r: r.run(rounds=2)),
diff --git a/harness/tests/prompts/test_files.py b/harness/tests/prompts/test_files.py
index 89bf933c..ecd65d66 100644
--- a/harness/tests/prompts/test_files.py
+++ b/harness/tests/prompts/test_files.py
@@ -38,5 +38,5 @@ def test_every_language_ships_a_system_prompt_and_a_contract_and_no_cookbook() -
assert not (PROMPTS_DIR / language_prompt(lang, "cookbook.md")).is_file(), (lang.value, "ships a cookbook")
assert language_text(lang, "cookbook.md") == ""
assert language_prompt(Language.URDF_BLENDER, "contract.md") == "urdf/contract.md"
- for role in ("scope", "repair"):
+ for role in ("asset", "repair"):
assert (PROMPTS_DIR / "system" / f"role_{role}.j2").is_file(), role
diff --git a/harness/tests/spatial_tools/test_placeholder_gate.py b/harness/tests/spatial_tools/test_placeholder_gate.py
new file mode 100644
index 00000000..1f2520fb
--- /dev/null
+++ b/harness/tests/spatial_tools/test_placeholder_gate.py
@@ -0,0 +1,188 @@
+"""The ``placeholder_part`` contract ERROR (D110): a plan part still the skeleton's box.
+
+Pure rule on synthetic measurements, then each object language's REAL skeleton built and measured:
+every part fires; a part rebuilt as real geometry at the same plan box does not."""
+
+from __future__ import annotations
+
+import shutil
+
+import pytest
+
+from codeverse3d.config import get_settings
+from codeverse3d.contracts.artifacts import (
+ PLACEHOLDER_PART,
+ GateFinding,
+ GateReport,
+ Measurement,
+ PartMeasure,
+ Severity,
+)
+from codeverse3d.contracts.common import Language
+from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan
+from codeverse3d.orchestrator import build_refine_instructions
+from codeverse3d.spatial.contract import (
+ PLACEHOLDER_MAX_TRIS,
+ check_contract,
+ is_placeholder,
+ plan_bbox_to_glb,
+)
+from codeverse3d.workspace import Workspace
+
+
+def _plan() -> StaticPlan:
+ return StaticPlan(
+ object_name="SideTable", summary="A small side table.",
+ overall_bbox=BBox(center=(0, 0, 0.3), extents=(0.5, 0.5, 0.6)),
+ parts=[
+ PartPlan(name="TableTop", role="top", description="slab", bbox=BBox(center=(0, 0, 0.58), extents=(0.5, 0.5, 0.04))),
+ PartPlan(name="Leg", role="support", description="leg", bbox=BBox(center=(0.21, 0.21, 0.28), extents=(0.04, 0.04, 0.56)),
+ attach_to="TableTop", symmetry="mirror_x", instances=4),
+ PartPlan(name="Shelf", role="shelf", description="round shelf",
+ bbox=BBox(center=(0, 0, 0.15), extents=(0.42, 0.42, 0.02)), attach_to="Leg"),
+ ],
+ acceptance=[],
+ )
+
+
+def _row(name: str, box: BBox, tris: int, dx: float = 0.0, fill: float | None = 1.0) -> PartMeasure:
+ """A measured row at ``box``; ``fill`` = volume / box volume (None = not watertight)."""
+ lo = [c - e / 2 for c, e in zip(box.center, box.extents, strict=True)]
+ hi = [c + e / 2 for c, e in zip(box.center, box.extents, strict=True)]
+ vol = None if fill is None else fill * box.extents[0] * box.extents[1] * box.extents[2]
+ return PartMeasure(name=name, bbox_min=(lo[0] + dx, lo[1], lo[2]), bbox_max=(hi[0] + dx, hi[1], hi[2]), tri_count=tris,
+ watertight=fill is not None, volume_m3=vol)
+
+
+def test_rule_is_triangles_and_the_plan_box_to_a_millimetre():
+ box = plan_bbox_to_glb(_plan().parts[2].bbox, "blender")
+ assert is_placeholder([_row("Shelf", box, PLACEHOLDER_MAX_TRIS)], box)
+ assert not is_placeholder([_row("Shelf", box, 96)], box) # real geometry, same box
+ assert not is_placeholder([_row("Shelf", box, 12, dx=0.002)], box) # moved 2 mm: someone built it
+ assert not is_placeholder([_row("Shelf", box, 0)], box) # tris not measured
+ # a real 12-triangle hexahedron at its plan box: the tapered cadquery fretboard of
+ # loop_argon_static iter_01 mus_med_acoustic_guitar (fill 0.879), a wedge, an open pane
+ assert not is_placeholder([_row("Shelf", box, 12, fill=0.879)], box)
+ assert not is_placeholder([_row("Shelf", box, 8, fill=0.5)], box)
+ assert not is_placeholder([_row("Shelf", box, 2, fill=None)], box)
+ assert not is_placeholder([], box)
+ # instances: the copies sit wherever the symmetry put them — only their size is the plan's
+ leg = plan_bbox_to_glb(_plan().parts[1].bbox, "blender")
+ copies = [_row(f"Leg_{i}", leg, 12, dx=-0.42 * (i % 2)) for i in range(4)]
+ assert is_placeholder(copies, leg)
+ assert not is_placeholder(copies[:3] + [_row("Leg_3", leg, 200)], leg) # one real leg: being built
+
+
+def test_a_bare_box_built_exactly_to_the_plan_is_taken_for_the_placeholder():
+ """The known limit, pinned: measurement alone cannot tell a real bare 12-triangle box at the
+ plan's millimetre from the skeleton's box, so it fires. Over the loop_argon iter_00/01 corpus
+ (942 part rows) no such real part existed — every hit was a byte-unchanged skeleton file."""
+ box = plan_bbox_to_glb(_plan().parts[0].bbox, "threejs")
+ assert is_placeholder([_row("TableTop", box, 12)], box)
+ assert not is_placeholder([_row("TableTop", box, 20)], box) # the same box, segmented once
+
+
+def test_gate_finding_is_typed_and_routes_first():
+ plan = _plan()
+ rows = [_row("TableTop", plan_bbox_to_glb(plan.parts[0].bbox, "blender"), 400),
+ *[_row(f"Leg_{i}", plan_bbox_to_glb(plan.parts[1].bbox, "blender"), 12, dx=-0.42 * (i % 2)) for i in range(4)],
+ _row("Shelf", plan_bbox_to_glb(plan.parts[2].bbox, "blender"), 12)]
+ lo, hi = (-0.25, 0.0, -0.25), (0.25, 0.6, 0.25)
+ m = Measurement(bbox_min=lo, bbox_max=hi, extents=(0.5, 0.6, 0.5), center=(0, 0.3, 0), tri_count=472,
+ n_meshes=6, n_islands=6, parts=rows)
+ report = check_contract(m, plan, language="blender")
+ hits = [f for f in report.findings if f.data.get("kind") == PLACEHOLDER_PART]
+ assert {f.target for f in hits} == {"Leg", "Shelf"} and all(f.severity is Severity.ERROR for f in hits)
+ assert not report.passed and "placeholder box" in hits[0].message and "planned size" in hits[0].fix_hint
+ floating = GateReport.of("connectivity", [GateFinding(gate="connectivity", severity=Severity.ERROR,
+ target="TableTop", message="floats")])
+ tasks = build_refine_instructions(None, [floating, report], [], plan)
+ assert [t.target for t in tasks[:2]] == ["Leg", "Shelf"] and tasks[2].target == "TableTop"
+
+
+# ----------------------------------------------------------------------------- each real skeleton
+def _placeholders(glb: str, language: str) -> set[str]:
+ from codeverse3d.spatial.measure import measure_glb
+
+ report = check_contract(measure_glb(glb), _plan(), language=language)
+ return {f.target for f in report.findings if f.data.get("kind") == PLACEHOLDER_PART}
+
+
+def _edit(path, old: str, new: str) -> None:
+ text = path.read_text()
+ assert old in text, f"{old!r} not in {path}"
+ path.write_text(text.replace(old, new))
+
+
+def test_blender_skeleton_fires_and_a_built_part_does_not(tmp_path):
+ b = get_settings().resolve_blender()
+ if not b or (not shutil.which(b) and not b.startswith("/")):
+ pytest.skip("no Blender binary")
+ from codeverse3d.languages.blender import BlenderRuntime
+
+ ws, rt = Workspace(tmp_path / "b").create(), BlenderRuntime(blender=b)
+ rt.skeleton(ws, _plan())
+ r = rt.build(ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ assert _placeholders(r.glb_path, "blender") == {"TableTop", "Leg", "Shelf"}
+ _edit(ws.src / "parts" / "shelf.py", 'return add_box("Shelf", SHELF_CENTER, SHELF_EXTENTS, mat)',
+ 'bpy.ops.mesh.primitive_cylinder_add(vertices=32, radius=0.21, depth=0.02, location=SHELF_CENTER)\n'
+ ' obj = bpy.context.object\n obj.name = "Shelf"\n obj.data.materials.append(mat)\n return obj')
+ r = rt.build(ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ assert _placeholders(r.glb_path, "blender") == {"TableTop", "Leg"}
+
+
+def test_cadquery_skeleton_fires_and_a_built_part_does_not(tmp_path):
+ pytest.importorskip("cadquery")
+ from codeverse3d.languages.cadquery import CadQueryRuntime
+
+ ws, rt = Workspace(tmp_path / "c").create(), CadQueryRuntime()
+ rt.skeleton(ws, _plan())
+ r = rt.build(ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ assert _placeholders(r.glb_path, "cadquery") == {"TableTop", "Leg", "Shelf"}
+ _edit(ws.src / "model.py", 'cq.Workplane("XY").box(0.420, 0.420, 0.020)',
+ 'cq.Workplane("XY").box(0.420, 0.420, 0.020).edges("|Z").fillet(0.02)')
+ r = rt.build(ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ assert _placeholders(r.glb_path, "cadquery") == {"TableTop", "Leg"}
+
+
+def test_cadquery_tapered_extrude_at_its_plan_box_does_not_fire(tmp_path):
+ """A real tapered part (a fretboard: trapezoid outline extruded) is 12 triangles and sits
+ exactly on its plan box, yet does not fill it — it was built, not left as the skeleton."""
+ pytest.importorskip("cadquery")
+ from codeverse3d.languages.cadquery import CadQueryRuntime
+
+ ws, rt = Workspace(tmp_path / "f").create(), CadQueryRuntime()
+ rt.skeleton(ws, _plan())
+ _edit(ws.src / "model.py", 'cq.Workplane("XY").box(0.420, 0.420, 0.020)',
+ 'cq.Workplane("XY").polyline([(-0.21, -0.21), (0.21, -0.21), (0.15, 0.21), (-0.15, 0.21)])'
+ '.close().extrude(0.020).translate((0, 0, -0.010))')
+ r = rt.build(ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ from codeverse3d.spatial.measure import measure_glb
+
+ shelf = [p for p in measure_glb(r.glb_path).parts if p.name.lower() == "shelf"]
+ assert shelf and shelf[0].tri_count <= PLACEHOLDER_MAX_TRIS # the case the fill rule exists for
+ assert _placeholders(r.glb_path, "cadquery") == {"TableTop", "Leg"}
+
+
+def test_threejs_skeleton_fires_and_a_built_part_does_not(tmp_path):
+ if shutil.which("node") is None:
+ pytest.skip("node not available")
+ from codeverse3d.languages.threejs import ThreeJsRuntime
+
+ ws, rt = Workspace(tmp_path / "t").create(), ThreeJsRuntime()
+ rt.skeleton(ws, _plan())
+ r = rt.build(ws)
+ assert r.ok, (r.error_type, r.error_message)
+ assert _placeholders(r.glb_path, Language.THREEJS.value) == {"TableTop", "Leg", "Shelf"}
+ _edit(ws.src / "parts" / "shelf.js", "new THREE.BoxGeometry(size[0], size[1], size[2])",
+ "new THREE.BoxGeometry(size[0], size[1], size[2], 4, 1, 4)")
+ r = rt.build(ws)
+ assert r.ok, (r.error_type, r.error_message)
+ assert _placeholders(r.glb_path, Language.THREEJS.value) == {"TableTop", "Leg"}
diff --git a/harness/tests/threejs_render/test_build.py b/harness/tests/threejs_render/test_build.py
index 29861a65..573c3338 100644
--- a/harness/tests/threejs_render/test_build.py
+++ b/harness/tests/threejs_render/test_build.py
@@ -111,7 +111,7 @@ def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace, bare_root
from codeverse3d.spatial.contract import check_contract
posts = (" const mat = new THREE.MeshStandardMaterial({ color: 0x885533 });\n"
- " const posts = new THREE.InstancedMesh(new THREE.BoxGeometry(0.05, 1, 0.05), mat, 10); posts.name = 'Posts';\n"
+ " const posts = new THREE.InstancedMesh(new THREE.BoxGeometry(0.05, 1, 0.05, 1, 2, 1), mat, 10); posts.name = 'Posts';\n"
" const m = new THREE.Matrix4();\n"
" for (let i = 0; i < 10; i++) { m.makeTranslation(-2.25 + i * 0.5, 0.5, 0); posts.setMatrixAt(i, m); posts.setColorAt(i, new THREE.Color(i % 2 ? 0xff0000 : 0x00ff00)); }\n"
" posts.instanceMatrix.needsUpdate = true;\n")
@@ -119,7 +119,7 @@ def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace, bare_root
body = posts + " return posts; }\n"
else:
body = (" const g = new THREE.Group(); g.name = 'Fence';\n" + posts + " g.add(posts);\n"
- " const rail = new THREE.Mesh(new THREE.BoxGeometry(4.6, 0.05, 0.03), mat); rail.name = 'Rail'; rail.position.set(0, 1.025, 0); g.add(rail);\n"
+ " const rail = new THREE.Mesh(new THREE.BoxGeometry(4.6, 0.05, 0.03, 2, 1, 1), mat); rail.name = 'Rail'; rail.position.set(0, 1.025, 0); g.add(rail);\n"
" return g; }\n")
(stool_ws.src / "object.js").write_text("import * as THREE from 'three';\nexport function build(T) {\n" + body)
res = ThreeJsRuntime().build(stool_ws)
@@ -131,7 +131,7 @@ def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace, bare_root
names = [f"Posts_{i}" for i in range(10)] + ([] if bare_root else ["Rail"])
m = measure_glb(res.glb_path)
assert sorted(p.name for p in m.parts) == sorted(names)
- assert m.tri_count == 12 * len(names) and abs(m.ground_gap_m) < 1e-3
+ assert m.tri_count == 20 * len(names) and abs(m.ground_gap_m) < 1e-3 # 2-segment boxes: 20 triangles each
p9 = next(p for p in m.parts if p.name == "Posts_9")
assert np.allclose(p9.bbox_min, [2.225, 0.0, -0.025], atol=1e-3)
assert np.allclose(p9.bbox_max, [2.275, 1.0, 0.025], atol=1e-3)
@@ -142,6 +142,8 @@ def test_build_bakes_instanced_meshes_for_trimesh(stool_ws: Workspace, bare_root
bbox=BBox(center=(0, 1.025, 0), extents=(4.6, 0.05, 0.03))))
plan = StaticPlan(object_name="Fence", summary="s", overall_bbox=BBox(center=(0, 0.525, 0), extents=(4.6, 1.05, 0.05)),
parts=parts)
+ # the boxes are segmented (20 triangles), so they are not the skeleton's 12-triangle placeholder
+ # (D110; a bare box exactly at its plan box is pinned in test_placeholder_gate)
assert [f.message for f in check_contract(m, plan, language="threejs").findings
if f.severity.value != "info"] == []
if not bare_root: