Skip to content

Official Codebase of 3DCodeVerse

Python

prompts: CV3D_LEAN_PROMPT drops the material the articulated agent already has (-45.7 % baseline)

ziyao3272f187ad8d
diff --git a/harness/codeverse/config.py b/harness/codeverse/config.py
index fc0d945d..dbd5b61a 100644
--- a/harness/codeverse/config.py
+++ b/harness/codeverse/config.py
@@ -108,6 +108,17 @@ class Limits(BaseModel):
"recipes seeded into the agent's own common.glsl were overwritten before the end of the run. "
"`CV3D_SEED_RECIPES=0` (read at call time by `seed_recipes_enabled`) is the control arm.",
)
+ lean_prompt: bool = Field(
+ default=False,
+ description="articulated_object AGENT sessions: stop re-sending what the session "
+ "already has. Measured on aa_articulated (2026-09-02): prompts/urdf/contract.md "
+ "(7 150 chars) rides in the baseline prompt AND byte-for-byte in the materialised "
+ "AGENTS.md/GEMINI.md; the tool list arrives three times (prompt 4 088 + GEMINI.md + "
+ "the MCP declarations); the whole 24 k cookbook is inlined though a brief-driven "
+ "chapter selector exists; and a refine prompt carries all acceptance items and all "
+ "part rows for a median of 3 targets. OFF until the A/B reads out; "
+ "`CV3D_LEAN_PROMPT=1` (read at call time by `lean_prompt_enabled`) is the variant arm.",
+ )
class Rate(BaseModel):
@@ -174,6 +185,8 @@ class Judge(BaseModel):
FEWER_TURNS_ENV = "CV3D_FEWER_TURNS"
#: The recipe-seeding switch (Limits.seed_recipes); same call-time contract as FEWER_TURNS_ENV.
SEED_RECIPES_ENV = "CV3D_SEED_RECIPES"
+#: The lean-articulated-prompt switch (Limits.lean_prompt); same call-time contract.
+LEAN_PROMPT_ENV = "CV3D_LEAN_PROMPT"
_TRUE_WORDS = frozenset({"1", "on", "true", "yes", "y"})
_FALSE_WORDS = frozenset({"0", "off", "false", "no", "n"})
@@ -215,6 +228,13 @@ def seed_recipes_enabled() -> bool:
return env_flag(SEED_RECIPES_ENV, get_settings().limits.seed_recipes)
+def lean_prompt_enabled() -> bool:
+ """Is the lean articulated prompt on for THIS call? ``$CV3D_LEAN_PROMPT`` when it is
+ set, else ``Settings.limits.lean_prompt`` (default OFF). ``tracks/prompting.lean_prompt``
+ is the only gate that consults it, and it also requires an articulated AGENT session."""
+ return env_flag(LEAN_PROMPT_ENV, get_settings().limits.lean_prompt)
+
+
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="CV3D_", env_nested_delimiter="__", extra="ignore")
@@ -229,6 +249,7 @@ class Settings(BaseSettings):
"CV3D_RENDER_GPU": ("render", "gpu"),
FEWER_TURNS_ENV: ("limits", "fewer_turns"),
SEED_RECIPES_ENV: ("limits", "seed_recipes"),
+ LEAN_PROMPT_ENV: ("limits", "lean_prompt"),
}
@model_validator(mode="after")
diff --git a/harness/codeverse/prompts/tracks/detail_object.j2 b/harness/codeverse/prompts/tracks/detail_object.j2
index 8fcc8cc8..84869df5 100644
--- a/harness/codeverse/prompts/tracks/detail_object.j2
+++ b/harness/codeverse/prompts/tracks/detail_object.j2
@@ -60,8 +60,10 @@ Detail vocabulary that is worth score here, cheapest first:
{% endif %}
{% if tool_cards and not single_shot %}
+{% if not lean %}
## Tools
{{ tool_cards }}
+{% endif %}
Run `build` and then `measure` after editing: if any part box moved by more than 5 mm, undo that
change before you finish.
{% endif %}
diff --git a/harness/codeverse/prompts/tracks/generate_articulated.j2 b/harness/codeverse/prompts/tracks/generate_articulated.j2
index 0f1bc91c..5479618a 100644
--- a/harness/codeverse/prompts/tracks/generate_articulated.j2
+++ b/harness/codeverse/prompts/tracks/generate_articulated.j2
@@ -15,7 +15,13 @@ Constraints:
## The contract (hard rules)
{{ frame_doc }}
+{% if lean %}
+The language contract is already in this workspace's agent instructions file (`AGENTS.md` =
+`GEMINI.md` = `CLAUDE.md`, loaded for you), and your 3dcv tools are declared in your tool
+list — read them there; neither is repeated below.
+{% else %}
{{ contract }}
+{% endif %}
{% if cookbook_rel %}Copyable snippets live in `{{ cookbook_rel }}`.{% endif %}
{% if cookbook_excerpt %}
Cookbook excerpt:
@@ -75,7 +81,7 @@ Joints (the URDF must realise EXACTLY these; pivots are WORLD points at rest):
{{ previous_error }}
{% endif %}
-{% if tool_cards and not single_shot %}
+{% if tool_cards and not single_shot and not lean %}
## Tools available to you
{{ tool_cards }}
{% endif %}
diff --git a/harness/codeverse/prompts/tracks/refine_object.j2 b/harness/codeverse/prompts/tracks/refine_object.j2
index 90a51128..017e12e6 100644
--- a/harness/codeverse/prompts/tracks/refine_object.j2
+++ b/harness/codeverse/prompts/tracks/refine_object.j2
@@ -58,8 +58,10 @@ Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}
{% endif %}
{% if tool_cards and not single_shot %}
+{% if not lean %}
## Tools
{{ tool_cards }}
+{% endif %}
Run `build` after editing and fix any error before finishing.
{% endif %}
{% if turn_discipline is defined and turn_discipline %}
diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.py
index 28395a4f..26b1c42a 100644
--- a/harness/codeverse/tracks/plan_features.py
+++ b/harness/codeverse/tracks/plan_features.py
@@ -34,7 +34,8 @@ GENERATION_SIDE: frozenset[str] = frozenset({CONTACTS})
GENERATION_SIDE_ENV: frozenset[str] = frozenset({"CV3D_SKILLS", "CV3D_SKILLS_MAX", "CV3D_SKILLS_UNVERIFIED",
"CV3D_SKILLS_ONLY",
"CV3D_DETAIL_ROUNDS", "CV3D_REFERENCE_DIFF",
- "CV3D_FEWER_TURNS", "CV3D_SEED_RECIPES"})
+ "CV3D_FEWER_TURNS", "CV3D_SEED_RECIPES",
+ "CV3D_LEAN_PROMPT"})
def pin_plan_blockers(variant_env: dict[str, str]) -> list[str]:
@@ -78,6 +79,11 @@ LIVE_SWITCHES: dict[str, str] = {
# switch, read at call time by config.fewer_turns_enabled; acts after planning.
"CV3D_FEWER_TURNS": "codeverse/config.py",
"CV3D_SEED_RECIPES": "codeverse/config.py",
+ # lean articulated prompt: drop from the per-turn prompt what the materialised
+ # AGENTS.md/GEMINI.md and the MCP tool declarations already carry, select cookbook
+ # chapters, focus the refine prompt. Read at call time by config.lean_prompt_enabled;
+ # it only ever changes the BUILDER's prompt, so an A/B over it may --pin-plan.
+ "CV3D_LEAN_PROMPT": "codeverse/config.py",
# model-transport switches (2026-08-28, the hung-read waves): streaming with
# inter-chunk stall detection, and the IPv4-only transport. Read at call time
# by every gemini request, so a control arm can set either to 0.
diff --git a/harness/codeverse/tracks/prompting.py b/harness/codeverse/tracks/prompting.py
index 665832e3..f8520272 100644
--- a/harness/codeverse/tracks/prompting.py
+++ b/harness/codeverse/tracks/prompting.py
@@ -13,7 +13,7 @@ from collections.abc import Sequence
from pathlib import Path
from typing import TYPE_CHECKING, Any
-from codeverse.config import fewer_turns_enabled
+from codeverse.config import fewer_turns_enabled, lean_prompt_enabled
from codeverse.contracts.chat import ImagePart
from codeverse.contracts.common import HARNESS_OWNED_SRC, Language, Track
from codeverse.contracts.plan import Plan, StaticPlan
@@ -104,11 +104,15 @@ def joints_table(plan: Plan) -> str:
return "\n".join(rows)
+def acceptance_line(item: Any) -> str:
+ return f"- [{item.id}] ({item.priority}, {item.how}) {item.text}"
+
+
def acceptance_lines(plan: Plan | None) -> str:
items = getattr(plan, "acceptance", None) or []
if not items:
return "(none)"
- return "\n".join(f"- [{a.id}] ({a.priority}, {a.how}) {a.text}" for a in items)
+ return "\n".join(acceptance_line(a) for a in items)
def bbox_line(bbox: Any) -> str:
@@ -260,6 +264,104 @@ def select_cookbook_chapters(ctx: RunContext, brief: str, *, budget: int = 9000,
return [chapters[i] for i in sorted(chosen)]
+# --------------------------------------------------------------------- lean articulated prompt
+#: urdf cookbook chapters an articulated prompt carries whatever the brief says: the frame
+#: recipe, both skeletons, joint semantics, clearances, pitfalls and the self-check. What is
+#: NOT here is the three worked examples — they are the 12 446 chars the brief chooses between.
+URDF_COOKBOOK_ALWAYS: tuple[str, ...] = (
+ "The frame recipe", "Skeleton (`src/model.py`", "Joint types, axes, limits",
+ "Clearances, rest pose, hardware", "URDF skeleton", "Pitfalls", "Self-check",
+)
+#: measured on prompts/urdf/cookbook.md: the always-set above is 11 680 chars and the worked
+#: examples are 4 976 (cabinet) / 4 677 (hand cart) / 2 793 (laptop). This budget admits the
+#: always-set plus exactly ONE example — the one the brief ranks first — and never a second.
+URDF_COOKBOOK_BUDGET = 16_700
+
+
+def lean_prompt(ctx: RunContext) -> bool:
+ """May this session's prompt drop what the workspace already carries?
+
+ Measured on aa_articulated (2026-09-02): the materialised AGENTS.md/GEMINI.md repeats
+ prompts/urdf/contract.md byte for byte, and the tool list reaches the model a third time
+ as MCP declarations — 11 k chars of the 53 k baseline prompt, on every turn. A
+ single-shot envelope has neither file nor tool declarations, so it keeps everything;
+ only the articulated track is measured, so only it is trimmed.
+ """
+ return (ctx.track is Track.ARTICULATED_OBJECT and not ctx.single_shot
+ and lean_prompt_enabled())
+
+
+def articulated_brief(ctx: RunContext) -> str:
+ """What ranks the cookbook's worked examples: the request plus the plan's own vocabulary.
+
+ Part and joint names are snake-cased back into words first — ``_words`` splits on
+ non-alphanumerics, so a raw ``DrawerFront`` is one token that matches nothing.
+ """
+ plan = ctx.plan
+ bits: list[str] = [ctx.spec.prompt, getattr(plan, "summary", "") or ""]
+ for p in getattr(plan, "parts", None) or ():
+ bits.append(to_snake(p.name).replace("_", " "))
+ for j in getattr(plan, "joints", None) or ():
+ bits += [to_snake(j.name).replace("_", " "), j.type, j.motion or ""]
+ return " ".join(b for b in bits if b)
+
+
+def cookbook_excerpt(ctx: RunContext, *, lean: bool) -> str:
+ """The cookbook the prompt inlines: the whole file, or the chapters this brief calls for.
+
+ The whole file is right when it is the ONLY copy the session has (single-shot, and every
+ track whose duplication is not measured). An articulated agent session also has it at
+ ``.3dcv/cookbook.md``, which the cookbook's own preamble — an always-carried chapter —
+ already points at, so nothing has to say where the unselected chapters went.
+ """
+ if not lean:
+ return ctx.cookbook_text
+ chapters = select_cookbook_chapters(ctx, articulated_brief(ctx), budget=URDF_COOKBOOK_BUDGET,
+ always=URDF_COOKBOOK_ALWAYS)
+ if not chapters:
+ return ctx.cookbook_text
+ return "\n\n".join(s.body.rstrip() for s in chapters)
+
+
+def acceptance_lines_focused(plan: Plan | None, failed: Sequence[Any]) -> str:
+ """Acceptance for a refine prompt: the FAILED items in full, the rest as their ids.
+
+ A refine round is told to change exactly the listed targets, so the items that already
+ pass are there to be preserved, not re-read — one id line each says that in 4 % of the
+ chars. Empty ``failed`` (no judgment, or everything passed) keeps the full list: with
+ nothing to focus on, focusing would only remove information."""
+ items = getattr(plan, "acceptance", None) or []
+ ids = {getattr(a, "id", "") for a in failed}
+ if not items or not ids:
+ return acceptance_lines(plan)
+ lines = [acceptance_line(a) for a in items if a.id in ids]
+ passing = [a.id for a in items if a.id not in ids]
+ if passing:
+ lines.append(f"- already verified, keep them true: {', '.join(passing)}")
+ return "\n".join(lines)
+
+
+def parts_table_for_targets(plan: Plan | None, targets: Sequence[str]) -> str:
+ """The plan rows for the refine targets — the whole table when none of them is a part.
+
+ The template's heading has always said "Plan rows for the targets"; the table under it
+ was every part in the plan (1 605 chars for a median of 3 targets, aa_articulated)."""
+ keys = {to_snake(t) for t in targets}
+ scoped = [p for p in (getattr(plan, "parts", None) or ()) if to_snake(p.name) in keys]
+ return parts_table_for(scoped) if scoped else parts_table(plan)
+
+
+def refine_focus(ctx: RunContext, last: RoundRecord, targets: Sequence[str]) -> dict[str, Any]:
+ """Refine-prompt overrides under the lean switch: focused acceptance + targeted parts.
+ ``{}`` when the switch is off, so the control arm renders byte-identically."""
+ if not lean_prompt(ctx):
+ return {}
+ from codeverse.tracks.steps import failed_acceptance # local: steps -> repair -> here
+
+ return {"acceptance": acceptance_lines_focused(ctx.plan, failed_acceptance(ctx, last.judgment)),
+ "parts_table": parts_table_for_targets(ctx.plan, targets)}
+
+
def language_system_prompt(language: Language, *, role: str = "", tools: bool = True, **vars: Any) -> str:
"""The generator's system prompt: ``prompts/<dir>/system.md``, or a role template.
@@ -289,6 +391,7 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
"""Variables every tracks/*.j2 template may use (StrictUndefined → all present)."""
plan = ctx.plan
object_name = getattr(plan, "object_name", None) or getattr(plan, "title", None) or "Object"
+ lean = lean_prompt(ctx)
d: dict[str, Any] = {
"track": ctx.track.value,
"language": ctx.language.value,
@@ -299,10 +402,13 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
# prefix that delivered 13 % of blender's and 10 % of scene_threejs's, cutting
# mid-snippet, and the read_cookbook tool that was supposed to fetch the rest
# went uncalled in all 20 measured sessions. Prompt material the harness wrote
- # for the model is not summarised by byte offset.
- "cookbook_excerpt": ctx.cookbook_text,
+ # for the model is not summarised by byte offset — CHAPTERS are the unit under
+ # the lean switch, and only where the session has the whole file on disk.
+ "cookbook_excerpt": cookbook_excerpt(ctx, lean=lean),
"tool_cards": ctx.tool_cards,
"single_shot": ctx.single_shot,
+ # templates drop with it only what the workspace already carries (see lean_prompt)
+ "lean": lean,
"output_format": SINGLE_SHOT_FORMAT if ctx.single_shot else AGENT_OUTPUT_RULES,
"spec_prompt": ctx.spec.prompt,
"constraints": constraints_text(ctx.spec),
diff --git a/harness/codeverse/tracks/static_object.py b/harness/codeverse/tracks/static_object.py
index 79fbdfc4..4e5c09d8 100644
--- a/harness/codeverse/tracks/static_object.py
+++ b/harness/codeverse/tracks/static_object.py
@@ -56,6 +56,7 @@ from codeverse.tracks.prompting import (
language_system_prompt,
measurement_vs_plan,
reference_images,
+ refine_focus,
refine_inline_files,
scope_context,
skeleton_files,
@@ -347,6 +348,10 @@ class StaticObjectTrack(BaseTrack):
# 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),
+ # lean switch only, {} when off: the failed acceptance items in full with
+ # the rest as ids, and the plan rows the heading already promises — this
+ # group's targets, not every part in the plan
+ **refine_focus(ctx, last, group.targets),
),
)
ctx.record_prompt("refine", prompt)
diff --git a/harness/tests/orchestrator_tracks/test_lean_prompt.py b/harness/tests/orchestrator_tracks/test_lean_prompt.py
new file mode 100644
index 00000000..7248dfb9
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_lean_prompt.py
@@ -0,0 +1,218 @@
+"""``CV3D_LEAN_PROMPT``: the articulated agent prompt stops re-sending what the session has.
+
+Measured on aa_articulated (2026-09-02, prompts dated 2026-09-01): the baseline prompt is
+53 562 chars and the CLI additionally loads GEMINI.md (18 444 B) plus 6 618 chars of MCP tool
+declarations on EVERY turn — with prompts/urdf/contract.md in both GEMINI.md and the prompt,
+the tool list in all three, the whole 24 k cookbook inlined, and a refine prompt carrying all
+26 acceptance items and all 9 part rows for a median of 3 targets.
+
+The switch is an A/B arm, so the control must be untouched: every test here renders the SAME
+context twice and the OFF arm has to come out byte-identical to what a caller that never heard
+of ``lean`` produces.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.config import LEAN_PROMPT_ENV, Settings, get_settings, lean_prompt_enabled
+from codeverse.contracts.artifacts import Judgment
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.plan import ArticulatedPlan
+from codeverse.contracts.run import RoundRecord
+from codeverse.orchestrator import BudgetGuard, RefineTask, RoundPolicy, RunState, TaskGroup
+from codeverse.proc import EventLog
+from codeverse.prompts import load_text, render
+from codeverse.tracks.common import RunContext, Services, cookbook_rel_for, language_contract
+from codeverse.tracks.plan_features import GENERATION_SIDE_ENV, LIVE_SWITCHES
+from codeverse.tracks.planner import plan_example
+from codeverse.tracks.prompting import (
+ URDF_COOKBOOK_ALWAYS,
+ base_prompt_context,
+ judge_digest,
+ lean_prompt,
+ refine_focus,
+)
+from codeverse.workspace import Workspace
+
+from .conftest import make_spec
+from .fakes import FakeRuntime, FakeServices
+
+GENERATE = "tracks/generate_articulated.j2"
+REFINE = "tracks/refine_object.j2"
+DETAIL = "tracks/detail_object.j2"
+
+
+def _ctx(tmp_path, *, track=Track.ARTICULATED_OBJECT, language=Language.URDF_BLENDER,
+ agent_id="gemini-cli:gemini-3.7-flash") -> RunContext:
+ """An articulated agent context with the REAL contract, cookbook and tool cards."""
+ ws = Workspace(tmp_path / "run").create()
+ spec = make_spec(track, language, prompt="a desk drawer unit with one sliding drawer")
+ plan = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))
+ ctx = RunContext(spec=spec, ws=ws, events=EventLog(ws.events_path),
+ settings=Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache"),
+ budget=BudgetGuard(spec.budget), runtime=FakeRuntime(language),
+ services=FakeServices(), state=RunState(), policy=RoundPolicy(),
+ track=track, rubric="r", agent_id=agent_id, plan=plan)
+ ctx.contract_text = language_contract(Language.URDF_BLENDER, None)
+ ctx.cookbook_rel = cookbook_rel_for(Language.URDF_BLENDER)
+ ctx.cookbook_text = load_text(ctx.cookbook_rel)
+ # the REAL registry cards, not FakeServices' two-line stub: their size is the measurement
+ ctx.tool_cards = Services().tool_cards(track.value, language.value)
+ return ctx
+
+
+def _last() -> RoundRecord:
+ return RoundRecord(index=1, kind="baseline", judgment=Judgment(
+ rubric="articulated_v1", overall=0.62, passed=False, summary="drawer face sits proud",
+ scores={"assembly_fit": 0.5}, acceptance_results={"a1": True, "a2": True, "j1": False}))
+
+
+def _group() -> TaskGroup:
+ return TaskGroup(tasks=[RefineTask(target="Drawer", kind="geometry", priority=2,
+ instruction="pull the drawer face back 8 mm",
+ files=["src/model.py"])], files=["src/model.py"])
+
+
+def _contexts(ctx: RunContext) -> dict[str, dict]:
+ """The three per-turn prompt contexts of an articulated round, as the track builds them."""
+ last, group = _last(), _group()
+ return {
+ GENERATE: base_prompt_context(ctx, expected_files=["src/model.py", "src/robot.urdf"],
+ skeleton_files={}, previous_error=""),
+ REFINE: base_prompt_context(ctx, round_index=1, tasks=["[gate/contract] Drawer: face proud"],
+ targets=group.targets, files=["src/model.py"], edit_only_these=True,
+ judge_summary=judge_digest(last), measurement_notes="",
+ current_files={}, **refine_focus(ctx, last, group.targets)),
+ DETAIL: base_prompt_context(ctx, round_index=2, tasks=["bevel the drawer face"],
+ files=["src/model.py"], judge_summary=judge_digest(last),
+ current_files={}),
+ }
+
+
+def _prompts(ctx: RunContext) -> dict[str, str]:
+ return {rel: render(rel, **vars_) for rel, vars_ in _contexts(ctx).items()}
+
+
+# --------------------------------------------------------------------------- the switch
+def test_switch_contract(monkeypatch):
+ monkeypatch.delenv(LEAN_PROMPT_ENV, raising=False)
+ assert not lean_prompt_enabled()
+ for raw in ("1", "on", "true", "YES"):
+ monkeypatch.setenv(LEAN_PROMPT_ENV, raw)
+ assert lean_prompt_enabled()
+ for raw in ("off", "maybe"):
+ monkeypatch.setenv(LEAN_PROMPT_ENV, raw)
+ assert not lean_prompt_enabled()
+ monkeypatch.setenv(LEAN_PROMPT_ENV, "on")
+ assert Settings().limits.lean_prompt is True
+ monkeypatch.delenv(LEAN_PROMPT_ENV)
+ get_settings.cache_clear()
+ assert Settings().limits.lean_prompt is False
+ # it only ever rewrites the BUILDER's prompt, so a paired A/B may share one plan
+ assert LIVE_SWITCHES[LEAN_PROMPT_ENV] == "codeverse/config.py"
+ assert LEAN_PROMPT_ENV in GENERATION_SIDE_ENV
+
+
+def test_only_an_articulated_agent_session_is_lean(tmp_path, monkeypatch):
+ monkeypatch.setenv(LEAN_PROMPT_ENV, "1")
+ assert lean_prompt(_ctx(tmp_path))
+ assert not lean_prompt(_ctx(tmp_path / "ss", agent_id="single-shot:fake:m"))
+ assert not lean_prompt(_ctx(tmp_path / "st", track=Track.STATIC_OBJECT, language=Language.BLENDER))
+ monkeypatch.delenv(LEAN_PROMPT_ENV)
+ get_settings.cache_clear()
+ assert not lean_prompt(_ctx(tmp_path / "off"))
+
+
+# --------------------------------------------------------------------------- reversibility
[email protected]("rel", [GENERATE, REFINE, DETAIL])
+def test_the_off_arm_is_byte_identical_to_the_prompt_without_the_switch(tmp_path, monkeypatch, rel):
+ """The control arm must be TODAY's prompt, not a re-flowed version of it.
+
+ The reference is the same context with ``lean`` removed — literally what every caller
+ passed before this switch existed, and what the templates then rendered."""
+ monkeypatch.delenv(LEAN_PROMPT_ENV, raising=False)
+ ctx = _ctx(tmp_path)
+ vars_ = _contexts(ctx)[rel]
+ assert vars_["lean"] is False
+ before = dict(vars_)
+ before.pop("lean")
+ assert render(rel, **vars_) == render(rel, **before)
+
+
+#: measured with this fixture (plan_example's DeskDrawerUnit): 18 504 / 4 295 / 4 098 chars
[email protected](("rel", "floor"), [(GENERATE, 16_000), (REFINE, 3_800), (DETAIL, 3_600)])
+def test_the_lean_arm_is_smaller_and_keeps_the_unique_material(tmp_path, monkeypatch, rel, floor):
+ monkeypatch.delenv(LEAN_PROMPT_ENV, raising=False)
+ off = _prompts(_ctx(tmp_path))[rel]
+ monkeypatch.setenv(LEAN_PROMPT_ENV, "1")
+ on = _prompts(_ctx(tmp_path / "on"))[rel]
+ assert len(off) - len(on) >= floor, (len(off), len(on))
+ # what only the prompt knows survives: this round's plan numbers, its tasks, how to finish
+ for keep in ("| Drawer |", "0.450", "HOW TO FINISH (agent mode)", "Z is UP"):
+ assert keep in on, keep
+ assert "`build`" in on # the tool the session must run before finishing is still named
+
+
+def test_lean_drops_the_contract_and_the_cards_the_workspace_already_carries(tmp_path, monkeypatch):
+ """Both are materialised into AGENTS.md/GEMINI.md/CLAUDE.md, and the cards a third time
+ as MCP declarations (agents/materialize.py:_body / _tool_section)."""
+ monkeypatch.delenv(LEAN_PROMPT_ENV, raising=False)
+ ctx = _ctx(tmp_path)
+ contract_tail = ctx.contract_text.strip().splitlines()[-1]
+ cards_head = ctx.tool_cards.strip().splitlines()[0]
+ off = _prompts(ctx)
+ monkeypatch.setenv(LEAN_PROMPT_ENV, "1")
+ on = _prompts(_ctx(tmp_path / "on"))
+ assert contract_tail in off[GENERATE] and contract_tail not in on[GENERATE]
+ assert "`AGENTS.md` =" in on[GENERATE] # it says where the contract is
+ for rel in (GENERATE, REFINE, DETAIL):
+ assert cards_head in off[rel] and cards_head not in on[rel], rel
+ assert "## Tools" in off[REFINE] and "## Tools" not in on[REFINE]
+ assert "Run `build` after editing" in on[REFINE] # the instruction, not the cards
+ assert "if any part box moved by more than 5 mm" in on[DETAIL]
+
+
+def test_single_shot_and_the_static_track_render_the_same_either_way(tmp_path, monkeypatch):
+ """Single-shot has no GEMINI.md and no tool declarations; the static track is not measured."""
+ for name, kw in (("ss", {"agent_id": "single-shot:fake:m"}),
+ ("st", {"track": Track.STATIC_OBJECT, "language": Language.BLENDER})):
+ monkeypatch.delenv(LEAN_PROMPT_ENV, raising=False)
+ off = _prompts(_ctx(tmp_path / f"{name}_off", **kw))
+ monkeypatch.setenv(LEAN_PROMPT_ENV, "1")
+ assert _prompts(_ctx(tmp_path / f"{name}_on", **kw)) == off, name
+
+
+# --------------------------------------------------------------------------- what lean keeps
+def test_the_cookbook_shrinks_to_the_always_chapters_plus_the_brief_s_example(tmp_path, monkeypatch):
+ """The urdf cookbook is 24 125 chars of which 12 446 are three worked examples; a drawer
+ brief needs the cabinet one. The always-set (frame recipe → self-check) is never dropped."""
+ monkeypatch.setenv(LEAN_PROMPT_ENV, "1")
+ ctx = _ctx(tmp_path)
+ excerpt = base_prompt_context(ctx)["cookbook_excerpt"]
+ assert len(excerpt) < len(ctx.cookbook_text) - 7_000
+ for chapter in URDF_COOKBOOK_ALWAYS:
+ assert chapter in excerpt, chapter
+ assert "Worked example 0: cabinet" in excerpt # door + drawer, prismatic
+ assert "Worked example 1: laptop" not in excerpt
+ assert "Worked example 2: hand cart" not in excerpt
+ assert ".3dcv/cookbook.md" in excerpt # where the rest is
+
+
+def test_refine_shows_the_failed_acceptance_in_full_and_only_the_targeted_parts(tmp_path, monkeypatch):
+ monkeypatch.setenv(LEAN_PROMPT_ENV, "1")
+ ctx = _ctx(tmp_path)
+ focus = refine_focus(ctx, _last(), ["Drawer"])
+ assert "[j1] (must, articulation) Drawer slides out" in focus["acceptance"]
+ assert "already verified, keep them true: a1, a2" in focus["acceptance"]
+ assert "Seat top at 0.45 m" not in focus["acceptance"]
+ rows = [r for r in focus["parts_table"].splitlines() if r.startswith("| ") and "|---" not in r]
+ assert [r.split("|")[1].strip() for r in rows] == ["part", "Drawer"]
+ # a target that is not a part (the judge's "overall") falls back to the whole table
+ whole = refine_focus(ctx, _last(), ["overall"])["parts_table"]
+ assert "| Cabinet | fixed carcass" in whole and "| Drawer |" in whole
+ # nothing failed → nothing to focus on, so the full checklist stands
+ passed = RoundRecord(index=1, kind="baseline", judgment=Judgment(
+ rubric="articulated_v1", overall=0.9, passed=True, summary="ok", scores={},
+ acceptance_results={"a1": True, "j1": True}))
+ assert "Seat top at 0.45 m" in refine_focus(ctx, passed, ["Drawer"])["acceptance"]