Skip to content

Official Codebase of 3DCodeVerse

Python

fewer_turns (1/3): build folds the gates in, write_file/edit_file return a lint verdict — behind CV3D_FEWER_TURNS, default OFF

gaoypengba596cf07f60
diff --git a/harness/codeverse/agents/api_agent.py b/harness/codeverse/agents/api_agent.py
index 35d87c5e..dfd98abe 100644
--- a/harness/codeverse/agents/api_agent.py
+++ b/harness/codeverse/agents/api_agent.py
@@ -103,6 +103,7 @@ class _Loop:
allow_shell=job.api.allow_shell,
edit_only=job.files_hint if job.edit_only else None,
always_writable=job.always_writable,
+ language=job.language,
)
self.spatial: SpatialTools | None = None
if job.spatial_tools:
diff --git a/harness/codeverse/agents/api_tools.py b/harness/codeverse/agents/api_tools.py
index 4c6fc95c..ef4bc1b8 100644
--- a/harness/codeverse/agents/api_tools.py
+++ b/harness/codeverse/agents/api_tools.py
@@ -22,8 +22,9 @@ from pathlib import Path
from typing import Any
from codeverse.agents.watchdog import run_with_watchdog
-from codeverse.config import get_settings
+from codeverse.config import fewer_turns_enabled, get_settings
from codeverse.contracts.chat import ImagePart, ToolSpec
+from codeverse.languages.file_lint import lint_one_file
from codeverse.workspace import Workspace
READ_CAP_CHARS = 60_000
@@ -100,8 +101,12 @@ class FileTools:
allow_shell: bool = True,
edit_only: Collection[str] | None = None,
always_writable: Collection[str] = (),
+ language: str = "",
):
self.ws = ws
+ #: the authoring language, so write_file / edit_file can lint the ONE file they touched
+ #: (fewer_turns; "" = no per-file verdict)
+ self.language = language
self.write_roots = [(ws.root / r).resolve() for r in write_roots]
#: when set, an EXISTING file outside this set may not be overwritten. New files are
#: fine (a task may add a part) and ``always_writable`` (the entry file) is exempt.
@@ -124,6 +129,13 @@ class FileTools:
# ------------------------------------------------------------------ specs
def specs(self) -> list[ToolSpec]:
roots = ", ".join(os.path.relpath(r, self.ws.root) + "/" for r in self.write_roots)
+ # fewer_turns: the write result carries the verdict the agent used to fetch with a
+ # read_file round trip (docs/COST.md §26)
+ no_readback = (
+ " The result reports the line count and a syntax/lint verdict for that file: you do NOT "
+ "need to read a file back after writing it."
+ if fewer_turns_enabled() else ""
+ )
specs = [
ToolSpec(
name="read_file",
@@ -134,14 +146,14 @@ class FileTools:
),
ToolSpec(
name="write_file",
- description=f"Create or overwrite a text file. Only allowed under: {roots}. Parent dirs are created.",
+ description=f"Create or overwrite a text file. Only allowed under: {roots}. Parent dirs are created.{no_readback}",
parameters=_schema(
{"path": {"type": "string"}, "content": {"type": "string"}}, ["path", "content"]
),
),
ToolSpec(
name="edit_file",
- description=f"Exact-string replacement in an existing file (under {roots}). `old` must occur exactly once unless all=true.",
+ description=f"Exact-string replacement in an existing file (under {roots}). `old` must occur exactly once unless all=true.{no_readback}",
parameters=_schema(
{
"path": {"type": "string"},
@@ -268,10 +280,23 @@ class FileTools:
p.write_text(content)
rel = os.path.relpath(p, self.ws.root)
self.writes.append(rel)
+ verb = "overwrote" if existed else "created"
+ if fewer_turns_enabled():
+ return self._written(f"{verb} {rel}", rel, content, p)
return ToolOutcome(
- f"{'overwrote' if existed else 'created'} {rel} ({len(content)} chars, {content.count(chr(10)) + 1} lines)"
+ f"{verb} {rel} ({len(content)} chars, {content.count(chr(10)) + 1} lines)"
)
+ def _written(self, head: str, rel: str, content: str, p: Path) -> ToolOutcome:
+ """`<head> (N lines) · syntax OK` / `<head> (N lines)\n2 lint error(s) — …` — the
+ verdict that replaces the read-back (never the content itself)."""
+ n_lines = content.count("\n") + (0 if content.endswith("\n") or not content else 1)
+ text = f"{head} ({n_lines} lines)"
+ verdict = lint_one_file(self.language, rel.replace(os.sep, "/"), content, p).summary()
+ if verdict:
+ text += (" · " if verdict == "syntax OK" else "\n") + verdict
+ return ToolOutcome(text)
+
def edit_file(self, path: str, old: str, new: str, all: bool = False) -> ToolOutcome: # noqa: A002 - API name
p = self._resolve(path, write=True)
if not p.is_file():
@@ -298,10 +323,14 @@ class FileTools:
f"`old` occurs {n} times in {path}; include more context or pass all=true",
is_error=True,
)
- p.write_text(text.replace(old, new) if all else text.replace(old, new, 1))
+ new_text = text.replace(old, new) if all else text.replace(old, new, 1)
+ p.write_text(new_text)
rel = os.path.relpath(p, self.ws.root)
self.writes.append(rel)
- return ToolOutcome(f"edited {rel}: replaced {n if all else 1} occurrence(s)")
+ head = f"edited {rel}: replaced {n if all else 1} occurrence(s)"
+ if fewer_turns_enabled():
+ return self._written(head, rel, new_text, p)
+ return ToolOutcome(head)
def list_files(self, glob: str = "src/**/*") -> ToolOutcome:
root = self.ws.root
@@ -434,7 +463,7 @@ class SpatialTools:
def specs(self) -> list[ToolSpec]:
return [
- ToolSpec(name=t.name, description=t.description, parameters=t.schema())
+ ToolSpec(name=t.name, description=t.describe(), parameters=t.schema())
for t in self.tools.values()
]
diff --git a/harness/codeverse/config.py b/harness/codeverse/config.py
index fb8bf6a4..1aeb2983 100644
--- a/harness/codeverse/config.py
+++ b/harness/codeverse/config.py
@@ -10,6 +10,7 @@ Gemini keys: ``GEMINI_API_KEYS`` (csv) or ``GEMINI_API_KEY`` or the owner's
from __future__ import annotations
+import logging
import os
import re
import shutil
@@ -88,6 +89,14 @@ class Limits(BaseModel):
"which is what ships: a 28-turn cap cost $0.02 more and 0.205 of a score point in its "
"own A/B — docs/COST.md §17 — so no profile sets one; name it here if you want one).",
)
+ fewer_turns: bool = Field(
+ default=False,
+ description="fold the cheap gates into `build`, report a per-file lint verdict from "
+ "write_file / edit_file, inline the files a refine task edits, and ask the baseline "
+ "session for every file in its first turn (docs/COST.md §26). OFF until the A/B "
+ "reads out; `CV3D_FEWER_TURNS=1` (read at call time by `fewer_turns_enabled`) is "
+ "what `bench/ab_plan.py --variant-env` flips.",
+ )
class Rate(BaseModel):
@@ -134,6 +143,38 @@ class Judge(BaseModel):
samples: int = Field(default=1, description="default VLM samples per verdict")
+#: The fewer-turns switch (docs/COST.md §26). Read at CALL time by
+#: :func:`fewer_turns_enabled`, never only through the cached Settings: ``bench/ab_plan.py``
+#: differs its arms by environment alone, and a value frozen at first ``get_settings()``
+#: would hand the variant the control's behaviour (the CQ-5 lesson, tracks/plan_features.py).
+FEWER_TURNS_ENV = "CV3D_FEWER_TURNS"
+_TRUE_WORDS = frozenset({"1", "on", "true", "yes", "y"})
+_FALSE_WORDS = frozenset({"0", "off", "false", "no", "n"})
+
+
+def _env_flag(raw: str, env: str) -> bool:
+ word = raw.strip().lower()
+ if word in _TRUE_WORDS:
+ return True
+ if word in _FALSE_WORDS:
+ return False
+ raise ValueError(f"{env}={raw!r}: expected on/off (1/0, true/false, yes/no)")
+
+
+def fewer_turns_enabled() -> bool:
+ """Is the fewer-turns bundle on for THIS call? ``$CV3D_FEWER_TURNS`` when it is set
+ (garbage counts as off, with a warning — a typo in a bench command must produce a
+ control run, not a crash mid-battery), else ``Settings.limits.fewer_turns``."""
+ raw = os.environ.get(FEWER_TURNS_ENV)
+ if raw is not None and raw.strip():
+ try:
+ return _env_flag(raw, FEWER_TURNS_ENV)
+ except ValueError as e:
+ logging.getLogger(__name__).warning("%s; treating it as off", e)
+ return False
+ return get_settings().limits.fewer_turns
+
+
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="CV3D_", env_nested_delimiter="__", extra="ignore")
@@ -144,6 +185,7 @@ class Settings(BaseSettings):
#: knob; both spellings now work and the doctor prints the short one.
_FLAT_ALIASES: ClassVar[dict[str, tuple[str, str]]] = {
"CV3D_MAX_IN_FLIGHT": ("rate", "max_in_flight"),
+ FEWER_TURNS_ENV: ("limits", "fewer_turns"),
}
@model_validator(mode="after")
@@ -152,17 +194,21 @@ class Settings(BaseSettings):
raw = os.environ.get(env)
if raw is None or raw.strip() == "":
continue
- try:
- value = int(raw)
- except ValueError as e:
- raise ValueError(f"{env}={raw!r}: expected an integer") from e
- # plain assignment does NOT re-validate (no validate_assignment), so the target
- # field's own bound is enforced here — and the message names the variable the
- # operator actually typed, not the nested field they never heard of.
sub = getattr(self, section)
- lo = _lower_bound(type(sub), field)
- if lo is not None and value < lo:
- raise ValueError(f"{env}={raw!r}: must be >= {lo}")
+ value: int | bool
+ if type(sub).model_fields[field].annotation is bool:
+ value = _env_flag(raw, env)
+ else:
+ try:
+ value = int(raw)
+ except ValueError as e:
+ raise ValueError(f"{env}={raw!r}: expected an integer") from e
+ # plain assignment does NOT re-validate (no validate_assignment), so the target
+ # field's own bound is enforced here — and the message names the variable the
+ # operator actually typed, not the nested field they never heard of.
+ lo = _lower_bound(type(sub), field)
+ if lo is not None and value < lo:
+ raise ValueError(f"{env}={raw!r}: must be >= {lo}")
setattr(sub, field, value)
return self
diff --git a/harness/codeverse/languages/file_lint.py b/harness/codeverse/languages/file_lint.py
new file mode 100644
index 00000000..093c1bd0
--- /dev/null
+++ b/harness/codeverse/languages/file_lint.py
@@ -0,0 +1,138 @@
+"""One file, one cheap verdict — what ``write_file`` / ``edit_file`` hand back so the agent
+never has to ``read_file`` its own output (docs/COST.md §26: ~35 read_file turns per run,
+each a 4 s round trip carrying the whole context, to look at a file it wrote a turn ago).
+
+This is deliberately the language's OWN per-file lint, not a new rule set: the same
+``lint_*_source`` the workspace lint calls per file (blender / cadquery / opengl_python /
+urdf), ``node --check`` for JS (threejs / scene_threejs) and the static shader rules for
+GLSL. Only ERRORs are reported — a WARN is what ``build`` shows. A file type the
+language has no cheap check for gets ``checked=False`` and the tool says nothing about
+syntax rather than pretending. Never raises: a lint crash is reported as unchecked.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from codeverse.contracts.artifacts import GateFinding, Severity
+from codeverse.contracts.common import Language
+
+log = logging.getLogger(__name__)
+
+MAX_ERRORS = 3
+
+
+@dataclass(frozen=True)
+class FileVerdict:
+ checked: bool
+ errors: list[str] = field(default_factory=list) # "line 7: SyntaxError: ..." (≤ MAX_ERRORS)
+ n_total: int = 0
+
+ def summary(self) -> str:
+ """`syntax OK` / `2 lint error(s): ...` / "" when nothing was checked."""
+ if not self.checked:
+ return ""
+ if not self.errors:
+ return "syntax OK"
+ head = f"{self.n_total} lint error(s) — fix before build:"
+ return head + "".join(f"\n - {e}" for e in self.errors)
+
+
+def _line_of(f: GateFinding) -> int | None:
+ n = f.data.get("line") if isinstance(f.data, dict) else None
+ return int(n) if isinstance(n, int) and n > 0 else None
+
+
+def _errors(findings: list[GateFinding], max_errors: int) -> FileVerdict:
+ errs = [f for f in findings if f.severity == Severity.ERROR]
+ out = []
+ for f in errs[:max_errors]:
+ line = _line_of(f)
+ msg = f.message
+ out.append((f"line {line}: " if line else "") + msg + (f" (fix: {f.fix_hint})" if f.fix_hint else ""))
+ return FileVerdict(checked=True, errors=out, n_total=len(errs))
+
+
+def _python(language: Language, rel: str, text: str, max_errors: int) -> FileVerdict:
+ name = Path(rel).name
+ if language is Language.BLENDER:
+ from codeverse.languages.blender.lint import lint_blender_source
+
+ # same per-file settings as blender.layout.lint_workspace: helpers (_x.py) need no bpy;
+ # PascalCase-name checks are WARNs anyway and never reported here
+ rep = lint_blender_source(text, target=rel, expect_names=False, expect_bpy=not name.startswith("_"))
+ return _errors(rep.findings, max_errors)
+ if language is Language.CADQUERY:
+ from codeverse.languages.cadquery.lint import lint_cadquery_source
+
+ return _errors(lint_cadquery_source(text, target=rel).findings, max_errors)
+ if language is Language.OPENGL_PYTHON:
+ from codeverse.languages.opengl_python.lint import lint_source
+
+ return _errors(lint_source(text), max_errors)
+ if language is Language.URDF_BLENDER:
+ from codeverse.languages.urdf.lint import lint_model_text
+
+ # link names are the urdf's business; here only syntax + forbidden APIs + `import bpy`
+ return _errors(lint_model_text(text, [], label=rel), max_errors)
+ return FileVerdict(checked=False)
+
+
+def _js(path: Path, max_errors: int) -> FileVerdict:
+ from codeverse.config import get_settings
+ from codeverse.languages._js_lint import node_check_syntax
+
+ problem = node_check_syntax(path, get_settings().binaries.node or "node")
+ if problem is None:
+ return FileVerdict(checked=True)
+ if problem.line is None and "could not run" in problem.message:
+ return FileVerdict(checked=False)
+ return FileVerdict(checked=True, n_total=1,
+ errors=[(f"line {problem.line}: " if problem.line else "") + problem.message][:max_errors])
+
+
+def _glsl(rel: str, text: str, max_errors: int) -> FileVerdict:
+ from codeverse.languages.glsl_shader import lint as gl
+
+ role = {gl.SHADER: "shader", gl.COMMON: "common", gl.BUFFER_A: "buffer_a"}.get(rel, "shader")
+ return _errors(gl._check_file(rel, text, role=role), max_errors)
+
+
+def _urdf(rel: str, text: str, max_errors: int) -> FileVerdict:
+ from codeverse.languages.urdf.lint import lint_urdf_text
+
+ findings, _links = lint_urdf_text(text, label=rel)
+ return _errors(findings, max_errors)
+
+
+def lint_one_file(language: str, rel: str, text: str, path: Path, *, max_errors: int = MAX_ERRORS) -> FileVerdict:
+ """Verdict for ONE just-written source file (``rel`` workspace-relative, ``path`` on disk).
+
+ Cheap by construction: an ``ast.parse`` + visitor for python, one ``node --check``
+ for JS, regexes for GLSL / URDF. Files outside ``src/`` and types the language has no
+ per-file check for come back ``checked=False``.
+ """
+ try:
+ lang = Language(language)
+ except ValueError:
+ return FileVerdict(checked=False)
+ if not rel.startswith("src/"):
+ return FileVerdict(checked=False)
+ suffix = Path(rel).suffix
+ try:
+ if suffix == ".py":
+ return _python(lang, rel, text, max_errors)
+ if suffix in (".js", ".mjs") and lang in (Language.THREEJS, Language.SCENE_THREEJS):
+ return _js(path, max_errors)
+ if suffix in (".frag", ".glsl") and lang is Language.GLSL_SHADER:
+ return _glsl(rel, text, max_errors)
+ if suffix == ".urdf" and lang is Language.URDF_BLENDER:
+ return _urdf(rel, text, max_errors)
+ except Exception as e: # noqa: BLE001 — a lint crash is not the agent's problem
+ log.warning("per-file lint of %s failed: %s: %s", rel, type(e).__name__, e)
+ return FileVerdict(checked=False)
+
+
+__all__ = ["MAX_ERRORS", "FileVerdict", "lint_one_file"]
diff --git a/harness/codeverse/spatial/mcp_server.py b/harness/codeverse/spatial/mcp_server.py
index e94339ec..059961d5 100644
--- a/harness/codeverse/spatial/mcp_server.py
+++ b/harness/codeverse/spatial/mcp_server.py
@@ -85,7 +85,7 @@ def make_server(ctx: ToolContext):
defs = {t.name: t for t in mcp_tools(ctx)}
async def on_list_tools(_req_ctx: Any, _params: Any) -> types.ListToolsResult:
- tools = [types.Tool(name=t.name, description=f"({t.cost_hint}) {t.description}", input_schema=t.schema())
+ tools = [types.Tool(name=t.name, description=f"({t.cost_hint}) {t.describe()}", input_schema=t.schema())
for t in defs.values()]
return types.ListToolsResult(tools=tools)
@@ -123,7 +123,7 @@ def main(argv: list[str] | None = None) -> int:
return 2
ctx = build_context(ws, track=ns.track, language=ns.language, round_index=ns.round_index)
if ns.list:
- print(json.dumps([{"name": t.name, "description": t.description, "schema": t.schema()} for t in mcp_tools(ctx)], indent=1))
+ print(json.dumps([{"name": t.name, "description": t.describe(), "schema": t.schema()} for t in mcp_tools(ctx)], indent=1))
return 0
asyncio.run(serve_stdio(ctx))
return 0
diff --git a/harness/codeverse/spatial/registry.py b/harness/codeverse/spatial/registry.py
index be084d53..07cc5d0b 100644
--- a/harness/codeverse/spatial/registry.py
+++ b/harness/codeverse/spatial/registry.py
@@ -87,6 +87,15 @@ class ToolDef:
tracks: tuple[str, ...] = () # empty = all
languages: tuple[str, ...] = () # empty = all
cost_hint: str = "fast" # fast | slow
+ #: optional call-time suffix for the description (a switch-dependent sentence, e.g.
+ #: "includes CONNECTIVITY / CONTRACT" when CV3D_FEWER_TURNS is on). Returns "" for none.
+ describe_extra: Callable[[], str] | None = None
+
+ def describe(self) -> str:
+ """The description the agent sees NOW: the static text plus the switch-dependent
+ suffix, so a tool card / native tool spec tracks the tool's real behaviour."""
+ extra = self.describe_extra() if self.describe_extra is not None else ""
+ return f"{self.description} {extra.strip()}" if extra and extra.strip() else self.description
def schema(self) -> dict[str, Any]:
"""JSON schema of the arguments object (for native tool calling / MCP)."""
@@ -98,7 +107,7 @@ class ToolDef:
"""Prompt card: name, one-line purpose, args with descriptions."""
props = self.schema().get("properties", {})
req = set(self.schema().get("required", []))
- lines = [f"- `{self.name}` ({self.cost_hint}): {self.description}"]
+ lines = [f"- `{self.name}` ({self.cost_hint}): {self.describe()}"]
for k, v in props.items():
typ = v.get("type", "any")
d = v.get("description", "")
@@ -137,6 +146,7 @@ def tool(
tracks: tuple[str, ...] = (),
languages: tuple[str, ...] = (),
cost_hint: str = "fast",
+ describe_extra: Callable[[], str] | None = None,
) -> Callable[[Callable[[ToolContext, Any], Observation]], Callable[[ToolContext, Any], Observation]]:
def deco(fn: Callable[[ToolContext, Any], Observation]) -> Callable[[ToolContext, Any], Observation]:
sig = inspect.signature(fn)
@@ -144,7 +154,8 @@ def tool(
raise TypeError(f"tool {name}: fn must be fn(ctx, args)")
if name in _REGISTRY:
raise ValueError(f"tool {name} registered twice")
- _REGISTRY[name] = ToolDef(name, args_model, description, fn, tracks, languages, cost_hint)
+ _REGISTRY[name] = ToolDef(name, args_model, description, fn, tracks, languages, cost_hint,
+ describe_extra)
return fn
return deco
diff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.py
index a34cc329..a39ad102 100644
--- a/harness/codeverse/spatial/tools.py
+++ b/harness/codeverse/spatial/tools.py
@@ -11,11 +11,12 @@ and every tool is cheap to call repeatedly.
from __future__ import annotations
+from pathlib import Path
from typing import Any
from pydantic import BaseModel, Field
-from codeverse.config import get_settings
+from codeverse.config import fewer_turns_enabled, get_settings
from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement
from codeverse.spatial.connectivity import check_connectivity as _check_connectivity
from codeverse.spatial.contract import check_contract as _check_contract
@@ -28,6 +29,7 @@ from codeverse.spatial.observe import (
rel_path,
sanitize_text,
text_observation,
+ truncate,
)
from codeverse.spatial.registry import NoArgs, Observation, ToolContext, ToolUsageError, tool
from codeverse.spatial.sections import cross_section as _cross_section
@@ -83,7 +85,51 @@ def _no_glb_summary(ctx: ToolContext, br: BuildResult, language: str) -> tuple[b
return True, lines, {"census": keep}
-@tool("build", NoArgs, "Lint + build the code in src/ with the language runtime, export artifacts/object.glb and measure it. Call after every edit.", cost_hint="slow")
+#: what `build` says about itself when the gates ride along (docs/COST.md §26): the agent
+#: must not spend two more round trips asking for what the build observation already holds.
+_BUILD_INCLUDES_CHECKS = ("On success it ALSO runs check_connectivity and check_contract and reports them "
+ "under CONNECTIVITY / CONTRACT — do not call those two tools separately.")
+_FOLDED_MAX_FINDINGS = 6
+_FOLDED_SECTION_CHARS = 900 # per section, errors first — two sections + the table fit the build limit
+
+
+def _folded_checks(ctx: ToolContext, glb: Path, m: Measurement, language: str) -> tuple[list[str], dict[str, Any]]:
+ """The connectivity + contract gates as they would appear from their own tools, folded
+ into the build observation: (lines, numbers). Each gate is a few hundred ms on a
+ built GLB; each as a separate tool call was a 4 s round trip carrying the whole
+ context (docs/COST.md §26). Same checkers, same gate JSON files, same formatter."""
+ ws = ctx.workspace
+ lines: list[str] = []
+ numbers: dict[str, Any] = {}
+ verdicts: list[str] = []
+
+ def fold(name: str, report: GateReport) -> None:
+ ws.write_json(ws.gates_dir(ctx.round_index) / f"{name.lower()}_tool.json", report)
+ obs = gate_observation(report, title=f"{name}: {'PASS' if report.passed else 'FAIL'}",
+ max_findings=_FOLDED_MAX_FINDINGS)
+ n_err = int(obs.numbers["errors"])
+ lines.append(truncate(obs.text, _FOLDED_SECTION_CHARS))
+ numbers[f"{name.lower()}_errors"] = n_err
+ verdicts.append(f"{name.lower()} " + ("PASS" if report.passed else f"FAIL ({n_err} error(s))"))
+
+ conn = _check_connectivity(glb, language=language)
+ fold("CONNECTIVITY", conn)
+ if ws.plan_path.is_file():
+ contract = _check_contract(m, load_plan(ws.plan_path), language=language)
+ fold("CONTRACT", contract)
+ passed = conn.passed and contract.passed
+ else:
+ lines.append("CONTRACT: skipped — no plan.json in the workspace")
+ passed = conn.passed
+ numbers["checks_passed"] = passed
+ tail = ("no separate check_connectivity / check_contract call is needed" if passed
+ else "fix the ERRORs listed under CONNECTIVITY / CONTRACT below, then build again")
+ summary = "CHECKS: " + " · ".join(verdicts) + " — " + tail
+ return [summary, *lines], numbers
+
+
+@tool("build", NoArgs, "Lint + build the code in src/ with the language runtime, export artifacts/object.glb and measure it. Call after every edit.", cost_hint="slow",
+ describe_extra=lambda: _BUILD_INCLUDES_CHECKS if fewer_turns_enabled() else "")
def build(ctx: ToolContext, args: NoArgs) -> Observation:
# ToolDef.call stamps Observation.duration_ms for every tool — no timing here
ws = ctx.workspace
@@ -128,6 +174,15 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
census_warn = br.census.get("warnings") if isinstance(br.census, dict) else None
if census_warn:
lines.append("build warnings:\n" + "\n".join(f"- {sanitize_text(str(w), ws.root)}" for w in list(census_warn)[:10]))
+ if m is not None and fewer_turns_enabled():
+ try:
+ folded, folded_numbers = _folded_checks(ctx, Path(br.glb_path), m, language)
+ except (ToolUsageError, ValueError, OSError) as e: # a broken plan.json must not hide a good build
+ folded, folded_numbers = [f"CHECKS: skipped ({type(e).__name__}: {e})"], {}
+ # errors first (house rule): the verdict and both sections right under BUILD OK, so
+ # the head/tail truncation eats the middle of the measurement table, never a gate error
+ lines[1:1] = folded
+ numbers.update(folded_numbers)
return text_observation(lines, ok=ok, numbers=numbers, limit=3000)
diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.py
index 8e4eca91..8980c23a 100644
--- a/harness/codeverse/tracks/plan_features.py
+++ b/harness/codeverse/tracks/plan_features.py
@@ -53,7 +53,8 @@ GENERATION_SIDE: frozenset[str] = frozenset({CONTACTS})
PLAN_SIDE_ENV: frozenset[str] = frozenset({"CV3D_PLAN_BRIEF", "CV3D_SCOPED_PARTS"})
GENERATION_SIDE_ENV: frozenset[str] = frozenset({"CV3D_SKILLS", "CV3D_SKILLS_MAX", "CV3D_SKILLS_UNVERIFIED",
"CV3D_SKILLS_ONLY",
- "CV3D_DETAIL_ROUNDS", "CV3D_REFERENCE_DIFF"})
+ "CV3D_DETAIL_ROUNDS", "CV3D_REFERENCE_DIFF",
+ "CV3D_FEWER_TURNS"})
def pin_plan_blockers(variant_env: dict[str, str]) -> list[str]:
@@ -89,6 +90,10 @@ LIVE_SWITCHES: dict[str, str] = {
"CV3D_SKILLS_MAX": "codeverse/skills/config.py",
"CV3D_SKILLS_UNVERIFIED": "codeverse/skills/config.py",
"CV3D_SKILLS_ONLY": "codeverse/skills/config.py",
+ # fewer turns (docs/COST.md §26): build folds the gates in, write_file lints, the refine
+ # prompt inlines its files, the baseline prompt asks for every file in turn 1. One
+ # switch, read at call time by config.fewer_turns_enabled; acts after planning.
+ "CV3D_FEWER_TURNS": "codeverse/config.py",
}
#: Switches that are DECLARED but read by no code path, with the reason. An A/B arm that
diff --git a/harness/tests/agents/test_api_tools.py b/harness/tests/agents/test_api_tools.py
index db782706..96b935ff 100644
--- a/harness/tests/agents/test_api_tools.py
+++ b/harness/tests/agents/test_api_tools.py
@@ -126,3 +126,43 @@ def test_unknown_tool_and_bad_args(tmp_ws: Workspace):
t = _tools(tmp_ws)
assert t.call("nope", {}).is_error
assert t.call("read_file", {"wrong": 1}).is_error
+
+
+# --------------------------------------------------------------------------- fewer_turns: the write result replaces the read-back
+GOOD_BPY = "import bpy\n\n\ndef build_seat():\n bpy.ops.mesh.primitive_cube_add(size=0.4)\n o = bpy.context.object\n o.name = 'Seat'\n return o\n"
+BROKEN_BPY = "import bpy\n\ndef build_seat(:\n return None\n"
+
+
+def test_write_file_reports_a_syntax_verdict_when_fewer_turns(tmp_ws: Workspace, monkeypatch):
+ """~35 read_file turns per run re-read a file the agent wrote a turn earlier (docs/COST.md
+ §26). On: the write says `(N lines) · syntax OK` or the first errors with line numbers —
+ never the content."""
+ monkeypatch.setenv("CV3D_FEWER_TURNS", "1")
+ t = FileTools(tmp_ws, ["src", "public"], language="blender")
+ out = t.call("write_file", {"path": "src/parts/seat.py", "content": GOOD_BPY})
+ assert not out.is_error and out.text == "created src/parts/seat.py (8 lines) · syntax OK"
+ assert "primitive_cube_add" not in out.text
+ bad = t.call("write_file", {"path": "src/parts/seat.py", "content": BROKEN_BPY})
+ assert not bad.is_error # the file WAS written; the verdict is in the text
+ assert bad.text.startswith("overwrote src/parts/seat.py (4 lines)\n1 lint error(s)")
+ assert "line 3: SyntaxError" in bad.text and "fix:" in bad.text
+ e = t.call("edit_file", {"path": "src/parts/seat.py", "old": "build_seat(:", "new": "build_seat():"})
+ assert e.text == "edited src/parts/seat.py: replaced 1 occurrence(s) (4 lines) · syntax OK"
+ # a file type the language has no cheap check for gets the count and no verdict
+ txt = t.call("write_file", {"path": "src/notes.txt", "content": "a\nb\n"})
+ assert txt.text == "created src/notes.txt (2 lines)"
+ # the tool cards say so
+ descs = {s.name: s.description for s in t.specs()}
+ assert "do NOT need to read a file back" in descs["write_file"] and "do NOT need to read a file back" in descs["edit_file"]
+ assert "read a file back" not in descs["read_file"]
+
+
+def test_write_file_is_byte_identical_when_fewer_turns_is_off(tmp_ws: Workspace, monkeypatch):
+ monkeypatch.delenv("CV3D_FEWER_TURNS", raising=False)
+ t = FileTools(tmp_ws, ["src", "public"], language="blender")
+ out = t.call("write_file", {"path": "src/parts/seat.py", "content": BROKEN_BPY})
+ assert out.text == f"created src/parts/seat.py ({len(BROKEN_BPY)} chars, 5 lines)"
+ assert "syntax" not in out.text and "lint" not in out.text
+ e = t.call("edit_file", {"path": "src/parts/seat.py", "old": "(:", "new": "():"})
+ assert e.text == "edited src/parts/seat.py: replaced 1 occurrence(s)"
+ assert all("read a file back" not in s.description for s in t.specs())
diff --git a/harness/tests/languages/test_file_lint.py b/harness/tests/languages/test_file_lint.py
new file mode 100644
index 00000000..94bfcb8d
--- /dev/null
+++ b/harness/tests/languages/test_file_lint.py
@@ -0,0 +1,68 @@
+"""``languages/file_lint.py``: one file → one cheap verdict, per language, never raising."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from codeverse.languages.file_lint import FileVerdict, lint_one_file
+
+
+def _v(language: str, rel: str, text: str, tmp_path: Path, **kw) -> FileVerdict:
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(text)
+ return lint_one_file(language, rel, text, p, **kw)
+
+
+def test_blender_good_and_broken(tmp_path):
+ ok = _v("blender", "src/parts/seat.py", "import bpy\n\n\ndef build_seat():\n return bpy.context.object\n", tmp_path)
+ assert ok.checked and not ok.errors and ok.summary() == "syntax OK"
+ bad = _v("blender", "src/model.py", "import bpy\nx = (\n", tmp_path)
+ assert bad.checked and bad.n_total == 1 and bad.errors[0].startswith("line ") and "SyntaxError" in bad.errors[0]
+ assert bad.summary().startswith("1 lint error(s)")
+ # a helper module needs no `import bpy`; a part file does
+ assert not _v("blender", "src/parts/_helpers.py", "def f():\n return 1\n", tmp_path).errors
+ nobpy = _v("blender", "src/parts/leg.py", "def build_leg():\n return None\n", tmp_path)
+ assert nobpy.errors and "never imports bpy" in nobpy.errors[0]
+
+
+def test_first_three_errors_only(tmp_path):
+ src = "import bpy\nimport subprocess\nimport socket\nimport pathlib\nimport urllib\nimport requests\n"
+ v = _v("blender", "src/model.py", src, tmp_path)
+ assert v.n_total >= 4 and len(v.errors) == 3
+ assert v.summary().startswith(f"{v.n_total} lint error(s)") and v.summary().count("\n - ") == 3
+
+
+def test_cadquery_opengl_urdf(tmp_path):
+ assert "SyntaxError" in _v("cadquery", "src/model.py", "import cadquery as cq\nresult = cq.Workplane(\n", tmp_path).errors[0]
+ gl = _v("opengl_python", "src/program.py", "def setup(ctx, width, height):\n return {}\n", tmp_path)
+ assert gl.checked and any("render" in e for e in gl.errors) # missing render()
+ urdf = _v("urdf_blender", "src/robot.urdf", "<robot name='r'><link name='base'/><joint", tmp_path)
+ assert urdf.checked and urdf.errors
+ model = _v("urdf_blender", "src/model.py", "import bpy\nx = 1\n", tmp_path)
+ assert model.checked and not model.errors
+
+
+def test_glsl_static_rules(tmp_path):
+ good = "void mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(1.0); }\n"
+ assert _v("glsl_shader", "src/shader.frag", good, tmp_path).summary() == "syntax OK"
+ bad = _v("glsl_shader", "src/shader.frag", "#version 330 core\n" + good, tmp_path)
+ assert bad.errors and "line 1" in bad.errors[0] and "#version" in bad.errors[0]
+
+
+def test_threejs_node_check(tmp_path):
+ ok = _v("threejs", "src/parts/seat.js", "export function buildSeat(THREE) { return new THREE.Group(); }\n", tmp_path)
+ assert ok.checked and not ok.errors
+ bad = _v("threejs", "src/parts/seat.js", "export function buildSeat(THREE) {\n return new THREE.Group(;\n}\n", tmp_path)
+ assert bad.checked and bad.errors and "line 2" in bad.errors[0]
+
+
+def test_unchecked_cases(tmp_path):
+ assert not _v("blender", "public/x.py", "x = (\n", tmp_path).checked # outside src/
+ assert not _v("blender", "src/notes.md", "# hi", tmp_path).checked # no per-file check
+ assert not _v("opengl_python", "src/pass.glsl", "#version 330", tmp_path).checked # no cheap GLSL compile
+ assert not _v("not-a-language", "src/model.py", "x = (", tmp_path).checked
+ assert FileVerdict(checked=False).summary() == ""
diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.py
index 70c3f345..869e3976 100644
--- a/harness/tests/spatial_tools/test_tools.py
+++ b/harness/tests/spatial_tools/test_tools.py
@@ -369,3 +369,63 @@ def test_load_plan_recognises_graphics_plan(tmp_ws: Workspace) -> None:
tmp_ws.write_json(tmp_ws.plan_path, plan)
loaded = load_plan(tmp_ws.plan_path)
assert isinstance(loaded, GraphicsPlan) and loaded.title == "Neon rain"
+
+
+# --------------------------------------------------------------------------- fewer_turns: build folds the gates in
+def _stool_plan_with_missing_backrest() -> StaticPlan:
+ return StaticPlan(object_name="Stool", summary="s", overall_bbox=BBox(center=(0, 0, 0.225), extents=(0.4, 0.4, 0.45)),
+ parts=[PartPlan(name="Seat", role="r", description="d", bbox=BBox(center=(0, 0, 0.43), extents=(0.4, 0.4, 0.04))),
+ PartPlan(name="Leg", role="r", description="d", bbox=BBox(center=(0, 0, 0.205), extents=(0.04, 0.04, 0.41)), instances=4),
+ PartPlan(name="Backrest", role="r", description="d", bbox=BBox(center=(0, 0.18, 0.6), extents=(0.4, 0.03, 0.3)))])
+
+
+def test_build_folds_connectivity_and_contract_in_when_fewer_turns(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ """docs/COST.md §26: ~25 check_connectivity + ~19 check_contract calls per run, each a 4 s
+ round trip for a < 0.5 s check. With the switch on, one build observation carries both."""
+ monkeypatch.setenv("CV3D_FEWER_TURNS", "1")
+ ws = stool_ctx.workspace
+ ws.write_json(ws.plan_path, _stool_plan_with_missing_backrest())
+ _patch_runtime(monkeypatch, _FakeRuntime(glb=ws.artifacts / "object.glb"))
+ obs = get_tool("build").call(stool_ctx, {})
+ assert obs.ok and obs.text.startswith("BUILD OK") # the build itself succeeded
+ head, verdict = obs.text.splitlines()[:2]
+ assert verdict.startswith("CHECKS: connectivity FAIL") and "contract FAIL" in verdict and "build again" in verdict
+ assert "CONNECTIVITY: FAIL" in obs.text and "Leg_3" in obs.text # the floating leg, with its fix hint
+ assert "CONTRACT: FAIL" in obs.text and "Backrest" in obs.text and "missing" in obs.text
+ assert "fix:" in obs.text
+ assert obs.numbers["connectivity_errors"] >= 1 and obs.numbers["contract_errors"] >= 1
+ assert obs.numbers["checks_passed"] is False
+ assert len(obs.text) <= 3000 # the existing build limit holds
+ gates = ws.gates_dir(stool_ctx.round_index)
+ assert (gates / "connectivity_tool.json").is_file() and (gates / "contract_tool.json").is_file()
+ # the separate tools still exist for an agent that insists
+ assert {"check_connectivity", "check_contract"} <= {t.name for t in list_tools()}
+
+
+def test_build_folded_checks_pass_on_a_solid_stool(tmp_ws: Workspace, solid_stool_glb: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("CV3D_FEWER_TURNS", "on")
+ (tmp_ws.artifacts / "object.glb").write_bytes(solid_stool_glb.read_bytes())
+ tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "static_object", "language": "blender", "prompt": "a stool"}))
+ ctx = ToolContext(workspace=tmp_ws, language="blender", track="static_object")
+ _patch_runtime(monkeypatch, _FakeRuntime(glb=tmp_ws.artifacts / "object.glb"))
+ obs = get_tool("build").call(ctx, {})
+ verdict = obs.text.splitlines()[1]
+ assert verdict.startswith("CHECKS: connectivity PASS") and "no separate check_connectivity" in verdict
+ assert "CONTRACT: skipped — no plan.json" in obs.text # no plan → no contract, said so
+ assert obs.numbers["checks_passed"] is True and "contract_errors" not in obs.numbers
+
+
+def test_build_card_and_observation_are_unchanged_when_fewer_turns_is_off(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("CV3D_FEWER_TURNS", raising=False)
+ ws = stool_ctx.workspace
+ ws.write_json(ws.plan_path, _stool_plan_with_missing_backrest())
+ _patch_runtime(monkeypatch, _FakeRuntime(glb=ws.artifacts / "object.glb"))
+ obs = get_tool("build").call(stool_ctx, {})
+ assert "CONNECTIVITY" not in obs.text and "CONTRACT" not in obs.text and "CHECKS:" not in obs.text
+ assert "checks_passed" not in obs.numbers
+ card_off = get_tool("build").card()
+ assert "check_connectivity" not in card_off
+ monkeypatch.setenv("CV3D_FEWER_TURNS", "1")
+ card_on = get_tool("build").card()
+ assert "do not call those two tools separately" in card_on and card_on.startswith(card_off.splitlines()[0][:40])
+ assert get_tool("build").description == get_tool("build").description # the static text never changes