Skip to content

Official Codebase of 3DCodeVerse

Python

fewer_turns (2/3): refine sessions get the ≤ 3 files they edit inlined; baseline prompt asks for every file in turn one

gaoypeng8c578e15213b
diff --git a/harness/codeverse/prompts/tracks/assemble_static.j2 b/harness/codeverse/prompts/tracks/assemble_static.j2
index 749c5578..cca1a269 100644
--- a/harness/codeverse/prompts/tracks/assemble_static.j2
+++ b/harness/codeverse/prompts/tracks/assemble_static.j2
@@ -26,7 +26,7 @@ Overall bbox: {{ overall_bbox }}
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:
+4. {% if turn_discipline %}Read the CONNECTIVITY and CONTRACT sections of the `build` result (it runs both checks for you){% else %}Run `check_connectivity` and `check_contract`{% endif %}. Every ERROR must be gone before you finish:
- a **floating** part → move it (or its neighbour) so the surfaces overlap by 2–5 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
@@ -47,6 +47,10 @@ Overall bbox: {{ overall_bbox }}
## Tools
{{ tool_cards }}
{% endif %}
+{% if turn_discipline %}
+
+{{ turn_discipline }}
+{% endif %}
## Output
{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/generate_static.j2 b/harness/codeverse/prompts/tracks/generate_static.j2
index 733d4d6a..54d4c7d8 100644
--- a/harness/codeverse/prompts/tracks/generate_static.j2
+++ b/harness/codeverse/prompts/tracks/generate_static.j2
@@ -79,6 +79,10 @@ Construction notes per part:
## Tools available to you
{{ tool_cards }}
{% endif %}
+{% if turn_discipline %}
+
+{{ turn_discipline }}
+{% endif %}
## Output
{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/generate_static_part.j2 b/harness/codeverse/prompts/tracks/generate_static_part.j2
index 021d7c27..fba4ca40 100644
--- a/harness/codeverse/prompts/tracks/generate_static_part.j2
+++ b/harness/codeverse/prompts/tracks/generate_static_part.j2
@@ -61,6 +61,10 @@ Run `build` after writing your files and fix every error it reports before you f
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 %}
+{% if turn_discipline %}
+
+{{ turn_discipline }}
+{% endif %}
## Output
{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/refine_object.j2 b/harness/codeverse/prompts/tracks/refine_object.j2
index 8cd3dfe3..51ab1fff 100644
--- a/harness/codeverse/prompts/tracks/refine_object.j2
+++ b/harness/codeverse/prompts/tracks/refine_object.j2
@@ -48,7 +48,7 @@ Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}
- One code path: no environment sniffing, no DOM/texture loading/network.
{% if current_files %}
-## Current file contents (edit these; return each edited file COMPLETE)
+{% if single_shot %}## Current file contents (edit these; return each edited file COMPLETE){% else %}## Current file contents (already in the workspace — edit with `edit_file` / `write_file`; do NOT read_file them first){% endif %}
{% for path, body in current_files.items() %}
--- {{ path }} ---
```
@@ -62,6 +62,13 @@ Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}
{{ tool_cards }}
Run `build` after editing and fix any error before finishing.
{% endif %}
+{% if turn_discipline %}
+
+## Turn discipline (every tool call is a full round trip — spend as few as you can)
+- Make the edits first (the files above are current), then call `build` once; it already runs
+ check_connectivity and check_contract — read its CONNECTIVITY / CONTRACT sections instead of
+ calling those tools. Do not read a file back after writing or editing it.
+{% endif %}
## Output
{{ output_format }}
diff --git a/harness/codeverse/tracks/prompting.py b/harness/codeverse/tracks/prompting.py
index acb2edae..d7636240 100644
--- a/harness/codeverse/tracks/prompting.py
+++ b/harness/codeverse/tracks/prompting.py
@@ -13,6 +13,7 @@ from collections.abc import Sequence
from pathlib import Path
from typing import Any
+from codeverse.config import fewer_turns_enabled
from codeverse.contracts.chat import ImagePart
from codeverse.contracts.common import Language, Track
from codeverse.contracts.plan import Plan, StaticPlan
@@ -276,6 +277,9 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
"detail_budget": detail_budget_text(ctx),
"root_link": getattr(plan, "root_link", "") if plan else "",
"reference_note": reference_note(ctx),
+ # a string, "" when off: templates render it with one {% if %} and stay byte-identical
+ # for the control arm
+ "turn_discipline": TURN_DISCIPLINE if (fewer_turns_enabled() and not ctx.single_shot) else "",
}
d.update(extra)
return d
@@ -432,6 +436,28 @@ def skeleton_files(ctx: RunContext, max_chars: int = MAX_SKELETON_CHARS) -> dict
)
+def refine_inline_files(ctx: RunContext, rels: Sequence[str], *, scoped: bool) -> dict[str, str]:
+ """The files a refine task may edit, inlined for the prompt — or ``{}``.
+
+ Single-shot always gets them (it has no read tool). An agent session gets them only
+ under ``fewer_turns`` and only when the task is scoped to ≤ ``INLINE_MAX_FILES`` files
+ totalling ≤ ``INLINE_MAX_CHARS`` — measured: a refine session spends 5.2 of its 24
+ turns on read_file, mostly on the files the task just named. Larger sets are NOT
+ truncated into the prompt (a half file is worse than a read): they stay on disk.
+ """
+ if ctx.single_shot:
+ return current_files(ctx, rels)
+ if not (fewer_turns_enabled() and scoped) or not rels or len(rels) > INLINE_MAX_FILES:
+ return {}
+ paths = [ctx.ws.root / r for r in rels]
+ if not all(p.is_file() for p in paths):
+ return {}
+ if sum(p.stat().st_size for p in paths) > INLINE_MAX_CHARS:
+ return {}
+ files = current_files(ctx, rels, max_chars=INLINE_MAX_CHARS + 1)
+ return files if sum(len(t) for t in files.values()) <= INLINE_MAX_CHARS else {}
+
+
def current_files(
ctx: RunContext, rels: Sequence[str], max_chars: int = MAX_SKELETON_CHARS
) -> dict[str, str]:
@@ -503,6 +529,24 @@ def measurement_vs_plan(
return "\n".join(lines + gate_lines)
+#: fewer_turns (docs/COST.md §26): the baseline session hit the 60-turn cap in every measured
+#: run — 22.5 write_file + 8 build + 7.5 read_file + 4.6 check_connectivity + 4.1 check_contract
+#: per session, each a 4 s round trip re-sending a 35–70 k context. The cap itself is NOT the
+#: lever (§17: a 28-turn cap cost 0.205 of a score point); the block asks for fewer, fuller turns.
+TURN_DISCIPLINE = """## Turn discipline (every tool call is a full round trip — spend as few as you can)
+- FIRST reply: write EVERY file listed under "Files you must produce" as multiple `write_file`
+ calls in that same reply, then call `build` once. Do not write one file per turn.
+- `build` already runs check_connectivity and check_contract: read its CONNECTIVITY / CONTRACT
+ sections, fix what they list, build again. Do not call those two tools separately.
+- Do not read a file back after writing or editing it: the write result reports its line count and
+ syntax verdict.
+- Call `render_sheet` once before you finish; `measure` at most once."""
+
+#: the refine prompt inlines the files a scoped task edits when they are few and small, so the
+#: session's first turn is the edit, not a read_file (fewer_turns, docs/COST.md §26)
+INLINE_MAX_FILES = 3
+INLINE_MAX_CHARS = 12_000
+
AGENT_OUTPUT_RULES = """HOW TO FINISH (agent mode): edit files under src/ only (and public/ for compiled assets).
Before you finish you MUST run the `build` tool and fix every error it reports; then run `measure`
(objects) or `scene_probe` (scenes) once and compare the numbers with the plan. Do not write
diff --git a/harness/codeverse/tracks/static_object.py b/harness/codeverse/tracks/static_object.py
index 5b293342..0ccf7922 100644
--- a/harness/codeverse/tracks/static_object.py
+++ b/harness/codeverse/tracks/static_object.py
@@ -40,6 +40,7 @@ from codeverse.tracks.prompting import (
judged_sheet,
measurement_vs_plan,
reference_images,
+ refine_inline_files,
scope_context,
skeleton_files,
)
@@ -335,7 +336,9 @@ class StaticObjectTrack(BaseTrack):
edit_only_these=scoped,
judge_summary=judge_digest(last),
measurement_notes=measurement_vs_plan(last, ctx.plan, ctx.language),
- current_files=current_files(ctx, files) if ctx.single_shot else {},
+ # single-shot: always; agent session: under fewer_turns, when the scoped
+ # set is ≤ 3 files / ≤ 12 k chars — the first turn is then the edit
+ current_files=refine_inline_files(ctx, files, scoped=scoped),
),
)
ctx.record_prompt("refine", prompt)
diff --git a/harness/tests/orchestrator_tracks/test_fewer_turns.py b/harness/tests/orchestrator_tracks/test_fewer_turns.py
new file mode 100644
index 00000000..f75e8460
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_fewer_turns.py
@@ -0,0 +1,157 @@
+"""``CV3D_FEWER_TURNS`` (docs/COST.md §26): the refine prompt carries the files it names, the
+baseline prompt asks for every file in turn one, and the control arm is byte-identical."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.config import FEWER_TURNS_ENV, Settings, fewer_turns_enabled
+from codeverse.contracts.common import Language
+from codeverse.orchestrator.rounds import RefineTask, TaskGroup
+from codeverse.tracks.plan_features import LIVE_SWITCHES, pin_plan_blockers
+from codeverse.tracks.prompting import INLINE_MAX_CHARS, INLINE_MAX_FILES, TURN_DISCIPLINE
+
+from .conftest import make_spec
+from .fakes import FakeAgent, FakeRuntime, FakeServices
+from .test_generation_depth import _round
+
+SEAT = "import bpy\n\n\ndef build_seat():\n return bpy.context.object # SEAT-BODY\n"
+LEG = "import bpy\n\n\ndef build_leg():\n return bpy.context.object # LEG-BODY\n"
+
+
+def _ctx(tmp_path, plan, settings, *, language=Language.BLENDER, agent_id="fake-agent:m"):
+ from codeverse.events import EventLog
+ from codeverse.orchestrator.state import RunState
+ from codeverse.tracks.static_object import StaticObjectTrack
+ from codeverse.workspace import Workspace
+
+ ws = Workspace(tmp_path / "runs" / "d").create()
+ track = StaticObjectTrack(services=FakeServices(), agent=FakeAgent(lambda job: None), settings=settings,
+ runtime=FakeRuntime(language))
+ ctx = track.build_context(make_spec(language=language, generator=agent_id), ws, EventLog(ws.events_path), RunState(slug="d"))
+ ctx.plan = plan
+ return track, ctx
+
+
+def _group(files):
+ return TaskGroup(tasks=[RefineTask(target="Seat", kind="geometry", instruction="thicken the seat", priority=2, files=list(files))],
+ files=list(files))
+
+
+def _write(ws, files):
+ for rel, body in files.items():
+ p = ws.root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body)
+
+
+# --------------------------------------------------------------------------- the switch
+def test_switch_reads_env_at_call_time_and_is_off_by_default(monkeypatch):
+ monkeypatch.delenv(FEWER_TURNS_ENV, raising=False)
+ assert fewer_turns_enabled() is False
+ monkeypatch.setenv(FEWER_TURNS_ENV, "1")
+ assert fewer_turns_enabled() is True
+ monkeypatch.setenv(FEWER_TURNS_ENV, "off")
+ assert fewer_turns_enabled() is False
+ monkeypatch.setenv(FEWER_TURNS_ENV, "maybe") # garbage = control run, not a crash
+ assert fewer_turns_enabled() is False
+
+
+def test_switch_is_a_settings_field_with_a_flat_alias(monkeypatch):
+ monkeypatch.setenv(FEWER_TURNS_ENV, "on")
+ assert Settings().limits.fewer_turns is True
+ monkeypatch.delenv(FEWER_TURNS_ENV)
+ assert Settings().limits.fewer_turns is False
+ monkeypatch.setenv("CV3D_LIMITS__FEWER_TURNS", "true")
+ assert Settings().limits.fewer_turns is True
+
+
+def test_switch_is_live_and_generation_side():
+ assert LIVE_SWITCHES[FEWER_TURNS_ENV] == "codeverse/config.py"
+ assert pin_plan_blockers({FEWER_TURNS_ENV: "1"}) == [] # ab_plan --pin-plan may share one plan
+
+
+# --------------------------------------------------------------------------- refine: the files ride along
+def test_refine_prompt_inlines_a_small_scoped_file_set(tmp_path, chair_plan, settings, monkeypatch):
+ monkeypatch.setenv(FEWER_TURNS_ENV, "1")
+ track, ctx = _ctx(tmp_path, chair_plan, settings)
+ files = {"src/parts/seat.py": SEAT, "src/parts/leg.py": LEG}
+ _write(ctx.ws, files)
+ task = track._refine_task(ctx, _group(files), _round(1, 0.6), 2, parallel=False)
+ assert task.edit_only and task.files_hint == list(files)
+ assert "SEAT-BODY" in task.prompt and "LEG-BODY" in task.prompt
+ assert "--- src/parts/seat.py ---" in task.prompt and "--- src/parts/leg.py ---" in task.prompt
+ assert "do NOT read_file them first" in task.prompt and "return each edited file COMPLETE" not in task.prompt
+ assert "## Turn discipline" in task.prompt
+
+
+def test_refine_prompt_inlines_nothing_when_off_or_too_big(tmp_path, chair_plan, settings, monkeypatch):
+ monkeypatch.delenv(FEWER_TURNS_ENV, raising=False)
+ track, ctx = _ctx(tmp_path, chair_plan, settings)
+ files = {"src/parts/seat.py": SEAT, "src/parts/leg.py": LEG}
+ _write(ctx.ws, files)
+ off = track._refine_task(ctx, _group(files), _round(1, 0.6), 2, parallel=False).prompt
+ assert "SEAT-BODY" not in off and "Current file contents" not in off and "Turn discipline" not in off
+ monkeypatch.setenv(FEWER_TURNS_ENV, "1")
+ many = {f"src/parts/p{i}.py": SEAT for i in range(INLINE_MAX_FILES + 1)}
+ _write(ctx.ws, many)
+ assert "SEAT-BODY" not in track._refine_task(ctx, _group(many), _round(1, 0.6), 2, parallel=False).prompt
+ big = {"src/parts/big.py": "import bpy\n" + "# " + "x" * INLINE_MAX_CHARS + "\n"}
+ _write(ctx.ws, big)
+ p = track._refine_task(ctx, _group(big), _round(1, 0.6), 2, parallel=False).prompt
+ assert "Current file contents" not in p # not truncated INTO the prompt: left on disk
+ # an unscoped group (target "overall") keeps the whole tree and inlines nothing
+ whole = track._refine_task(ctx, TaskGroup(tasks=[RefineTask(target="overall", kind="geometry", instruction="x", priority=2)]),
+ _round(1, 0.6), 2, parallel=False)
+ assert not whole.edit_only and "Current file contents" not in whole.prompt
+
+
+def test_single_shot_refine_still_inlines_regardless_of_the_switch(tmp_path, chair_plan, settings, monkeypatch):
+ monkeypatch.delenv(FEWER_TURNS_ENV, raising=False)
+ track, ctx = _ctx(tmp_path, chair_plan, settings, agent_id="single-shot:fake:m")
+ files = {"src/parts/seat.py": SEAT}
+ _write(ctx.ws, files)
+ p = track._refine_task(ctx, _group(files), _round(1, 0.6), 2, parallel=False).prompt
+ assert "SEAT-BODY" in p and "return each edited file COMPLETE" in p and "Turn discipline" not in p
+
+
+# --------------------------------------------------------------------------- baseline: every file in turn one
+def test_baseline_prompt_carries_the_turn_discipline_block(tmp_path, chair_plan, settings, monkeypatch):
+ monkeypatch.setenv("CV3D_SCOPED_PARTS", "off")
+ monkeypatch.setenv(FEWER_TURNS_ENV, "1")
+ track, ctx = _ctx(tmp_path, chair_plan, settings)
+ (task,) = track.baseline_tasks(ctx)
+ assert task.label == "baseline" and TURN_DISCIPLINE in task.prompt
+ assert "write EVERY file" in task.prompt and "do not call those two tools separately".lower() in task.prompt.lower()
+ assert task.prompt.index("## Turn discipline") < task.prompt.index("## Output")
+ monkeypatch.delenv(FEWER_TURNS_ENV)
+ (off,) = _ctx(tmp_path / "off", chair_plan, settings)[0].baseline_tasks(_ctx(tmp_path / "off", chair_plan, settings)[1])
+ assert "Turn discipline" not in off.prompt
+ # single-shot has no tools to discipline
+ monkeypatch.setenv(FEWER_TURNS_ENV, "1")
+ t2, c2 = _ctx(tmp_path / "ss", chair_plan, settings, agent_id="single-shot:fake:m")
+ assert "Turn discipline" not in t2.baseline_tasks(c2)[0].prompt
+
+
+def test_scoped_baseline_and_assembly_prompts_carry_it_too(tmp_path, settings, monkeypatch):
+ from .test_generation_depth import big_plan
+
+ monkeypatch.delenv("CV3D_SCOPED_PARTS", raising=False)
+ monkeypatch.setenv(FEWER_TURNS_ENV, "1")
+ track, ctx = _ctx(tmp_path, big_plan(), settings, language=Language.THREEJS)
+ tasks = track.baseline_tasks(ctx)
+ assert len(tasks) >= 3
+ assert all("## Turn discipline" in t.prompt for t in tasks)
+ assemble = tasks[-1].prompt
+ assert "Read the CONNECTIVITY and CONTRACT sections of the `build` result" in assemble
+ assert "Run `check_connectivity` and `check_contract`" not in assemble
+ monkeypatch.delenv(FEWER_TURNS_ENV)
+ t2, c2 = _ctx(tmp_path / "off", big_plan(), settings, language=Language.THREEJS)
+ off = t2.baseline_tasks(c2)[-1].prompt
+ assert "Run `check_connectivity` and `check_contract`" in off and "Turn discipline" not in off
+
+
[email protected]("raw", ["1", "on", "true", "YES"])
+def test_every_truthy_spelling_turns_it_on(monkeypatch, raw):
+ monkeypatch.setenv(FEWER_TURNS_ENV, raw)
+ assert fewer_turns_enabled()