Official Codebase of 3DCodeVerse
Python
prompts: delete the CV3D_LEAN_PROMPT switch (D52 readout was inconclusive)
ziyaoa0f55f9a7d5b
diff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.pyindex c50c4f4d..5630320a 100644--- a/harness/codeverse/agents/materialize.py+++ b/harness/codeverse/agents/materialize.py@@ -44,11 +44,6 @@ log = logging.getLogger(__name__)CV3D_DIR = ".3dcv" # harness-owned read-only docs inside the workspaceMCP_SERVER_NAME = "3dcv"MCP_TOOL_TIMEOUT_MS = 600_000-#: backends that get NO MCP server, so the 3dcv tools never appear as declarations in the-#: session's own tool list — this file's ``_tool_section`` is their only tool documentation-#: and they call the tools from the shell. A prompt may point at "your tool list" only for-#: the kinds NOT in here (``tracks/prompting.tools_declared``).-MCPLESS_KINDS: frozenset[str] = frozenset({"agy"})#: ``.geminiignore`` / ``.aiexclude`` — gemini-cli's read_file/glob REFUSE ignored paths, so the#: agent-facing artefacts must stay readable: ``artifacts/*.json`` (the build tool advertises#: ``census.json`` etc.), ``artifacts/tool_renders/`` and ``trajectories/<label>_rNN/task_prompt.md``@@ -92,7 +87,7 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str],prove = [n for n in ("measure", "check_contract", "scene_probe", "gl_probe") if n in names]if agent_kind == "claude-code":how = "Tools are exposed by the MCP server `3dcv`; their names appear as `mcp__c3v__<name>` (e.g. `mcp__c3v__build`)."- elif agent_kind in MCPLESS_KINDS:+ elif agent_kind == "agy":how = ("This session has no MCP server. Call a tool from the shell instead:\n""`python -m codeverse.cli.main tools <name> --json '{\"arg\": \"value\"}'` "diff --git a/harness/codeverse/config.py b/harness/codeverse/config.pyindex 9a026356..fc0d945d 100644--- a/harness/codeverse/config.py+++ b/harness/codeverse/config.py@@ -108,18 +108,6 @@ 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 (median 18 604 chars over the 48 "- "recorded there) carries all 21 acceptance items when 6 failed, and every part row "- "for a median of 4 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):@@ -186,8 +174,6 @@ 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"})@@ -229,13 +215,6 @@ 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")@@ -250,7 +229,6 @@ 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/orchestrator.py b/harness/codeverse/orchestrator.pyindex 6d6b4c01..18b41ff6 100644--- a/harness/codeverse/orchestrator.py+++ b/harness/codeverse/orchestrator.py@@ -373,7 +373,7 @@ def compact_instructions(tasks: Sequence[RefineTask], max_lines: int = 6) -> lisreturn []groups: dict[str, list[RefineTask]] = {}for t in sorted(tasks, key=lambda t: t.priority):- groups.setdefault(instance_base(t.target), []).append(t)+ groups.setdefault(_instance_base(t.target), []).append(t)lines: list[str] = []for target, members in groups.items():if len(members) == 1:@@ -403,12 +403,7 @@ def _split_instance(target: str) -> tuple[str, str]:return target or "overall", ""-def instance_base(target: str) -> str:- """The plan name behind a refine target: ``Leg_1`` → ``Leg``, anything else unchanged.-- ``_canon_target`` keeps the suffix, so every consumer that matches a target against- plan part names has to strip it here rather than inventing its own rule- (``tracks/prompting.parts_table_for_targets`` is the other one)."""+def _instance_base(target: str) -> str:return _split_instance(target)[0]diff --git a/harness/codeverse/prompts/tracks/detail_object.j2 b/harness/codeverse/prompts/tracks/detail_object.j2index 84869df5..8fcc8cc8 100644--- a/harness/codeverse/prompts/tracks/detail_object.j2+++ b/harness/codeverse/prompts/tracks/detail_object.j2@@ -60,10 +60,8 @@ 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 thatchange before you finish.{% endif %}diff --git a/harness/codeverse/prompts/tracks/generate_articulated.j2 b/harness/codeverse/prompts/tracks/generate_articulated.j2index 6a74d94f..0f1bc91c 100644--- a/harness/codeverse/prompts/tracks/generate_articulated.j2+++ b/harness/codeverse/prompts/tracks/generate_articulated.j2@@ -15,14 +15,7 @@ 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){% if tools_declared %}, and your 3dcv tools are declared in your-tool list{% else %}, which is also where your 3dcv tools are documented — this session has no MCP server,-so you call them from the shell as that file shows{% endif %} — 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:@@ -82,7 +75,7 @@ Joints (the URDF must realise EXACTLY these; pivots are WORLD points at rest):{{ previous_error }}{% endif %}-{% if tool_cards and not single_shot and not lean %}+{% if tool_cards and not single_shot %}## Tools available to you{{ tool_cards }}{% endif %}diff --git a/harness/codeverse/prompts/tracks/refine_object.j2 b/harness/codeverse/prompts/tracks/refine_object.j2index e5d2ad20..cd3f4593 100644--- a/harness/codeverse/prompts/tracks/refine_object.j2+++ b/harness/codeverse/prompts/tracks/refine_object.j2@@ -33,13 +33,9 @@ Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}## Plan rows for the targets (bbox centre/extents in meters — the truth to converge to){{ parts_table }}-## Acceptance checklist{% if not lean %} (unchanged){% endif %}+## Acceptance checklist (unchanged){{ acceptance }}-{% if plan_pointer %}--{{ plan_pointer }}-{% endif %}## Detail budget{{ detail_budget }}@@ -63,10 +59,8 @@ 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.pyindex fecc3bb2..a04f2cf5 100644--- a/harness/codeverse/tracks/plan_features.py+++ b/harness/codeverse/tracks/plan_features.py@@ -34,8 +34,7 @@ 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_LEAN_PROMPT"})+ "CV3D_FEWER_TURNS", "CV3D_SEED_RECIPES"})def pin_plan_blockers(variant_env: dict[str, str]) -> list[str]:@@ -81,11 +80,6 @@ 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.pyindex df5c5333..f1bbb636 100644--- a/harness/codeverse/tracks/prompting.py+++ b/harness/codeverse/tracks/prompting.py@@ -13,13 +13,12 @@ from collections.abc import Sequencefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any-from codeverse.config import fewer_turns_enabled, lean_prompt_enabled+from codeverse.config import fewer_turns_enabledfrom codeverse.contracts.chat import ImagePartfrom codeverse.contracts.common import HARNESS_OWNED_SRC, Language, Track, is_harness_ownedfrom codeverse.contracts.plan import Plan, StaticPlanfrom codeverse.contracts.run import RoundRecordfrom codeverse.conventions import LANGUAGE_FRAME, Frame, frame_doc, to_snake-from codeverse.orchestrator import instance_basefrom codeverse.prompts import renderfrom codeverse.prompts.catalog import prompt_dir_forfrom codeverse.tracks.common import RunContext@@ -265,141 +264,6 @@ 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 tools_declared(ctx: RunContext) -> bool:- """Does this session see the 3dcv tools as declarations of its own?-- True for every backend the harness gives an MCP server; false for the mcp-less ones- (:data:`agents.materialize.MCPLESS_KINDS`), whose materialised instructions say the- opposite — "This session has no MCP server", call them from the shell. A prompt that- drops the tool cards has to point at whichever of the two the session actually got."""- from codeverse.agents.materialize import MCPLESS_KINDS # local: tracks -> agents stays lazy-- return ctx.agent_kind not in MCPLESS_KINDS---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 a third of- the chars (median 2 625 -> 885 over the 48 recorded refine prompts of aa_articulated:- 20 items, 6 of them failed on the round that precedes the prompt). 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 unless EVERY target 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 (median 1 532 chars over the 48 recorded refine prompts of- aa_articulated). Narrowing is only honest when the round is ABOUT those parts: a group- that also carries the whole-artifact target (``overall`` — where a gate error with no- part of its own lands) is about the assembly, and an assembly is judged against rows- this would have dropped. That is most rounds — 40 of those 48 prompts carry ``overall``- and only 3 narrow — which is the price of not lying about what the table is. Instance- suffixes come off first: ``_canon_target`` hands on the plan's spelling but keeps the- ``Leg_1``, and the plan has no such row."""- keys = {to_snake(instance_base(t)) for t in targets}- parts = list(getattr(plan, "parts", None) or ())- if not keys or not keys <= {to_snake(p.name) for p in parts}:- return parts_table(plan)- return parts_table_for([p for p in parts if to_snake(p.name) in keys])---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.-- Whatever is dropped gets a pointer to ``plan.json``, which is in the workspace and is- neither git- nor agent-ignored. Measured precedent says the model will not fetch it- (the ``read_cookbook`` tool went uncalled in all 20 sessions of the excerpt study), so- the pointer buys nothing when nothing was dropped — hence it names only what actually- went, and is empty when the two helpers returned the full text anyway."""- if not lean_prompt(ctx):- return {}- from codeverse.tracks.steps import failed_acceptance # local: steps -> repair -> here-- acceptance = acceptance_lines_focused(ctx.plan, failed_acceptance(ctx, last.judgment))- parts = parts_table_for_targets(ctx.plan, targets)- dropped: list[str] = []- if acceptance != acceptance_lines(ctx.plan):- dropped.append("the text of the acceptance items listed by id only")- if parts != parts_table(ctx.plan):- dropped.append("the rows of the parts this round does not name")- pointer = (f"Elided from this prompt and readable in `{ctx.ws.plan_path.name}` at the workspace "- f"root: {'; '.join(dropped)}." if dropped else "")- return {"acceptance": acceptance, "parts_table": parts, "plan_pointer": pointer}--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.@@ -448,7 +312,6 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:"""Variables every tracks/*.j2 template may use (StrictUndefined → all present)."""plan = ctx.planobject_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,@@ -459,18 +322,10 @@ 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 — 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),+ # for the model is not summarised by byte offset.+ "cookbook_excerpt": ctx.cookbook_text,"tool_cards": ctx.tool_cards,"single_shot": ctx.single_shot,- # templates drop with it only what the workspace already carries (see lean_prompt),- # and say where it went: the tools in the session's own declarations or, for an- # mcp-less backend, in the instructions file; the elided plan material in plan.json- # (refine only, so "" here — refine_focus fills it when something was actually cut)- "lean": lean,- "tools_declared": tools_declared(ctx),- "plan_pointer": "","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.pyindex 36d998eb..79fbdfc4 100644--- a/harness/codeverse/tracks/static_object.py+++ b/harness/codeverse/tracks/static_object.py@@ -56,7 +56,6 @@ from codeverse.tracks.prompting import (language_system_prompt,measurement_vs_plan,reference_images,- refine_focus,refine_inline_files,scope_context,skeleton_files,@@ -348,11 +347,6 @@ 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 editcurrent_files=refine_inline_files(ctx, files, scoped=scoped),- # lean switch only, {} when off: the failed acceptance items in full with- # the rest as ids, the plan rows the heading already promises (this group's- # targets, when every one of them IS a part), and a pointer to plan.json- # for whatever that dropped- **refine_focus(ctx, last, group.targets),),)ctx.record_prompt("refine", prompt)diff --git a/harness/docs/DECISIONS.md b/harness/docs/DECISIONS.mdindex 9d90ca90..cbfdfcfb 100644--- a/harness/docs/DECISIONS.md+++ b/harness/docs/DECISIONS.md@@ -693,8 +693,10 @@ written) that were accepted because the code works that way and the tests pin itsd 0.131, **2 SE ±0.076**, 8 up / 3 down (p 0.227), one regression — inconclusive bythe rig's own rule — and no cost saving ($3.51 vs $3.66 per scored cell), which is thesecond time a prompt/turn-shape change has moved tokens without moving dollars- (docs/COST.md §29). The switch and its measured character savings stay for the day a- larger battery can resolve them.+ (docs/COST.md §29). The switch itself was DELETED in review (2026-09-03, −569 lines):+ an inconclusive lever with no cost saving is not worth a second prompt path through+ three templates, and the measurement above is the record of what it was worth. To+ re-run it, restore the branch commit named in docs/PAPER_WRITING.md §9.3.* **`<mimic>` is used and it changes the sweep, which is what it was for.** In the samebattery the planner and agent declared couplings in 8 of 14 prompts (umbrella 6 joints,workbench 4, step ladder 4, scissor mirror 3, rolltop desk 3), and the sampled posesdiff --git a/harness/docs/PAPER_WRITING.md b/harness/docs/PAPER_WRITING.mdindex de81f7a1..5c03c6d5 100644--- a/harness/docs/PAPER_WRITING.md+++ b/harness/docs/PAPER_WRITING.md@@ -148,7 +148,7 @@ They are recorded so nobody re-runs them expecting a different answer.| **Pro planner** (`gemini-3.1-pro` vs `3.7-flash`) | `compare_art_v4` pp vs pf | 13 | +0.090 | ±0.23 | 9/2/2 | keep flash: 2–10× plan cost, 5/14 cells lost to provider limits || **Deterministic repairs** (`CV3D_ART_REPAIRS`) | `ab_repairs`, plan pinned | 12 | −0.039 | ±0.105 | 2/5/5 | ships **OFF**; the axis flip fired in 1 of 12 cells || **Fewer turns** (`CV3D_FEWER_TURNS`) | `ab_fewer_turns`, plan pinned | 14 | +0.015 | ±0.126 | 6/5/3 | ships **OFF**; −12 % tool calls, $/cell unchanged |-| **Lean prompt** (`CV3D_LEAN_PROMPT`) | `wave2_lean`, plan pinned | 12 | +0.030 | ±0.076 | 8/3/1 | ships **OFF**; −45.7 % generate prompt chars, $3.51 vs $3.66 per cell |+| **Lean prompt** (`CV3D_LEAN_PROMPT`) | `wave2_lean`, plan pinned | 12 | +0.030 | ±0.076 | 8/3/1 | ships **OFF**; −45.7 % generate prompt chars, $3.51 vs $3.66 per cell; code removed 2026-09-03 in review (D52); the numbers stand, the second prompt path does not. |Two of these carry a second, non-score reading worth keeping:@@ -406,7 +406,7 @@ a test enforces by grepping the tree; a switch nothing reads once produced "keep| `CV3D_PLAN_GEOMETRY` | plan-time geometry re-ask (attachment gap, hinge pivot, swept collision) | **off** | +0.064 ±0.25, no measurable gain (§4) || `CV3D_PLAN_RESTART` | re-sample a degenerate plan from the original request | **on**, kill switch | 4.7 % → 0.7 % planner mortality, p = 0.0067 (§5.1) || `CV3D_ART_REPAIRS` | axis flip on a reversed joint + buried-link check | **off** | −0.039 ±0.105, fired 1/12 (§4) |-| `CV3D_LEAN_PROMPT` | drop duplicated contract/tool cards, select cookbook chapters, focus the refine prompt | **off** | +0.030 ±0.076, no cost saving (§4) |+| `CV3D_LEAN_PROMPT` | drop duplicated contract/tool cards, select cookbook chapters, focus the refine prompt | **off** | +0.030 ±0.076, no cost saving (§4); **removed from the tree 2026-09-03**; last carried on `ziyao/articulated-wave-2` before commit `554b52b`. || `CV3D_FEWER_TURNS` (pre-existing) | fold gate checks into build, inline refine files | **off** | +0.015 ±0.126, dollars flat (§4) || `CV3D_AXIS_REPAIR` (upstream) | deterministic axis rewrite from the measured motion | on | upstream's, kept |@@ -424,7 +424,7 @@ python bench/ab_plan.py --prompts bench/prompts/articulated_v2.yaml --aa --pin-p--n-samples 3 --rounds 3 --out bench/out/aa_articulated# a switch A/B (generation-side switches only; plan-side is refused for --pin-plan)python bench/ab_plan.py --prompts bench/prompts/articulated_v2.yaml \- --variant-env CV3D_LEAN_PROMPT=1 --pin-plan --out bench/out/lean+ --variant-env CV3D_FEWER_TURNS=1 --pin-plan --out bench/out/fewer_turns# harness vs one-shotpython bench/compare_backends.py --prompts bench/prompts/articulated_v2.yaml \--arms harness:gemini-cli:gemini-3.7-flash,oneshot+repair:gemini:gemini-3.7-flash \diff --git a/harness/tests/orchestrator_tracks/test_lean_prompt.py b/harness/tests/orchestrator_tracks/test_lean_prompt.pydeleted file mode 100644index e7abb5c5..00000000--- a/harness/tests/orchestrator_tracks/test_lean_prompt.py+++ /dev/null@@ -1,356 +0,0 @@-"""``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 (median-18 604 chars over the 48 recorded there) carrying all 21 acceptance items when 6 had failed,-and every part row for a median of 4 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 subprocess-from pathlib import Path--import pytest-from jinja2 import ChoiceLoader, DictLoader, FileSystemLoader--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 PROMPTS_DIR, _env, load_text, render-from codeverse.tracks.articulated_object import ArticulatedObjectTrack-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"--#: the last commit before ``CV3D_LEAN_PROMPT`` existed. Pinned by sha on purpose: the value-#: of this reference is that it does NOT move with the branch — it is the literal template a-#: caller that never heard of ``lean`` rendered.-PRE_LEAN = "ee38e5d375fd4900f45ff8e1a20f5cdb464ddace"-HARNESS = Path(__file__).resolve().parents[2]---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 _track_ctx(tmp_path, *, agent_id="gemini-cli:gemini-3.7-flash") -> tuple[ArticulatedObjectTrack, RunContext]:- """The REAL track and the context it builds — the production path into ``_refine_task``."""- ws = Workspace(tmp_path / "run").create()- settings = Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")- track = ArticulatedObjectTrack(services=FakeServices(), settings=settings,- runtime=FakeRuntime(Language.URDF_BLENDER))- spec = make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER, generator=agent_id,- prompt="a desk drawer unit with one sliding drawer")- ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState(slug="d"))- ctx.plan = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))- return track, ctx---def _pre_lean_templates():- """The three templates as of :data:`PRE_LEAN`, in the STRICT prompt environment.-- ``prompts.render`` falls back to a lenient environment when a template wants a name its- caller does not pass — under that fallback an unknown ``lean`` renders as empty, i.e. as- the OFF arm, and a reversibility test would pass for the wrong reason. Overlaying the- real environment keeps the settings that decide the bytes (trim_blocks, lstrip_blocks,- keep_trailing_newline)."""- srcs: dict[str, str] = {}- for rel in (GENERATE, REFINE, DETAIL):- out = subprocess.run(["git", "show", f"{PRE_LEAN}:./codeverse/prompts/{rel}"],- cwd=HARNESS, capture_output=True, text=True, check=False)- if out.returncode:- pytest.skip(f"no git object {PRE_LEAN} here: {out.stderr.strip()}")- srcs[rel] = out.stdout- return _env.overlay(loader=ChoiceLoader([DictLoader(srcs), FileSystemLoader(str(PROMPTS_DIR))]))---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 _rows(table: str) -> list[str]:- """The part names of a rendered parts table, header row and rule dropped."""- rows = [r for r in table.splitlines() if r.startswith("| ") and "|---" not in r]- return [r.split("|")[1].strip() for r in rows][1:]---#: plan_example's DeskDrawerUnit has exactly these parts, in this order-ALL_ROWS = ["Cabinet", "Drawer"]---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-#: the names the switch added to every prompt context; the pre-lean templates use none of them-LEAN_VARS = ("lean", "tools_declared", "plan_pointer")--[email protected]("rel", [GENERATE, REFINE, DETAIL])-def test_the_off_arm_is_byte_identical_to_the_prompt_before_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 template FILE as of :data:`PRE_LEAN`, rendered strictly with the- same context minus the names the switch introduced — what a caller that never heard of- ``lean`` passed, and what the templates then rendered, byte for byte."""- monkeypatch.delenv(LEAN_PROMPT_ENV, raising=False)- ctx = _ctx(tmp_path)- vars_ = _contexts(ctx)[rel]- assert vars_["lean"] is False and vars_["plan_pointer"] == ""- before = {k: v for k, v in vars_.items() if k not in LEAN_VARS}- today = _env.get_template(rel).render(**vars_) # strict: no lenient fallback to hide a rename- assert render(rel, **vars_) == today # ...and that is what production renders- assert today == _pre_lean_templates().get_template(rel).render(**before)---#: measured with this fixture (plan_example's DeskDrawerUnit): 18 504 / 4 131 / 4 098 chars.-#: A fixture is not the corpus — what one refine prompt of the aa_articulated battery saves is-#: in the commit message, and it is smaller (its rounds mostly keep the whole parts table).[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"]- assert _rows(focus["parts_table"]) == ["Drawer"]- # 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"]--[email protected](("targets", "rows"), [- (["Drawer"], ["Drawer"]),- (["Drawer", "Cabinet"], ALL_ROWS), # narrowed to both, which happens to be all of them- (["Drawer_1"], ["Drawer"]), # _canon_target keeps the instance suffix; the plan has no such row- (["drawer"], ["Drawer"]), # the match is on to_snake, not on spelling- (["overall"], ALL_ROWS), # the whole artifact- (["Drawer", "overall"], ALL_ROWS), # ...even next to a part- (["overall", "Drawer"], ALL_ROWS), # ...in either order- (["Hinge"], ALL_ROWS), # a target the plan does not know- ([], ALL_ROWS), # no targets at all is not "no rows"-])-def test_the_parts_table_narrows_only_when_every_target_is_a_part(tmp_path, monkeypatch, targets, rows):- """A group carrying the whole-artifact target is about the assembly, and an assembly is- judged against the rows narrowing would drop, so ONE non-part target keeps the table whole."""- monkeypatch.setenv(LEAN_PROMPT_ENV, "1")- assert _rows(refine_focus(_ctx(tmp_path), _last(), targets)["parts_table"]) == rows---def test_what_was_elided_points_at_plan_json_and_the_heading_stops_saying_unchanged(tmp_path, monkeypatch):- """Material the model must fetch is never fetched (the read_cookbook study), so the pointer- is not a promise — but a checklist rewritten to ids while its heading says "(unchanged)"- is a lie, and a prompt that drops rows without naming the file holding them is a dead end.- The pointer names only what actually went: with nothing failed and no part target, nothing- is dropped and there is no pointer."""- monkeypatch.setenv(LEAN_PROMPT_ENV, "1")- ctx = _ctx(tmp_path)- both = refine_focus(ctx, _last(), ["Drawer"])["plan_pointer"]- assert "`plan.json`" in both and ctx.ws.plan_path.name == "plan.json"- assert "acceptance items listed by id" in both and "parts this round does not name" in both- kept = refine_focus(ctx, _last(), ["overall"])["plan_pointer"]- assert "acceptance items listed by id" in kept and "does not name" not in kept- 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 refine_focus(ctx, passed, ["overall"])["plan_pointer"] == ""-- monkeypatch.delenv(LEAN_PROMPT_ENV)- get_settings.cache_clear()- off = _prompts(_ctx(tmp_path / "off"))[REFINE]- monkeypatch.setenv(LEAN_PROMPT_ENV, "1")- on = _prompts(_ctx(tmp_path / "on"))[REFINE]- # ("plan.json" alone is no evidence: check_contract's tool card names it too)- assert "## Acceptance checklist (unchanged)" in off and "Elided from this prompt" not in off- assert "## Acceptance checklist\n" in on and "(unchanged)" not in on- assert both in on---def test_the_pointer_names_the_tool_channel_this_backend_actually_got(tmp_path, monkeypatch):- """agy has no MCP server: `agents/materialize._tool_section` tells it the tools are shell- calls documented in that same file, so "declared in your tool list" would be false."""- monkeypatch.setenv(LEAN_PROMPT_ENV, "1")- mcp = _prompts(_ctx(tmp_path / "gem"))[GENERATE]- shell = _prompts(_ctx(tmp_path / "agy", agent_id="agy:gemini-3.7-flash"))[GENERATE]- assert "declared in your\ntool list" in mcp and "no MCP server" not in mcp- assert "this session has no MCP server" in shell and "declared in your" not in shell- for p in (mcp, shell): # the contract half is the same either way- assert "`AGENTS.md` =" in p---# --------------------------------------------------------------------------- the production path-def test_the_track_s_own_refine_prompt_is_the_focused_one(tmp_path, monkeypatch):- """Through ``ArticulatedObjectTrack._refine_task`` — the only caller of ``refine_focus``.-- A hand-built context proves the helpers; deleting the call from the track leaves those- tests green and every real refine prompt fat."""- monkeypatch.setenv(LEAN_PROMPT_ENV, "1")- track, ctx = _track_ctx(tmp_path)- prompt = track._refine_task(ctx, _group(), _last(), 2, parallel=True).prompt- assert "already verified, keep them true: a1, a2" in prompt- assert "Seat top at 0.45 m" not in prompt # the passing items, by id only- assert _rows(prompt) == ["Drawer"] # not every part in the plan- assert "Elided from this prompt" in prompt and "## Acceptance checklist\n" in prompt-- monkeypatch.delenv(LEAN_PROMPT_ENV)- get_settings.cache_clear()- track, ctx = _track_ctx(tmp_path / "off")- off = track._refine_task(ctx, _group(), _last(), 2, parallel=True).prompt- assert "Seat top at 0.45 m" in off and _rows(off) == ALL_ROWS- assert "## Acceptance checklist (unchanged)" in off and "Elided from this prompt" not in off