Official Codebase of 3DCodeVerse
Python
delete the in-process coding agent: the vendors already ship one
gaoypeng91e4099cdde4
diff --git a/harness/CLAUDE.md b/harness/CLAUDE.mdindex 4a009946..476c5051 100644--- a/harness/CLAUDE.md+++ b/harness/CLAUDE.md@@ -4,9 +4,14 @@ Backend harness (python package `codeverse`, CLI `3dcodeverse` / short alias `3drepo path `/home/yipeng/3dcodeverse/harness`) for LLM-written **raw** 3D code:Blender bpy · CadQuery · Three.js · URDF · GLSL / OpenGL, across four tracks(`static_object`, `articulated_object`, `scene`, `graphics`), with pluggable-backends (Gemini/Anthropic/OpenAI APIs + gemini-cli / claude-code / codex /-antigravity / in-process api-agent / single-shot), an optional text-to-image-texture pass, and a data-flywheel record per run.+backends. **The coding agent is always a VENDOR's** — gemini-cli / claude-code /+codex / antigravity — and the harness supplies the workspace, the prompt and its 20+3D tools (over MCP), then reads the result. The harness's OWN api use is planning,+judging, single-shot file generation and the texture pass (Gemini/Anthropic/OpenAI).+It does not implement an agent loop: the in-process `api-agent` was deleted+2026-08-28 (owner's call — reimplementing what the vendors already ship was never+this project's job). Plus an optional text-to-image texture pass and a+data-flywheel record per run.Read `docs/ARCHITECTURE.md` (design, package map, authoring contracts, what a runreally does, known limits), `docs/INTERFACES.md` (binding cross-package signatures as@@ -86,7 +91,7 @@ cd /home/yipeng/3dcodeverse/harness3dcv bench run bench/prompts/static_objects_v1.yaml --generator ... --judge gemini:gemini-3.1-pro-previewpython -m codeverse.judges.calibration runs/<slug>... --model gemini:gemini-3.1-pro-preview --n 3 --out out/python bench/complexity_report.py bench/out --recursive # score-vs-complexity + $/complexity point (docs/COMPLEXITY.md)-python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml --arms harness:api-agent:gemini:gemini-3.7-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1+python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml --arms harness:gemini-cli:gemini-3.6-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1python -m pytest tests -q -m "not live" # ~860 offline tests; add "and not blender and not node" for pure python```diff --git a/harness/bench/ab_plan.py b/harness/bench/ab_plan.pyindex b3cf1b96..3dc23e06 100644--- a/harness/bench/ab_plan.py+++ b/harness/bench/ab_plan.py@@ -2,7 +2,7 @@python bench/ab_plan.py --prompts bench/prompts/static_objects_v2.yaml \\--variant-env CV3D_PLAN_BRIEF=on --out bench/out/ab_brief \\- [--generator api-agent:gemini:gemini-3.7-flash] [--judge gemini:gemini-3.1-pro-preview] \\+ [--generator gemini-cli:gemini-3.6-flash] [--judge gemini:gemini-3.1-pro-preview] \\[--rounds 2] [--max-usd 2.5] [--ids a,b] [--wait-for-provider 60] [--redo-status infra_failed]The only thing that differs between the arms is the ``--variant-env`` block, applied to@@ -114,7 +114,7 @@ from codeverse.workspace import Workspace # noqa: E402log = logging.getLogger(__name__)-DEFAULT_GENERATOR = "api-agent:gemini:gemini-3.7-flash"+DEFAULT_GENERATOR = "gemini-cli:gemini-3.6-flash"DEFAULT_JUDGE = "gemini:gemini-3.1-pro-preview"#: the per-child cap. The flat name is a first-class alias of ``CV3D_RATE__MAX_IN_FLIGHT``#: since 2026-08-24 (``Settings._FLAT_ALIASES``; before that it was read by nothing) anddiff --git a/harness/bench/compare_backends.py b/harness/bench/compare_backends.pyindex 87f06e0e..39f051cf 100644--- a/harness/bench/compare_backends.py+++ b/harness/bench/compare_backends.py@@ -1,7 +1,7 @@"""Harness vs raw one-shot generation under ONE fixed judge (methodology bench).python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml \\- --arms harness:api-agent:gemini:gemini-3.7-flash,harness:gemini-cli:gemini-3.7-flash,\\+ --arms harness:gemini-cli:gemini-3.6-flash,harness:gemini-cli:gemini-3.7-flash,\\oneshot:claude-code,oneshot:codex,oneshot:gemini:gemini-3.7-flash \\--judge gemini:gemini-3.1-pro-preview --out <dir> [--parallel 8] [--limit N]diff --git a/harness/bench/prompts/complexity_v3.yaml b/harness/bench/prompts/complexity_v3.yamlindex 4a0f23a7..56ec3cab 100644--- a/harness/bench/prompts/complexity_v3.yaml+++ b/harness/bench/prompts/complexity_v3.yaml@@ -15,7 +15,7 @@# (extra keys are ignored); `bench/complexity_report.py --battery` reads it.## 3dcv bench run bench/prompts/complexity_v3.yaml --out bench/out/complexity_v3 \-# --generator api-agent:gemini:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview+# --generator gemini-cli:gemini-3.6-flash --judge gemini:gemini-3.1-pro-preview# python bench/complexity_report.py bench/out/complexity_v3 --battery bench/prompts/complexity_v3.yaml## Ladder (measured index of the nearest corpus run is in brackets):diff --git a/harness/bench/prompts/teaser_v1_articulated.yaml b/harness/bench/prompts/teaser_v1_articulated.yamlindex 96e0197e..aff02e54 100644--- a/harness/bench/prompts/teaser_v1_articulated.yaml+++ b/harness/bench/prompts/teaser_v1_articulated.yaml@@ -2,7 +2,7 @@# one track + language (bench/run_bench.py). Cross-language prompts inside a track use# the per-prompt `language:` override. These four files ARE the source; edit them here.# Regenerate: python /tmp/claude-1000/-home-yipeng/256e9f01-5a86-4d6d-9b4b-3d662f71921d/scratchpad/teaser/make_batteries.py-# Heroes (run with codex:gpt-5.6-sol, everything else api-agent:gemini:gemini-3.7-flash): (none)+# Heroes (run with codex:gpt-5.6-sol, everything else gemini-cli:gemini-3.6-flash): (none)name: teaser_v1_articulatedtrack: articulated_objectlanguage: urdf_blenderdiff --git a/harness/bench/prompts/teaser_v1_graphics.yaml b/harness/bench/prompts/teaser_v1_graphics.yamlindex a63f104a..6c6f1b64 100644--- a/harness/bench/prompts/teaser_v1_graphics.yaml+++ b/harness/bench/prompts/teaser_v1_graphics.yaml@@ -2,7 +2,7 @@# one track + language (bench/run_bench.py). Cross-language prompts inside a track use# the per-prompt `language:` override. These four files ARE the source; edit them here.# Regenerate: python /tmp/claude-1000/-home-yipeng/256e9f01-5a86-4d6d-9b4b-3d662f71921d/scratchpad/teaser/make_batteries.py-# Heroes (run with codex:gpt-5.6-sol, everything else api-agent:gemini:gemini-3.7-flash): (none)+# Heroes (run with codex:gpt-5.6-sol, everything else gemini-cli:gemini-3.6-flash): (none)name: teaser_v1_graphicstrack: graphicslanguage: glsl_shaderdiff --git a/harness/bench/prompts/teaser_v1_scene.yaml b/harness/bench/prompts/teaser_v1_scene.yamlindex d4e43f17..727c1be3 100644--- a/harness/bench/prompts/teaser_v1_scene.yaml+++ b/harness/bench/prompts/teaser_v1_scene.yaml@@ -2,7 +2,7 @@# one track + language (bench/run_bench.py). Cross-language prompts inside a track use# the per-prompt `language:` override. These four files ARE the source; edit them here.# Regenerate: python /tmp/claude-1000/-home-yipeng/256e9f01-5a86-4d6d-9b4b-3d662f71921d/scratchpad/teaser/make_batteries.py-# Heroes (run with codex:gpt-5.6-sol, everything else api-agent:gemini:gemini-3.7-flash): tsr_scn_temple_night+# Heroes (run with codex:gpt-5.6-sol, everything else gemini-cli:gemini-3.6-flash): tsr_scn_temple_nightname: teaser_v1_scenetrack: scenelanguage: scene_threejsdiff --git a/harness/bench/prompts/teaser_v1_static.yaml b/harness/bench/prompts/teaser_v1_static.yamlindex a0a4e64d..9977a8d1 100644--- a/harness/bench/prompts/teaser_v1_static.yaml+++ b/harness/bench/prompts/teaser_v1_static.yaml@@ -2,7 +2,7 @@# one track + language (bench/run_bench.py). Cross-language prompts inside a track use# the per-prompt `language:` override. These four files ARE the source; edit them here.# Regenerate: python /tmp/claude-1000/-home-yipeng/256e9f01-5a86-4d6d-9b4b-3d662f71921d/scratchpad/teaser/make_batteries.py-# Heroes (run with codex:gpt-5.6-sol, everything else api-agent:gemini:gemini-3.7-flash): tsr_obj_penny_farthing, tsr_cad_radial_engine+# Heroes (run with codex:gpt-5.6-sol, everything else gemini-cli:gemini-3.6-flash): tsr_obj_penny_farthing, tsr_cad_radial_enginename: teaser_v1_statictrack: static_objectlanguage: blenderdiff --git a/harness/bench/prompts/turns_v1.yaml b/harness/bench/prompts/turns_v1.yamlindex 0401e570..fb7fde5f 100644--- a/harness/bench/prompts/turns_v1.yaml+++ b/harness/bench/prompts/turns_v1.yaml@@ -7,7 +7,7 @@# Run with:# python bench/ab_plan.py --prompts bench/prompts/turns_v1.yaml --out bench/out/turns_v1 \# --pin-plan --variant-env CV3D_FEWER_TURNS=1 \-# --generator api-agent:gemini:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview \+# --generator gemini-cli:gemini-3.6-flash --judge gemini:gemini-3.1-pro-preview \# --rounds 3 --max-minutes 120 --max-in-flight 8 --allow-siblingsname: turns_v1track: static_objectdiff --git a/harness/bench/teaser/build_page.py b/harness/bench/teaser/build_page.pyindex 34c97806..151afcdb 100644--- a/harness/bench/teaser/build_page.py+++ b/harness/bench/teaser/build_page.py@@ -422,7 +422,7 @@ def build() -> str:<pre>pip install -e harnesscd harness3dcv bench run bench/prompts/teaser_v1_static.yaml \\- --generator api-agent:gemini:gemini-3.7-flash+ --generator gemini-cli:gemini-3.6-flash3dcv render <slug> # 8 canonical views3dcv texture pass <slug> # text-to-image material passpython -m http.server -d . 8931 # this page: /docs/teaser.html</pre>diff --git a/harness/bench/teaser/content.py b/harness/bench/teaser/content.pyindex 6d162f42..3fdec497 100644--- a/harness/bench/teaser/content.py+++ b/harness/bench/teaser/content.py@@ -22,7 +22,7 @@ LEAD = dict(STATIC = [dict(id="arcade", title="Arcade cabinet", slug="tsr_tjs_arcade_cabinet",- langs=["three.js"], gen="api-agent:gemini:gemini-3.7-flash", score=0.948, verdict="reads",+ langs=["three.js"], gen="gemini-cli:gemini-3.6-flash", score=0.948, verdict="reads",rounds="1 round", mins="34 min",prompt="an upright 1980s arcade cabinet: a sloped control panel with a ball-top joystick and six ""buttons, a recessed CRT screen behind a bezel, a glowing backlit marquee, a speaker grille, "@@ -36,7 +36,7 @@ STATIC = [media=[("img", "arcade", "hero · low front left"), ("gif", "tt_arcade", "turntable"),("img", "arcade_sheet", "8 canonical views")]),dict(id="lighthouse", title="Coastal lighthouse", slug="tsr_obj_lighthouse",- langs=["Blender · bpy", "text-to-image texture"], gen="api-agent:gemini:gemini-3.7-flash",+ langs=["Blender · bpy", "text-to-image texture"], gen="gemini-cli:gemini-3.6-flash",score=0.7277, verdict="reads", rounds="3 rounds", mins="51 min",prompt="a coastal lighthouse on a rock plinth: a tapered stone tower with painted bands, a corbelled ""gallery with a railing, a glazed lantern room with a fresnel lens and a domed copper roof with "@@ -50,7 +50,7 @@ STATIC = [media=[("img", "lighthouse", "hero · low front left"), ("gif", "tt_lighthouse", "turntable"),("img", "lighthouse_sheet", "8 canonical views")]),dict(id="gramophone", title="Wind-up gramophone", slug="tsr_obj_gramophone",- langs=["Blender · bpy"], gen="api-agent:gemini:gemini-3.7-flash", score=0.75, verdict="reads",+ langs=["Blender · bpy"], gen="gemini-cli:gemini-3.6-flash", score=0.75, verdict="reads",rounds="1 round", mins="48 min",prompt="an antique wind-up gramophone: a big flared brass horn on an elbow, an oak case with a felted ""turntable and a shellac record, a curved tonearm with a sound box, a crank handle on the side "@@ -86,7 +86,7 @@ STATIC = [media=[("img", "radial", "hero · front right ¾"), ("gif", "tt_radial", "turntable"),("img", "radial_sheet", "8 canonical views")]),dict(id="chandelier", title="Art-deco chandelier", slug="tsr_tjs_deco_chandelier_v2",- langs=["three.js"], gen="api-agent:gemini:gemini-3.7-flash", score=0.60, verdict="usable",+ langs=["three.js"], gen="gemini-cli:gemini-3.6-flash", score=0.60, verdict="usable",rounds="4 rounds", mins="86 min", rerun="second attempt",prompt="an art-deco brass chandelier dripping with cut crystal: a stepped brass ceiling canopy and a ""chain drop to a fluted central stem; two tiers of curved brass arms, six above and eight below, "@@ -108,7 +108,7 @@ STATIC = [ARTIC = [dict(id="rollcab", title="Rolling tool chest", slug="tsr_art_roll_cabinet",- langs=["URDF", "Blender · bpy"], gen="api-agent:gemini:gemini-3.7-flash", score=0.957,+ langs=["URDF", "Blender · bpy"], gen="gemini-cli:gemini-3.6-flash", score=0.957,verdict="reads", rounds="1 round", mins="31 min",prompt="a red steel rolling tool chest: seven drawers of three different heights on slides, full-width ""chrome pulls, a hinged top lid over a shallow tray, a push handle on one end and four castors",@@ -125,7 +125,7 @@ ARTIC = [("img", "rollcab_art", "articulation sheet · every joint"),("img", "rollcab_sheet", "8 canonical views")]),dict(id="clock", title="Longcase clock", slug="tsr_art_grandfather_clock_v2",- langs=["URDF", "Blender · bpy"], gen="api-agent:gemini:gemini-3.7-flash", score=0.9469,+ langs=["URDF", "Blender · bpy"], gen="gemini-cli:gemini-3.6-flash", score=0.9469,verdict="reads", rounds="2 rounds", mins="98 min", rerun="second attempt",prompt="a longcase grandfather clock in dark figured walnut with working articulation: a broken-arch ""bonnet with two turned finials over reeded columns, a warm brass dial with a silvered chapter "@@ -151,7 +151,7 @@ ARTIC = [SCENES = [dict(id="alley", title="Neon alley", slug="tsr_scn_neon_alley_v2",- langs=["three.js", "GLSL"], gen="api-agent:gemini:gemini-3.7-flash", score=0.8267,+ langs=["three.js", "GLSL"], gen="gemini-cli:gemini-3.6-flash", score=0.8267,verdict="reads", rounds="5 rounds", mins="75 min", rerun="second attempt",prompt="a rain-soaked neon alley at night, seen down a narrow corridor between two TALL buildings whose ""walls fill the left and right thirds of the frame and rise out of the top of shot. MATERIALS AND "@@ -173,7 +173,7 @@ SCENES = [("alley_sign", "SignDetail · emissive signage")],sheet=("alley_sheet", "all authored cameras, both times")),dict(id="boat", title="Boatbuilder's workshop", slug="tsr_scn_boat_workshop_v2",- langs=["three.js", "GLSL", "Blender · bpy"], gen="api-agent:gemini:gemini-3.7-flash", score=0.747,+ langs=["three.js", "GLSL", "Blender · bpy"], gen="gemini-cli:gemini-3.6-flash", score=0.747,verdict="reads", rounds="4 rounds", mins="81 min", rerun="second attempt", ml=True,prompt="INSIDE a boatbuilder's workshop at dusk — a FULLY ENCLOSED INTERIOR. THE ENCLOSURE IS THE ""ENVIRONMENT AND MUST BE BUILT FIRST: a rectangular timber shed about 16 m x 10 m x 6 m high with "@@ -225,7 +225,7 @@ SCENES = [GFX = [dict(id="aurora", title="Aurora over a ridge", slug="tsr_gfx_aurora_ridge_v3",- langs=["GLSL · fragment shader"], gen="api-agent:gemini:gemini-3.7-flash", score=0.94,+ langs=["GLSL · fragment shader"], gen="gemini-cli:gemini-3.6-flash", score=0.94,verdict="reads", rounds="1 round", mins="14 min", rerun="third attempt",prompt="an aurora over a snowy ridge on a black winter night, painted in three clean horizontal bands. ""TOP TWO THIRDS — the sky: near-black deep-blue, crowded with thousands of small crisp white stars, "@@ -244,7 +244,7 @@ GFX = [media=[("img", "aurora", "t = 2.5 s"), ("gif", "tt_aurora", "animated preview"),("img", "aurora_strip", "frames at 0 / 1 / 2.5 / 4 / 6 s")]),dict(id="murmur", title="Starling murmuration", slug="tsr_ogl_murmuration",- langs=["Python · OpenGL", "GLSL"], gen="api-agent:gemini:gemini-3.7-flash", score=0.865,+ langs=["Python · OpenGL", "GLSL"], gen="gemini-cli:gemini-3.6-flash", score=0.865,verdict="reads", rounds="4 rounds", mins="43 min",prompt="a starling murmuration at dusk: several thousand instanced birds flocking with cohesion, ""separation and alignment around a slowly moving attractor, their dark silhouettes thickening and "@@ -261,7 +261,7 @@ GFX = [media=[("img", "murmur", "t = 1 s"), ("gif", "tt_murmur", "animated preview"),("img", "murmur_strip", "frames at 0 / 1 / 2.5 / 4 / 6 s")]),dict(id="accretion", title="Accretion disc", slug="tsr_gfx_accretion_disc",- langs=["GLSL · fragment shader"], gen="api-agent:gemini:gemini-3.7-flash", score=0.753,+ langs=["GLSL · fragment shader"], gen="gemini-cli:gemini-3.6-flash", score=0.753,verdict="reads", rounds="2 rounds", mins="33 min",prompt="a black hole with a glowing accretion disc: a pure black sphere ringed by a thin bright photon ""ring, a hot orange-white disc of turbulent filaments orbiting it with the approaching side "@@ -278,7 +278,7 @@ GFX = [media=[("img", "accretion", "t = 2.5 s"), ("gif", "tt_accretion", "animated preview"),("img", "accretion_strip", "frames at 0 / 1 / 2.5 / 4 / 6 s")]),dict(id="rain", title="Rain on a window", slug="tsr_gfx_rain_window",- langs=["GLSL · fragment shader"], gen="api-agent:gemini:gemini-3.7-flash", score=0.9087,+ langs=["GLSL · fragment shader"], gen="gemini-cli:gemini-3.6-flash", score=0.9087,verdict="usable", rounds="1 round", mins="7 min",prompt="raindrops running down a dark window in front of an out-of-focus neon city: each drop refracts a ""tiny inverted image of the lights behind it, drops grow until they break loose and cut clean "diff --git a/harness/codeverse/agents/api_agent.py b/harness/codeverse/agents/api_agent.pydeleted file mode 100644index 77b7b396..00000000--- a/harness/codeverse/agents/api_agent.py+++ /dev/null@@ -1,409 +0,0 @@-"""``api-agent:<provider>:<model>`` — in-process agentic loop on any ChatModel.--Tools: workspace-confined file tools (+ policy-filtered ``run_shell``) and every spatial registry tool-(``build``, ``measure``, ``render_views`` ...) as native function calls. The-loop runs until the model stops calling tools or ``job.max_turns``; it writes a-per-turn transcript JSONL, accumulates ``Usage``, compacts old tool results-when the context grows, and applies the *freshness* rule: a model that claims-to be done after editing files without a subsequent ``build`` is nudged once.-"""--from __future__ import annotations--import logging-import time-from typing import Any--from codeverse.agents.api_skills import SkillTools-from codeverse.agents.api_tools import FileTools, SpatialTools, ToolOutcome-from codeverse.agents.cli_common import Session, begin_session, failed, finish_session-from codeverse.agents.context import compact_messages, message_chars-from codeverse.contracts.agent import AgentJob, AgentResult-from codeverse.contracts.chat import (- ChatMessage,- ChatRequest,- ChatResponse,- TextPart,- ToolCallPart,- ToolResultPart,- ToolSpec,-)-from codeverse.contracts.common import Usage-from codeverse.skills.delivery import delivery_for--log = logging.getLogger(__name__)--BUILD_TOOL = "build"-COMPACT_AT_CHARS = 350_000-#: compact once the PROVIDER says the context is this big. The char estimate above is-#: what the harness can see (visible text + tool arguments); it misses the model's own-#: thoughts, which are re-sent as context every turn. Measured 2026-08-27 on one-#: fancy_bl_windsor_chair assemble session: message_chars said 204 732 (threshold-#: 350 000, never tripped) while the provider was actually reading 113 956 tokens —-#: 2.2x more than the estimate. The conversation grew ~1 650 tokens a turn for 60-#: turns, 49 % of it file bodies the model had already written to disk, and every turn-#: re-processed all of it. input_tokens is ground truth, so trigger on that.-COMPACT_AT_INPUT_TOKENS = 60_000-MODEL_RETRIES = 3-#: per-turn output envelope, and how far a TRUNCATED turn may grow it. Measured-#: 2026-08-27 (art_med_tool_chest, 3.6-flash): thinking escalated 13 -> 3 144 -> 15 359-#: tokens as the problem got harder and turn 5 hit the 16 000 default at-#: 15 359 + 637 = 15 996 — the model behaved normally, the envelope was four tokens too-#: small. ``tracks/planner`` has grown its budget on truncation since it hit the same-#: wall (PLAN_TOKENS_MAX / TRUNCATION_GROWTH); the agent loop never did.-TURN_TOKENS = 65_536 # the model's declared ceiling; unused tokens cost nothing-TURN_TOKENS_MAX = 65_536-TURN_TOKENS_GROWTH = 1.5-#: retry budget (``ChatRequest.max_wait_s``) for ONE model call of a turn: the session's-#: remaining time, clipped to this window. Audit 2026-08-26 §5.1: with the model's own-#: 900 s deadline x MODEL_RETRIES one turn could wait 2 700 s, and 66 such give-up spans-#: (median 923 s, p90 2 743 s) were 30 % of a storm day's waiting — ~1 430 s per run. A-#: successful storm-day call is 8.3 s p50 / 31 s p90, so 120 s is ~4x p90; 20 s is the-#: floor so a turn that starts near the deadline still gets one real attempt.-TURN_WAIT_MIN_S = 20.0-TURN_WAIT_MAX_S = 120.0-#: ...but a deadline must also fit the ANSWER the turn asked for, or the tokens are billed-#: and then discarded on a timeout. Measured 2026-08-27: a 15 996-token turn streamed in-#: ~90 s (178 tok/s) and planner calls run 145 tok/s p50 / 60 tok/s p10, so with the-#: envelope at the model's 65 536 ceiling a flat 120 s would cut a long turn off — trading-#: the token wall for a wait wall. The derived wait is bounded by TURN_WAIT_CEILING_S and-#: then by the session deadline, which is itself clipped to the run's wall clock.-TURN_SLOW_TOKENS_PER_S = 145.0-TURN_WAIT_OVERHEAD_S = 45.0-TURN_WAIT_CEILING_S = 900.0-DEFAULT_SYSTEM = (- "You are an expert 3D programmer working inside a harness-managed workspace. "- "Use the tools to read, write and verify code under src/ and public/. Write RAW code in the "- "language the task names; never import from `codeverse` or any helper SDK. Call `build` after "- "every batch of edits and only finish on a clean build. Reply with a short summary when done; "- "never ask questions — decide and proceed."-)-FRESHNESS_NUDGE = (- "You edited files after your last `build`. Run the `build` tool now, read its result, fix any "- "errors, and only then give your final summary."-)-#: A turn that ran out of output tokens mid-thought emits partial text and NO tool call,-#: which is indistinguishable from "I am done" at the loop's `if not resp.tool_calls`.-#: Measured 2026-08-27 (art_med_tool_chest): the baseline spent 15 359 thinking tokens on-#: turn 5, was truncated at MAX_TOKENS, and the session was recorded as completed with-#: zero files written. Thinking is billed either way, so the cure is to ask for the call-#: rather than the reasoning.-TRUNCATED_NUDGE = (- "Your previous turn hit the output limit while thinking, so no tool call arrived. Do not "- "re-derive anything: make the single most useful tool call NOW (write the file you had "- "planned, or `build`), with no analysis before it."-)-#: how many truncated turns in one session get a nudge before it is called a failure-MAX_TRUNCATED_NUDGES = 2---class ApiAgent:- kind = "api-agent"-- def __init__(self, model: str, chat_model: Any | None = None):- self.model = model # '<provider>:<model>'- self._chat_model = chat_model-- @property- def id(self) -> str:- return f"{self.kind}:{self.model}"-- def _chat(self):- if self._chat_model is None:- from codeverse.models import get_chat_model-- self._chat_model = get_chat_model(self.model)- return self._chat_model-- def available(self) -> tuple[bool, str]:- try:- from codeverse.models import parse_model_id-- parse_model_id(self.model)- except Exception as e: # noqa: BLE001 - report, don't raise- return False, str(e)- try:- self._chat()- except Exception as e: # noqa: BLE001- return False, f"chat model unavailable: {e}"- return True, "ok"-- # ------------------------------------------------------------------ run- def run(self, job: AgentJob) -> AgentResult:- s = begin_session(job, self.kind)- try:- chat = self._chat()- except Exception as e: # noqa: BLE001- return failed(s, "error", f"chat model unavailable: {e}")- loop = _Loop(self, s, chat)- return loop.run()---class _Loop:- """One session's state: tools, messages, usage, freshness, compaction."""-- def __init__(self, agent: ApiAgent, s: Session, chat: Any):- self.agent, self.s, self.chat = agent, s, chat- job = s.job- self.files = FileTools(- s.ws,- job.write_roots,- allow_shell=job.api.allow_shell,- edit_only=job.files_hint if job.edit_only else None,- always_writable=job.always_writable,- read_only=job.read_only,- language=job.language,- )- self.spatial: SpatialTools | None = None- if job.spatial_tools:- self.spatial = SpatialTools(- s.ws, track=job.track, language=job.language, round_index=job.round- )- if not self.spatial.tools:- s.notes.append("spatial registry is empty; running with file tools only")- self.spatial = None- # the routed bundles as a TOOL, not as prose: measured, api-agent read 0 of 5 from a- # MANDATORY paragraph in AGENTS.md while the CLI backends read 5 of 5 through their own- # loaders. It responds to tool specs; the bundles also sit in hidden dirs list_files- # skips, so it could not have found them by looking (codeverse/agents/api_skills.py).- # a backend WITHOUT a native loader gets the routed set as a tool; the policy lives- # in skills/delivery.py so a new backend is one row there, not a branch here- self.skills = SkillTools(s.ws) if delivery_for(agent.kind).needs_tool else None- self.specs: list[ToolSpec] = (- self.files.specs()- + (self.skills.specs() if self.skills else [])- + (self.spatial.specs() if self.spatial else [])- )- self.usage = Usage(backend="api-agent", model=agent.model)- self.tool_calls = 0- self.last_write_turn = -1- self.last_build_turn = -1- self.nudged = False- self.truncated = 0- self.turn_tokens = TURN_TOKENS- self.errors: list[str] = []- # the images ride on the first message only: reference photos, and for a refine- # session the contact sheet the judge scored. Until 2026-08-26 no image reached an- # agent session at all — GenerationTask.images fed the single-shot path only, so a- # `--image` reference was seen by the planner and the judge and never by the code- # writer, which had to infer it back from compare_reference's IoU number.- self.messages: list[ChatMessage] = [ChatMessage.user(job.prompt, images=job.images or None)]- self.system = self._system_prompt()- self.max_usd = job.api.max_usd- self.t_deadline = time.monotonic() + job.timeout_s-- def _system_prompt(self) -> str:- agents_md = self.s.ws.root / "AGENTS.md"- base = agents_md.read_text() if agents_md.is_file() else DEFAULT_SYSTEM- if self.s.job.system_append:- base += "\n\n" + self.s.job.system_append- return base-- # ------------------------------------------------------------------ loop- def run(self) -> AgentResult:- job = self.s.job- traj = self.s.traj- traj.append("system", text=self.system[:20000], tools=[t.name for t in self.specs])- ok, reason, text = False, "budget", ""- for turn in range(job.max_turns):- if time.monotonic() > self.t_deadline:- reason, self.errors = (- "timeout",- self.errors + [f"wall clock exceeded {job.timeout_s}s"],- )- break- resp = self._generate(turn)- if resp is None:- reason = "error"- break- text = resp.text- self.messages.append(_assistant_message(resp))- traj.append(- "assistant",- turn=turn,- text=resp.text[:20000],- tool_calls=[- {"id": c.id, "name": c.name, "arguments": c.arguments} for c in resp.tool_calls- ],- usage=resp.usage.model_dump(),- finish_reason=resp.finish_reason,- )- if not resp.tool_calls:- if resp.finish_reason == "MAX_TOKENS" and self.truncated < MAX_TRUNCATED_NUDGES:- # cut off mid-thought, not finished: widen the envelope AND ask for the- # call rather than more reasoning (thinking is billed either way)- self.truncated += 1- self.turn_tokens = min(TURN_TOKENS_MAX, int(self.turn_tokens * TURN_TOKENS_GROWTH))- self.messages.append(ChatMessage.user(TRUNCATED_NUDGE))- traj.append("nudge", turn=turn, text=TRUNCATED_NUDGE, reason="max_tokens")- continue- if resp.finish_reason == "MAX_TOKENS":- ok, reason = False, "truncated"- self.errors.append(- f"{self.truncated + 1} turns ran out of output tokens while thinking and "- "never emitted a tool call")- break- if self._needs_build_nudge():- self.nudged = True- self.messages.append(ChatMessage.user(FRESHNESS_NUDGE))- traj.append("nudge", turn=turn, text=FRESHNESS_NUDGE)- continue- ok, reason = True, "completed"- break- self._execute(turn, resp.tool_calls)- if self.max_usd and self.usage.cost_usd > self.max_usd:- reason, self.errors = (- "budget",- self.errors + [f"cost {self.usage.cost_usd:.3f} > max_usd {self.max_usd}"],- )- break- seen = int(getattr(resp.usage, "input_tokens", 0) or 0)- if seen > COMPACT_AT_INPUT_TOKENS or message_chars(self.messages) > COMPACT_AT_CHARS:- self.messages = compact_messages(self.messages, keep_recent=6, facts=self._facts())- traj.append("compact", turn=turn, chars=message_chars(self.messages),- input_tokens_seen=seen)- else:- self.errors.append(f"max_turns ({job.max_turns}) reached")- return finish_session(- self.s,- ok=ok,- exit_reason=reason,- text=text,- usage=self.usage,- tool_calls=self.tool_calls,- errors=self.errors,- turns=len(self.messages),- nudged=self.nudged,- tools=[t.name for t in self.specs],- )-- def _turn_wait_s(self) -> float:- """Retry budget for one model call of this turn: enough for the answer it asked- for, never past what the session can still afford."""- want = max(TURN_WAIT_MAX_S,- min(TURN_WAIT_CEILING_S,- self.turn_tokens / TURN_SLOW_TOKENS_PER_S + TURN_WAIT_OVERHEAD_S))- return max(TURN_WAIT_MIN_S, min(want, self.t_deadline - time.monotonic()))-- def _generate(self, turn: int) -> ChatResponse | None:- req = ChatRequest(- messages=self.messages,- system=self.system,- tools=self.specs,- temperature=self.s.job.api.temperature,- thinking=self.s.job.api.thinking,- label=f"api-agent:{self.s.label}:t{turn}",- max_output_tokens=self.turn_tokens,- max_wait_s=self._turn_wait_s(),- )- delay = 2.0- for attempt in range(MODEL_RETRIES):- if attempt: # a retry gets what is left, not the turn's opening budget again- req = req.model_copy(update={"max_wait_s": self._turn_wait_s()})- try:- resp = self.chat.generate(req)- self.usage = self.usage + resp.usage- return resp- except Exception as e: # ModelError or provider glitch- self.usage = self.usage + (getattr(e, "usage", None) or Usage()) # billed anyway- retryable = bool(getattr(e, "retryable", False))- # the session deadline used to be checked only between turns, so a turn that- # met it inside this loop still slept and re-entered the model's whole- # retry machine (97 sessions overshot their timeout on 2026-08-26)- expired = time.monotonic() >= self.t_deadline- self.s.traj.append(- "model_error",- turn=turn,- attempt=attempt,- error=str(e)[:2000],- retryable=retryable,- deadline_passed=expired,- )- if not retryable or expired or attempt == MODEL_RETRIES - 1:- note = " (session deadline passed; not retried)" if expired and retryable else ""- self.errors.append(f"model error on turn {turn}: {type(e).__name__}: {e}{note}")- return None- time.sleep(delay)- delay *= 2- return None-- # ------------------------------------------------------------------ tools- def _execute(self, turn: int, calls: list[ToolCallPart]) -> None:- parts: list[ToolResultPart] = []- for call in calls:- self.tool_calls += 1- out = self._dispatch(call.name, dict(call.arguments or {}))- if call.name in ("write_file", "edit_file") and not out.is_error:- self.last_write_turn = turn- if call.name == "read_file" and not out.is_error:- # signal 3 of the read probe: api-agent is the only backend where we own- # the read tool, so it is the calibration arm for the atime probe.- from codeverse.skills.telemetry import record_exact_read-- record_exact_read(- self.s.ws.root,- str((call.arguments or {}).get("path", "")),- turn=turn,- label=getattr(self.s, "label", "") or "",- )- if call.name in (BUILD_TOOL, "run_build"):- self.last_build_turn = turn- parts.append(- ToolResultPart(- call_id=call.id,- name=call.name,- content=out.text,- images=out.images,- is_error=out.is_error,- )- )- self.s.traj.append(- "tool_result",- turn=turn,- name=call.name,- call_id=call.id,- ok=not out.is_error,- content=out.text[:8000],- images=[i.path for i in out.images],- numbers=out.numbers,- )- self.messages.append(ChatMessage(role="tool", parts=parts))-- def _dispatch(self, name: str, args: dict[str, Any]) -> ToolOutcome:- if name == "run_build" and self.spatial and BUILD_TOOL in self.spatial.names():- name = BUILD_TOOL- if self.skills and (out := self.skills.dispatch(name, args)) is not None:- return out- if name in self.files.names():- return self.files.call(name, args)- if self.spatial and name in self.spatial.names():- return self.spatial.call(name, args)- return ToolOutcome(- f"unknown tool {name!r}; available: {sorted(t.name for t in self.specs)}", is_error=True- )-- def _needs_build_nudge(self) -> bool:- has_build = bool(self.spatial and BUILD_TOOL in self.spatial.names())- return has_build and not self.nudged and self.last_write_turn > self.last_build_turn-- def _facts(self) -> str:- writes = list(dict.fromkeys(self.files.writes))- lines = [- f"- tool calls so far: {self.tool_calls}",- f"- files written/edited (in order): {', '.join(writes) if writes else 'none'}",- f"- last build turn: {self.last_build_turn} (last write turn: {self.last_write_turn})",- ]- return "\n".join(lines)---def _assistant_message(resp: ChatResponse) -> ChatMessage:- parts: list[Any] = []- if resp.text:- parts.append(TextPart(text=resp.text))- parts.extend(resp.tool_calls)- if not parts:- parts.append(TextPart(text=""))- return ChatMessage(role="assistant", parts=parts)---__all__ = ["ApiAgent", "DEFAULT_SYSTEM", "FRESHNESS_NUDGE"]diff --git a/harness/codeverse/agents/api_skills.py b/harness/codeverse/agents/api_skills.pydeleted file mode 100644index 7e541611..00000000--- a/harness/codeverse/agents/api_skills.py+++ /dev/null@@ -1,159 +0,0 @@-"""``read_skill`` — the routed skill bundles as a TOOL, for the in-process api-agent.--WHY a tool and not prose. Every CLI backend has a native skill loader, and measured on a-real build task codex, claude-code and agy each read **5 of 5** routed bundles unprompted.-api-agent read **0 of 5** on the same library, in the same workspace, while making 52-``read_file`` calls — so it was reading plenty, just never a skill. Two reasons it could-not, both structural rather than a matter of persuasion:--* the bundles live in ``.agents/skills/`` and ``.claude/skills/``, which are HIDDEN- directories, and ``list_files`` deliberately skips hidden paths — the agent cannot- discover them by looking;-* everything else it knew came from tool specs, while the skills were a paragraph in a- 2.3 kB system prompt competing with the contract, the rules and the cookbook pointer.--So the index becomes an affordance: the routed names are in the tool's own description,-where the model reads its options, and opening one is a tool call like any other. The-AGENTS.md index stays as well — belt and braces, and it is what a native loader reads.-"""--from __future__ import annotations--import os-from pathlib import Path-from typing import Any--from codeverse.agents.api_tools import ToolOutcome, _schema-from codeverse.contracts.chat import ToolSpec--#: every discovery root the library writes to; first match wins (the same bytes go to all-#: of them, so a loaderless backend can read whichever exists)-from codeverse.skills.delivery import AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT-from codeverse.workspace import Workspace--SKILL_ROOTS = (AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT)-#: a body is capped like read_file's — a skill that cannot fit is a skill to split-READ_CAP_CHARS = 24_000-#: how much of each description the tool spec repeats, per skill-SPEC_SUMMARY_CHARS = 150--__all__ = ["SKILL_ROOTS", "SkillTools"]---class SkillTools:- """``read_skill`` over the bundles already materialised into ``ws``."""-- def __init__(self, ws: Workspace):- self.ws = ws- self.listed, self.summaries = self._discover()- self.reads: list[str] = [] # names actually opened, in order — the read-rate ground truth-- def _discover(self) -> tuple[list[str], dict[str, str]]:- """Read the routed set off the workspace rather than being told it.-- The bundles are already there — materialize.py wrote them for this round — so- discovering them here keeps the tool from ever disagreeing with what is on disk,- and needs no field threaded through AgentJob and the generation task. The read- CONTROL bundle is excluded: it exists to catch a probe that reports a read nobody- made, and offering it as a choice would be inviting exactly that.- """- from codeverse.skills.materialize import CONTROL_NAME-- names: dict[str, str] = {}- for root in SKILL_ROOTS:- d = Path(self.ws.root) / root- if not d.is_dir():- continue- for bundle in sorted(d.iterdir()):- name = bundle.name- if name == CONTROL_NAME or name in names or not (bundle / "SKILL.md").is_file():- continue- names[name] = _description_of(bundle / "SKILL.md")- return list(names), names-- # ------------------------------------------------------------------ specs- def specs(self) -> list[ToolSpec]:- if not self.listed:- return []- lines = [f" - {n}: {self.summaries.get(n, '')[:SPEC_SUMMARY_CHARS]}".rstrip(": ") for n in self.listed]- desc = (- "Read one of the skill bundles the harness routed for THIS task — chosen from your "- "track, language, plan and the previous round's gate findings. Read every one before "- "writing code; they carry the rules this harness's gates actually enforce.\n"- + "\n".join(lines)- )- return [ToolSpec(- name="read_skill", description=desc,- parameters=_schema({"name": {"type": "string", "description": "skill name, exactly as listed",- "enum": list(self.listed)}}, ["name"]),- )]-- # ------------------------------------------------------------------ tool- def read_skill(self, name: str) -> ToolOutcome:- if not isinstance(name, str) or not name.strip():- return ToolOutcome("name must be one of: " + ", ".join(self.listed), is_error=True)- name = name.strip()- if name not in self.listed:- return ToolOutcome(f"{name!r} was not routed for this task; available: {', '.join(self.listed)}",- is_error=True)- body = self._body(name)- if body is None:- return ToolOutcome(f"skill {name!r} is listed but its SKILL.md is missing from the workspace",- is_error=True)- self.reads.append(name)- return ToolOutcome(body)-- def dispatch(self, name: str, args: dict[str, Any]) -> ToolOutcome | None:- """``None`` when this toolbox does not own ``name`` (the caller keeps looking)."""- if name != "read_skill":- return None- return self.read_skill(str(args.get("name", "")))-- # ------------------------------------------------------------------ internals- def _body(self, name: str) -> str | None:- for root in SKILL_ROOTS:- p = Path(self.ws.root) / root / name / "SKILL.md"- if p.is_file():- text = p.read_text(errors="replace")- extra = self._references(p.parent)- if extra:- text += "\n\n" + extra- return text[:READ_CAP_CHARS] + (- f"\n... [truncated at {READ_CAP_CHARS} chars]" if len(text) > READ_CAP_CHARS else "")- return None-- @staticmethod- def _references(bundle: Path) -> str:- """The spec puts depth in ``references/``; name them so a body is not a dead end."""- ref = bundle / "references"- if not ref.is_dir():- return ""- names = sorted(p.name for p in ref.iterdir() if p.is_file())- if not names:- return ""- rel = os.path.relpath(ref, bundle.parents[2]) if len(bundle.parents) > 2 else str(ref)- return "Further reading in this bundle (open with read_file):\n" + "\n".join(- f" {rel}/{n}" for n in names)---def _description_of(skill_md: Path) -> str:- """The frontmatter ``description``, without importing the loader (which validates the- whole bundle and would turn one malformed skill into a session with no tool at all)."""- try:- text = skill_md.read_text(errors="replace")- except OSError:- return ""- if not text.startswith("---"):- return ""- end = text.find("\n---", 3)- front = text[3:end] if end > 0 else ""- out, grabbing = [], False- for line in front.splitlines():- if line.startswith("description:"):- out.append(line.split(":", 1)[1].strip())- grabbing = True- elif grabbing and line[:1] in (" ", "\t"):- out.append(line.strip())- elif grabbing:- break- return " ".join(out).strip().strip("'\"")diff --git a/harness/codeverse/agents/api_tools.py b/harness/codeverse/agents/api_tools.pydeleted file mode 100644index f2349bbc..00000000--- a/harness/codeverse/agents/api_tools.py+++ /dev/null@@ -1,507 +0,0 @@-"""Tool set for the in-process ``api-agent``: workspace-confined file tools + shell + spatial registry.--Every tool returns a :class:`ToolOutcome` (text, images, is_error) and never-raises. Paths are resolved inside the workspace; writes are restricted to-``write_roots``. ``run_shell`` is a *policy filter*, not an OS sandbox: only an-allow-listed program, no shell operators, no inline-code flags (``python -c``,-``node -e`` …, ``-m`` only for a few stdlib modules), every path-like argument-must resolve inside the workspace, and the child runs under the watchdog with a-minimal environment (no host secrets). Trust model = cooperative agent — the-harness executes the agent's own source files anyway (same as the CLI backends).-"""--from __future__ import annotations--import fnmatch-import json-import os-import shlex-from collections.abc import Collection-from dataclasses import dataclass, field-from pathlib import Path-from typing import Any--from codeverse.agents.watchdog import run_with_watchdog-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-SHELL_OUT_CAP = 6_000-SHELL_TIMEOUT_S = 180.0-SHELL_ALLOW = (- "node",- "python",- "python3",- "ls",- "cat",- "head",- "tail",- "wc",- "grep",- "find",- "stat",-)-_SHELL_OPERATORS = {"|", "&&", "||", ";", ">", ">>", "<", "2>", "&"}-#: python/node short options that run inline code / a REPL (``-c CODE``, ``-e CODE``, ``-p``, ``-i``)-#: or load code by path we cannot vet (``-r``); combined forms (``-Bc``, ``-pe``) are caught per letter.-_INLINE_SHORT = {"python": set("cim"), "python3": set("cim"), "node": set("epir")}-_INLINE_LONG = (- "--eval",- "--print",- "--interactive",- "--input-type",- "--require",- "--import",- "--loader",- "--experimental-loader",- "--experimental-default-type",-)-#: ``python -m <module>`` is allowed only for these stdlib modules (syntax / JSON checks)-PY_MODULE_ALLOW = ("py_compile", "compileall", "json.tool", "ast", "tokenize")-_FIND_DENY = (- "-exec",- "-execdir",- "-ok",- "-okdir",- "-delete",- "-fprint",- "-fprintf",- "-fls",- "-fprint0",-)-_SKIP_GLOB_DIRS = (".git", "node_modules", "__pycache__", "trajectories")---@dataclass-class ToolOutcome:- text: str- images: list[ImagePart] = field(default_factory=list)- is_error: bool = False- numbers: dict[str, Any] = field(default_factory=dict)---class PathDenied(ValueError):- pass---def _schema(props: dict[str, dict[str, Any]], required: list[str]) -> dict[str, Any]:- return {"type": "object", "properties": props, "required": required}---class FileTools:- """read_file / write_file / edit_file / list_files / run_shell inside one workspace."""-- def __init__(- self,- ws: Workspace,- write_roots: list[str],- *,- allow_shell: bool = True,- edit_only: Collection[str] | None = None,- always_writable: Collection[str] = (),- read_only: 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.- #:- #: Why a hard rule and not the prose the prompt already carries ("keep everything else- #: as it is"): measured 2026-08-25 over 128 judged refine rounds on static objects, the- #: rounds that REGRESSED the score had rewritten a median 6 of 9 part files against 4- #: of 8 for the rounds that improved — and their worst-dropping criterion was- #: structure_plausibility with zero gate errors, i.e. working geometry the task never- #: named was replaced and nothing deterministic could see it. The prompt was already- #: asking for scope; only the tool can hold it.- self.edit_only = (- frozenset((ws.root / f).resolve() for f in edit_only) if edit_only is not None else None- )- self.always_writable = frozenset((ws.root / f).resolve() for f in always_writable)- #: harness-owned files inside the write roots (``src/recipes.glsl``): readable, never- #: writable — measured 2026-08-26 (bench/out/seed_v1), recipes seeded into the agent's own- #: common.glsl were overwritten by the end of the run; a file the agent can rewrite is not- #: a place to keep verified code.- self.read_only = frozenset((ws.root / f).resolve() for f in read_only)- self.scope_denials: list[str] = []- self.read_only_denials: list[str] = []- self.allow_shell = allow_shell- self.writes: list[str] = [] # workspace-relative paths written/edited, in order-- # ------------------------------------------------------------------ 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 §29)- 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",- description="Read a text file in the workspace (path relative to the workspace root).",- parameters=_schema(- {"path": {"type": "string", "description": "workspace-relative path"}}, ["path"]- ),- ),- ToolSpec(- name="write_file",- 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.{no_readback}",- parameters=_schema(- {- "path": {"type": "string"},- "old": {"type": "string"},- "new": {"type": "string"},- "all": {- "type": "boolean",- "description": "replace every occurrence",- "default": False,- },- },- ["path", "old", "new"],- ),- ),- ToolSpec(- name="list_files",- description="List workspace files matching a glob (default '**/*' under src/). Hidden/git/node_modules skipped.",- parameters=_schema(- {- "glob": {- "type": "string",- "description": "e.g. 'src/**/*.js'",- "default": "src/**/*",- }- },- [],- ),- ),- ]- if self.allow_shell:- specs.append(- ToolSpec(- name="run_shell",- description=f"Run ONE command in the workspace root (no pipes/redirects/network). Allowed programs: {', '.join(SHELL_ALLOW)}. "- "Use it to syntax-check (`node --check src/x.js`, `python -m py_compile src/model.py`) or inspect files. "- "Inline code (`python -c`, `node -e`) and paths outside the workspace are rejected.",- parameters=_schema(- {- "cmd": {- "type": "string",- "description": "the command line, e.g. 'node --check src/object.js'",- },- "timeout_s": {"type": "integer", "default": 60},- },- ["cmd"],- ),- )- )- return specs-- def names(self) -> set[str]:- return {s.name for s in self.specs()}-- # ------------------------------------------------------------------ dispatch- def call(self, name: str, args: dict[str, Any]) -> ToolOutcome:- fn = {- "read_file": self.read_file,- "write_file": self.write_file,- "edit_file": self.edit_file,- "list_files": self.list_files,- "run_shell": self.run_shell,- }.get(name)- if fn is None or (name == "run_shell" and not self.allow_shell):- return ToolOutcome(f"unknown tool {name!r}", is_error=True)- try:- return fn(**args)- except TypeError as e:- return ToolOutcome(f"{name}: bad arguments: {e}", is_error=True)- except PathDenied as e:- return ToolOutcome(f"{name}: {e}", is_error=True)- except (OSError, ValueError) as e: # ValueError covers UnicodeDecodeError / bad numbers- return ToolOutcome(f"{name}: {type(e).__name__}: {e}", is_error=True)- except Exception as e: # noqa: BLE001 — tools never raise into the agent loop- return ToolOutcome(f"{name}: {type(e).__name__}: {e}", is_error=True)-- # ------------------------------------------------------------------ paths- def _resolve(self, path: str, *, write: bool) -> Path:- if not isinstance(path, str) or not path.strip():- raise PathDenied("path must be a non-empty workspace-relative string")- p = Path(path)- p = (self.ws.root / p).resolve() if not p.is_absolute() else p.resolve()- root = self.ws.root.resolve()- if p != root and root not in p.parents:- raise PathDenied(f"path escapes the workspace: {path}")- if ".git" in p.relative_to(root).parts:- raise PathDenied("the .git directory is off limits")- if write and not any(p == r or r in p.parents for r in self.write_roots):- roots = ", ".join(os.path.relpath(r, root) + "/" for r in self.write_roots)- raise PathDenied(f"writes are only allowed under {roots} (got {path})")- if write and p in self.read_only:- rel = os.path.relpath(p, root)- self.read_only_denials.append(rel)- raise PathDenied(- f"{rel} is harness-owned and read-only: the harness wrote it and pastes it above your "- f"code at build time, so its functions are already in scope — call them from your own "- f"files instead of editing, redefining or copying them (read_file on it still works)."- )- if (- write- and self.edit_only is not None- and p.exists()- and p not in self.edit_only- and p not in self.always_writable- ):- rel = os.path.relpath(p, root)- self.scope_denials.append(rel)- allowed = (- ", ".join(sorted(os.path.relpath(f, root) for f in self.edit_only)) or "(none)"- )- raise PathDenied(- f"{rel} is outside this task's scope and already exists — it is another part's file "- f"and this round did not ask for changes to it. You may edit: {allowed}; you may also "- f"create NEW files and edit the entry file. If the fix genuinely needs {rel}, say so "- f"in your final summary instead of editing it."- )- return p-- # ------------------------------------------------------------------ tools- def read_file(self, path: str) -> ToolOutcome:- p = self._resolve(path, write=False)- if not p.is_file():- return ToolOutcome(f"no such file: {path}", is_error=True)- text = p.read_text(errors="replace")- if len(text) > READ_CAP_CHARS:- text = text[:READ_CAP_CHARS] + f"\n... [truncated; file has {len(text)} chars]"- return ToolOutcome(text)-- def write_file(self, path: str, content: str) -> ToolOutcome:- p = self._resolve(path, write=True)- p.parent.mkdir(parents=True, exist_ok=True)- existed = p.exists()- 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"{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():- return ToolOutcome(f"no such file: {path} (use write_file to create it)", is_error=True)- try:- text = p.read_text(encoding="utf-8")- except UnicodeDecodeError:- return ToolOutcome(- f"{path} is not UTF-8 text; edit_file only works on text files (use write_file to replace it)",- is_error=True,- )- n = text.count(old)- if not old:- return ToolOutcome(- "`old` must be non-empty; read the file and quote the exact text to replace",- is_error=True,- )- if n == 0:- return ToolOutcome(- f"`old` not found in {path}; read_file it and copy the exact text", is_error=True- )- if n > 1 and not all:- return ToolOutcome(- f"`old` occurs {n} times in {path}; include more context or pass all=true",- is_error=True,- )- 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)- 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- out = []- for p in sorted(root.rglob("*")):- if not p.is_file():- continue- rel = p.relative_to(root).as_posix()- if any(- part in _SKIP_GLOB_DIRS or part.startswith(".") for part in Path(rel).parts[:-1]- ):- continue- if fnmatch.fnmatch(rel, glob) or fnmatch.fnmatch(rel, glob.replace("**/", "")):- out.append(f"{rel} ({p.stat().st_size} B)")- if len(out) >= 300:- out.append("... (truncated at 300)")- break- return ToolOutcome("\n".join(out) if out else f"no files match {glob!r}")-- # ------------------------------------------------------------------ shell policy- def _arg_escapes(self, a: str) -> bool:- """True when ``a`` (a path-like argument) resolves outside the workspace or into .git."""- root = self.ws.root.resolve()- cand = Path(os.path.realpath(os.path.join(root, os.path.expanduser(a))))- if cand != root and root not in cand.parents:- return True- return cand != root and ".git" in cand.relative_to(root).parts-- def _shell_policy_error(self, argv: list[str]) -> str | None:- """Why ``argv`` is refused (None = allowed). See the module docstring."""- if not argv or os.path.basename(argv[0]) not in SHELL_ALLOW:- return f"program {argv[0] if argv else ''!r} not allowed; use one of {SHELL_ALLOW}"- prog = os.path.basename(argv[0])- inline = _INLINE_SHORT.get(prog, set())- rest = argv[1:]- for i, a in enumerate(rest):- if a == "-" or (prog == "find" and a in _FIND_DENY):- return f"{a!r} is not allowed (stdin scripts / find actions are disabled)"- if a.startswith("--"):- opt, _, val = a.partition("=")- if opt in _INLINE_LONG:- return f"{opt} is not allowed: inline code / custom loaders are disabled; put code in a file under src/"- if val and self._arg_escapes(val):- return f"paths outside the workspace are not allowed: {val}"- continue- if a.startswith("-") and len(a) > 1:- letters = a[1:]- if prog.startswith("python") and "m" in letters:- pre, _, module = letters.partition("m") # -Bm mod / -mmod; -cm is `-c "m"`- if set(pre) & inline:- return f"{a} is not allowed: inline code / REPL flags are disabled; put code in a file under src/"- module = module or (rest[i + 1] if i + 1 < len(rest) else "")- if module not in PY_MODULE_ALLOW:- return f"python -m {module!r} is not allowed; allowed modules: {PY_MODULE_ALLOW}"- continue- if set(letters) & inline:- return f"{a} is not allowed: inline code / REPL flags are disabled; put code in a file under src/"- continue- if self._arg_escapes(a):- return f"paths outside the workspace are not allowed: {a}"- return None-- def run_shell(self, cmd: str, timeout_s: int | float | str = 60) -> ToolOutcome:- try:- argv = shlex.split(cmd)- except ValueError as e:- return ToolOutcome(f"cannot parse command: {e}", is_error=True)- if any(- tok in _SHELL_OPERATORS for tok in argv- ): # no shell is involved; this is just a clear message- return ToolOutcome(- "shell operators (| && ; > <) are not allowed; run ONE plain command", is_error=True- )- why = self._shell_policy_error(argv)- if why:- return ToolOutcome(why, is_error=True)- env = {- "PATH": os.environ.get("PATH", "/usr/bin:/bin"),- "HOME": str(self.ws.root),- "LANG": "C.UTF-8",- "NODE_PATH": str(get_settings().runtime_js_dir() / "node_modules"),- "PYTHONDONTWRITEBYTECODE": "1",- "NO_PROXY": "*",- "no_proxy": "*",- }- t = float(max(5, min(_as_int(timeout_s, 60), int(SHELL_TIMEOUT_S))))- proc = run_with_watchdog(- argv,- cwd=self.ws.root,- env=env,- soft_timeout_s=t,- idle_grace_s=5,- hard_timeout_s=t + 5,- activity_dirs=[],- poll_s=0.2,- )- body = f"$ {cmd}\nrc={proc.rc}" + (" (killed: timeout)" if proc.timed_out else "")- if proc.stdout.strip():- body += "\n--- stdout ---\n" + _cap(proc.stdout)- if proc.stderr.strip():- body += "\n--- stderr ---\n" + _cap(proc.stderr)- return ToolOutcome(body, is_error=proc.rc != 0)---def _as_int(value: Any, default: int) -> int:- """Lenient int coercion for model-supplied numbers ('60', 60.5, 'soon' → default)."""- try:- return int(float(value))- except (TypeError, ValueError):- return default---def _cap(text: str, n: int = SHELL_OUT_CAP) -> str:- if len(text) <= n:- return text- head, tail_ = n // 4, n - n // 4- return text[:head] + f"\n... [{len(text) - n} chars omitted] ...\n" + text[-tail_:]---class SpatialTools:- """Bridge from the ``codeverse.spatial.registry`` to native tool calls."""-- def __init__(self, ws: Workspace, *, track: str = "", language: str = "", round_index: int = 0):- from codeverse.spatial.registry import ToolContext, list_tools-- self.ctx = ToolContext(- workspace=ws, round_index=round_index, language=language, track=track- )- self.tools = {t.name: t for t in list_tools(track=track, language=language)}-- def specs(self) -> list[ToolSpec]:- return [- ToolSpec(name=t.name, description=t.describe(), parameters=t.schema())- for t in self.tools.values()- ]-- def names(self) -> set[str]:- return set(self.tools)-- def call(self, name: str, args: dict[str, Any]) -> ToolOutcome:- t = self.tools.get(name)- if t is None:- return ToolOutcome(f"unknown spatial tool {name!r}", is_error=True)- obs = t.call(self.ctx, args)- text = obs.text- if obs.numbers:- text += "\n\nnumbers: " + json.dumps(obs.numbers, default=str)[:4000]- images = [ImagePart(path=p, label=Path(p).stem) for p in obs.images if Path(p).is_file()]- return ToolOutcome(text, images=images, is_error=not obs.ok, numbers=obs.numbers)---__all__ = [- "FileTools",- "SpatialTools",- "ToolOutcome",- "PathDenied",- "SHELL_ALLOW",- "PY_MODULE_ALLOW",-]diff --git a/harness/codeverse/agents/context.py b/harness/codeverse/agents/context.pydeleted file mode 100644index a67b19fb..00000000--- a/harness/codeverse/agents/context.py+++ /dev/null@@ -1,92 +0,0 @@-"""Deterministic context compaction for the api-agent loop (no LLM involved).--Old tool-result bodies are trimmed to a stub, old images are dropped, and a-"facts so far" note is inserted after the first user message so the model keeps-the task + a running summary while the transcript on disk stays complete.-"""--from __future__ import annotations--from codeverse.contracts.chat import ChatMessage, ImagePart, TextPart, ToolCallPart, ToolResultPart--STUB_CHARS = 240-FACTS_TAG = "<facts_so_far>"-#: tool-call arguments whose payload is a file body: once written, the file is on disk-#: and ``read_file`` can fetch it, so keeping the text in the conversation buys nothing-#: and is re-processed on every later turn. Measured 2026-08-27 on one assemble-#: session: 29 write_file calls were 49 % of the whole conversation.-BODY_ARG_TOOLS = frozenset({"write_file", "edit_file"})-BODY_ARG_KEYS = ("content", "new", "old", "text")---def message_chars(messages: list[ChatMessage]) -> int:- """Rough context size: text chars + a flat 4k per image."""- n = 0- for m in messages:- for p in m.parts:- if isinstance(p, TextPart):- n += len(p.text)- elif isinstance(p, ToolResultPart):- n += len(p.content) + 4000 * len(p.images)- elif isinstance(p, ImagePart):- n += 4000- else: # tool call- n += len(str(getattr(p, "arguments", "")))- return n---def _stub(content: str) -> str:- if len(content) <= STUB_CHARS:- return content- return content[:STUB_CHARS] + f" … [compacted; {len(content)} chars originally]"---def _stub_written_bodies(m: ChatMessage) -> ChatMessage:- """Shorten the file bodies carried in this message's write/edit tool CALLS."""- if not any(isinstance(p, ToolCallPart) and p.name in BODY_ARG_TOOLS for p in m.parts):- return m- parts: list[object] = []- for p in m.parts:- if isinstance(p, ToolCallPart) and p.name in BODY_ARG_TOOLS:- args = dict(p.arguments or {})- for k in BODY_ARG_KEYS:- if isinstance(args.get(k), str):- args[k] = _stub(args[k])- parts.append(ToolCallPart(id=p.id, name=p.name, arguments=args))- else:- parts.append(p)- return ChatMessage(role=m.role, parts=parts) # type: ignore[arg-type]---def compact_messages(messages: list[ChatMessage], *, keep_recent: int = 8, facts: str = "") -> list[ChatMessage]:- """Return a new message list with old bodies stubbed and a facts note.-- The first message (the task) and the last ``keep_recent`` messages are kept- verbatim; everything in between has tool-result bodies shortened, images removed,- and the file bodies inside old ``write_file``/``edit_file`` CALLS stubbed — the- file is on disk, so re-sending its text every turn buys nothing. Any earlier- facts note is replaced.- """- if len(messages) <= keep_recent + 1:- return list(messages)- head, middle, tail = messages[0], messages[1:-keep_recent], messages[-keep_recent:]- out: list[ChatMessage] = [head]- if facts:- out.append(ChatMessage.user(f"{FACTS_TAG}\n{facts}\n</facts_so_far>"))- for m in middle:- if m.role == "user" and m.text.startswith(FACTS_TAG):- continue # superseded- if m.role != "tool":- out.append(_stub_written_bodies(m))- continue- parts = [- ToolResultPart(call_id=p.call_id, name=p.name, content=_stub(p.content), images=[], is_error=p.is_error)- if isinstance(p, ToolResultPart) else p- for p in m.parts- ]- out.append(ChatMessage(role="tool", parts=parts))- out.extend(tail)- return out---__all__ = ["compact_messages", "message_chars", "FACTS_TAG", "BODY_ARG_TOOLS"]diff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.pyindex 4e1b7dd0..4d2c2702 100644--- a/harness/codeverse/agents/materialize.py+++ b/harness/codeverse/agents/materialize.py@@ -90,8 +90,6 @@ def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str])"`python -m codeverse.cli.main tools <name> --json '{\"arg\": \"value\"}'` ""(run from the workspace root; prints the observation as text + JSON).")- elif agent_kind == "api-agent":- how = "Tools are native function calls with exactly the names below."elif agent_kind == "gemini-cli":how = (f"Tools are exposed by the MCP server `{MCP_SERVER_NAME}`; they appear in your tool list as "diff --git a/harness/codeverse/agents/registry.py b/harness/codeverse/agents/registry.pyindex 53d2097e..29c7ae6d 100644--- a/harness/codeverse/agents/registry.py+++ b/harness/codeverse/agents/registry.py@@ -6,11 +6,11 @@ from functools import lru_cachefrom codeverse.agents.base import CodingAgent-KINDS = ("gemini-cli", "claude-code", "codex", "agy", "api-agent")+KINDS = ("gemini-cli", "claude-code", "codex", "agy")def parse_agent_id(agent_id: str) -> tuple[str, str]:- """``api-agent:gemini:gemini-3.7-flash`` → ('api-agent', 'gemini:gemini-3.7-flash')."""+ """``gemini-cli:gemini-3.6-flash`` → ('gemini-cli', 'gemini-3.6-flash')."""if ":" not in agent_id:raise ValueError(f"agent id must be '<kind>:<model>', got {agent_id!r}")kind, model = agent_id.split(":", 1)@@ -38,6 +38,4 @@ def get_coding_agent(agent_id: str) -> CodingAgent:from codeverse.agents.antigravity import AntigravityAgentreturn AntigravityAgent(model)- from codeverse.agents.api_agent import ApiAgent-- return ApiAgent(model)+ raise ValueError(f"unknown agent kind {kind!r}; known: {KINDS}")diff --git a/harness/codeverse/cli/skills_cmd.py b/harness/codeverse/cli/skills_cmd.pyindex e41527f9..1e3f6f97 100644--- a/harness/codeverse/cli/skills_cmd.py+++ b/harness/codeverse/cli/skills_cmd.py@@ -164,7 +164,7 @@ def report(t.add_column(col)for (name, backend), (listed, surfaced, deep) in sorted(per.items()):rate = deep / listed if listed else 0.0- target = 0.80 if backend == "api-agent" else 0.60+ target = 0.60verdict = "delete/merge" if (listed >= 20 and rate < 0.20) else ("ok" if rate >= target else "below target")t.add_row(name, backend, str(listed), str(surfaced), str(deep), f"{rate:.0%}", verdict)console.print(t)diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.pyindex c4ffb9a3..fe2a00f9 100644--- a/harness/codeverse/contracts/common.py+++ b/harness/codeverse/contracts/common.py@@ -151,11 +151,15 @@ class Backends(BaseModel):· ``openai:gpt-5.6-sol``* Coding agents: ``gemini-cli:gemini-3.7-flash`` · ``claude-code:sonnet``· ``codex:gpt-5.6-sol`` · ``agy:gemini-3.6-flash-high``- · ``api-agent:gemini:gemini-3.7-flash`` (in-process tool loop on a ChatModel)++ The coding agent is always a VENDOR agent: the harness supplies the workspace, the+ prompt and its 3D tools (over MCP) and reads the result. The in-process+ ``api-agent`` tool loop was deleted 2026-08-28 — reimplementing agent plumbing the+ vendors already ship was never this project's job (owner's call)."""planner: str = "gemini:gemini-3.7-flash"- generator: str = "api-agent:gemini:gemini-3.7-flash"+ generator: str = "gemini-cli:gemini-3.6-flash"# The judge drives the refine loop: the pro tier has ~3x lower sample noise than# flash (calibration 2026-08-23: std 0.03 vs 0.08-0.12) for ~$0.07 per verdict.judge: str = "gemini:gemini-3.1-pro-preview"diff --git a/harness/codeverse/cost/caching.py b/harness/codeverse/cost/caching.pyindex 9c5b8117..19deaa5d 100644--- a/harness/codeverse/cost/caching.py+++ b/harness/codeverse/cost/caching.py@@ -192,7 +192,7 @@ def session_key(label: str) -> str:A session is what shares a prompt prefix: every turn of one agent session,every sample of one verdict."""parts = [p for p in (label or "").split(":") if p]- if parts and parts[0] == "api-agent":+ if parts and parts[0] == "api-agent": # historical ledgers only (backend deleted 2026-08-28)parts = parts[1:]while parts and len(parts[-1]) > 1 and parts[-1][0] in "tsr" and parts[-1][1:].isdigit():parts = parts[:-1]diff --git a/harness/codeverse/cost/instrument.py b/harness/codeverse/cost/instrument.pyindex a9e8f320..e53810e2 100644--- a/harness/codeverse/cost/instrument.py+++ b/harness/codeverse/cost/instrument.py@@ -94,7 +94,11 @@ def per_call_metering() -> bool:#: session whose turns ran in another thread looked unmetered and was counted#: twice. The backend either meters itself or it does not; that is a property of#: the backend, not of what happened to run alongside it.-IN_PROCESS_AGENT_KINDS = frozenset({"api-agent"})+#: empty since 2026-08-28: the in-process ``api-agent`` was the only backend whose+#: individual model calls landed on the ledger by themselves. A vendor CLI bills as one+#: session row. Kept (rather than deleted) because ``meters_own_calls`` is the seam a+#: future self-metering backend would declare itself through.+IN_PROCESS_AGENT_KINDS: frozenset[str] = frozenset()def meters_own_calls(agent: Any) -> bool:diff --git a/harness/codeverse/cost/profiles.py b/harness/codeverse/cost/profiles.pyindex 2f75d9a5..3e143385 100644--- a/harness/codeverse/cost/profiles.py+++ b/harness/codeverse/cost/profiles.py@@ -118,7 +118,7 @@ PROFILES: dict[str, Profile] = {),"balanced": Profile(name="balanced",- generator="api-agent:gemini:gemini-3.7-flash",+ generator="gemini-cli:gemini-3.6-flash",planner="gemini:gemini-3.7-flash",judge="gemini:gemini-3.1-pro-preview",captioner="gemini:gemini-3.7-flash",@@ -131,7 +131,7 @@ PROFILES: dict[str, Profile] = {),"quality": Profile(name="quality",- generator="api-agent:gemini:gemini-3.7-flash",+ generator="gemini-cli:gemini-3.6-flash",planner="gemini:gemini-3.7-flash",judge="gemini:gemini-3.1-pro-preview",captioner="gemini:gemini-3.7-flash",diff --git a/harness/codeverse/cost/routing.py b/harness/codeverse/cost/routing.pyindex 4d25a2ec..d91623bd 100644--- a/harness/codeverse/cost/routing.py+++ b/harness/codeverse/cost/routing.py@@ -47,7 +47,7 @@ ROUTES: tuple[Route, ...] = ("always — the plan is 0.8% of a run; a pro planner would double that for no measured gain",default=True),# -------------------------------------------------------------- generator- Route(Role.GENERATOR, "api-agent:gemini:gemini-3.7-flash", 0.52,+ Route(Role.GENERATOR, "gemini-cli:gemini-3.6-flash", 0.52,"compare_v1: mean judge 0.835 on easy static objects (best arm measured)","default for every track that has tools (it is the loop, not the model, that scores)",default=True),diff --git a/harness/codeverse/cost/types.py b/harness/codeverse/cost/types.pyindex ac95c4e0..30af53e5 100644--- a/harness/codeverse/cost/types.py+++ b/harness/codeverse/cost/types.py@@ -162,7 +162,7 @@ class CallCost(BaseModel):backend: str = ""provider: str = ""model: str = "" # bare model name, canonical (no provider prefix)- model_id: str = "" # as reported by the backend ("api-agent:gemini:gemini-3.7-flash")+ model_id: str = "" # as reported by the backend ("gemini-cli:gemini-3.6-flash")input_tokens: int = 0cached_tokens: int = 0diff --git a/harness/codeverse/flywheel/telemetry.py b/harness/codeverse/flywheel/telemetry.pyindex 8a191d06..24625af5 100644--- a/harness/codeverse/flywheel/telemetry.py+++ b/harness/codeverse/flywheel/telemetry.py@@ -93,7 +93,7 @@ def _planner_defaults() -> dict[str, Any]:def _generator_defaults(model_id: str) -> dict[str, Any]:"""Only the in-process ``api-agent`` exposes sampling knobs; CLI agents own theirs."""- if backend_kind(model_id) != "api-agent":+ if backend_kind(model_id) != "api-agent": # historical runs only (backend deleted 2026-08-28)return {}try:from codeverse.contracts.agent import ApiAgentOptionsdiff --git a/harness/codeverse/skills/delivery.py b/harness/codeverse/skills/delivery.pyindex a4842a8f..dbc26e5c 100644--- a/harness/codeverse/skills/delivery.py+++ b/harness/codeverse/skills/delivery.py@@ -65,7 +65,6 @@ _BACKENDS: dict[str, Delivery] = {"codex": Delivery(root=AGENTS_SKILL_ROOT, native_loader=True),"gemini-cli": Delivery(root=AGENTS_SKILL_ROOT, native_loader=True),"agy": Delivery(root=AGENTS_SKILL_ROOT, native_loader=True),- "api-agent": Delivery(root=AGENTS_SKILL_ROOT, native_loader=False),}#: the safe answer for a backend nobody has classified yetdiff --git a/harness/codeverse/tracks/scene_asset_gen.py b/harness/codeverse/tracks/scene_asset_gen.pyindex 0e189db6..62b71cc8 100644--- a/harness/codeverse/tracks/scene_asset_gen.py+++ b/harness/codeverse/tracks/scene_asset_gen.py@@ -42,17 +42,18 @@ ASSET_MAX_TRIS = 15_000# ----------------------------------------------------------------------------- strategy-def single_shot_agent_id(agent_id: str) -> str:- """``api-agent:gemini:x`` → ``single-shot:gemini:x``; "" when not derivable.-- Only API backends can be single-shot: a CLI agent (gemini-cli / claude-code /- codex / agy) runs on a local subscription and exposes no chat model."""+def single_shot_agent_id(agent_id: str, chat_model_id: str = "") -> str:+ """The single-shot strategy id for this run, or "" when there is no chat model.++ Single-shot is ONE api call that returns the asset file — the cheap path the asset+ stage tries before escalating to a full agent session. It needs a chat model, and+ the coding agent is always a vendor CLI (which exposes none), so the model comes+ from ``chat_model_id`` — the run's planner backend, which is always an API model.+ Until 2026-08-28 it was derived from the in-process ``api-agent`` generator id;+ that backend is gone."""if is_single_shot(agent_id):return agent_id- kind, _, rest = agent_id.partition(":")- if kind == "api-agent" and rest.count(":") >= 1:- return SINGLE_SHOT_PREFIX + rest- return ""+ return SINGLE_SHOT_PREFIX + chat_model_id if chat_model_id.count(":") >= 1 else ""def single_shot_ctx(ctx: RunContext) -> RunContext | None:@@ -61,7 +62,7 @@ def single_shot_ctx(ctx: RunContext) -> RunContext | None:cached = ctx.extra.get("_single_shot_ctx")if cached is not None:return cached or None # False = known-unavailable- sid = single_shot_agent_id(ctx.agent_id)+ sid = single_shot_agent_id(ctx.agent_id, getattr(ctx.spec.backends, "planner", ""))sub: RunContext | None = Noneif sid:try:diff --git a/harness/docs/COMPLEXITY.md b/harness/docs/COMPLEXITY.mdindex 25f7ff9c..e8a1efd9 100644--- a/harness/docs/COMPLEXITY.md+++ b/harness/docs/COMPLEXITY.md@@ -290,7 +290,7 @@ expected to reach:```3dcv bench run bench/prompts/complexity_v3.yaml --out bench/out/complexity_v3 \- --generator api-agent:gemini:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview+ --generator gemini-cli:gemini-3.6-flash --judge gemini:gemini-3.1-pro-previewpython bench/complexity_report.py bench/out/complexity_v3 --battery bench/prompts/complexity_v3.yaml```@@ -305,7 +305,7 @@ number the next wave should move.## 5. Live check: three `static_objects_v2` prompts re-run (2026-08-24)Re-run on the current tree with the same generator and judge as their recorded-baselines (`api-agent:gemini:gemini-3.7-flash` / `gemini-3.1-pro-preview`), and+baselines (`gemini-cli:gemini-3.6-flash` / `gemini-3.1-pro-preview`), andscored against the recorded run of the same prompt:| run / arm | index | parts | tris | silhouette | feature density | hollow | overall | detail | fit | materials | $ | min |diff --git a/harness/docs/COST.md b/harness/docs/COST.mdindex 4e5f0882..171fd3c0 100644--- a/harness/docs/COST.md+++ b/harness/docs/COST.md@@ -321,7 +321,7 @@ residency (1.1x) and fast-mode multipliers, per-search server-tool fees.| role | model | $/call | measured quality | when ||---|---|---|---|---|| planner | `gemini:gemini-3.7-flash` ★ | $0.013 | no failure attributable to the planner | always — the plan is 0.8% of a run |-| generator | `api-agent:gemini:gemini-3.7-flash` ★ | $0.52 | compare_v1 mean 0.835 (best arm) | default for every track with tools |+| generator | `gemini-cli:gemini-3.6-flash` ★ | $0.52 | compare_v1 mean 0.835 (best arm) | default for every track with tools || generator | `single-shot:gemini:gemini-3.7-flash` | $0.05 | graphics: 5/6 passed, median 0.810 | glsl / opengl — one file, compiler feedback || generator | `gemini-cli:gemini-3.7-flash` | $0.73 | 0.827 — same as api-agent, 2x price, 2x wall | only when you need the CLI itself || generator | `codex:gpt-5.6-sol` | $1.93 in-loop / $0.20 one-shot | one-shot 0.786 | strong one-shot baseline, expensive loop |@@ -632,7 +632,7 @@ given**, so `3dcv resume` reproduces it.| | economy | balanced | quality ||---|---|---|---|-| generator | `single-shot:gemini:gemini-3.7-flash` | `api-agent:gemini:gemini-3.7-flash` | `api-agent:gemini:gemini-3.7-flash` |+| generator | `single-shot:gemini:gemini-3.7-flash` | `gemini-cli:gemini-3.6-flash` | `gemini-cli:gemini-3.6-flash` || judge | flash, n=2 | **pro, n=1** | **pro, n=3** || refine rounds | 2 | 4 | 4 || best-of-N | 1 | 1 | 2 |@@ -750,7 +750,7 @@ turns past 28 buy nothing. A controlled A/B says they do:| uncapped (backend default) | $1.001 / 0.852 | $1.603 / 0.600 | $1.477 / 0.600 | **$1.360** | **0.684** |Same prompt (an articulated desk lamp), same generator-(`api-agent:gemini:gemini-3.7-flash`), same judge (`gemini-3.1-pro-preview`),+(`gemini-cli:gemini-3.6-flash`), same judge (`gemini-3.1-pro-preview`),same budget and box; 3 runs per arm; scripts and run dirs in`verifier/ab_uncapped.py` + `verifier/live/vstatic_hard_lamp + vlamp_cap60*`. The cap **cost $0.02 moreand 0.205 of a score point**: a session stopped at turn 28 leaves work the nextdiff --git a/harness/docs/EVAL.md b/harness/docs/EVAL.mdindex 1e6e6b7b..88aec291 100644--- a/harness/docs/EVAL.md+++ b/harness/docs/EVAL.md@@ -54,7 +54,7 @@ deterministic contract check.```bash3dcv bench run bench/prompts/static_objects_v1.yaml \- --generator api-agent:gemini:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview \+ --generator gemini-cli:gemini-3.6-flash --judge gemini:gemini-3.1-pro-preview \--rounds 2 --max-usd 2.5 --parallel 4 --out bench/out/static_v1_apiagent3dcv bench run bench/prompts/static_objects_v1.yaml --generator gemini-cli:gemini-3.7-flash --judge gemini:gemini-3.1-pro-preview --out bench/out/static_v1_gemcli3dcv bench report bench/out/static_v1_apiagent@@ -80,7 +80,7 @@ cheaply.```bashpython bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml \- --arms harness:api-agent:gemini:gemini-3.7-flash,harness:gemini-cli:gemini-3.7-flash,oneshot:claude-code,oneshot:codex,oneshot:gemini:gemini-3.7-flash,oneshot+repair:gemini:gemini-3.7-flash \+ --arms harness:gemini-cli:gemini-3.6-flash,harness:gemini-cli:gemini-3.7-flash,oneshot:claude-code,oneshot:codex,oneshot:gemini:gemini-3.7-flash,oneshot+repair:gemini:gemini-3.7-flash \--judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1 [--parallel 3] [--limit N] [--ids a,b][--rounds 3] [--max-usd 2.5] [--loop-judge gemini:gemini-3.7-flash] [--repair-attempts 2] [--gen-timeout 900][--no-pairwise] [--no-resume] [--report-only]@@ -116,7 +116,7 @@ unstated effort silently changes what a codex arm measures.### Codex tiers — results (compare_v3, verified 2026-08-24)-**Incomplete: `harness:codex:gpt-5.6-sol` has 2 evaluated cells, `harness:api-agent:gemini:gemini-3.7-flash` 2, `oneshot:gemini:gemini-3.7-flash` 7; harness terra / luna have none** — flash (the planner) answered on 0/6 keys and pro (the judge) intermittently for the whole window, so only the 8 compare_v2 prompts are covered and none of compare_v3's 4 new prompts has run. Full table, per-prompt grid and re-pricing notes: `bench/out/codex_tiers_v3/report.md`.+**Incomplete: `harness:codex:gpt-5.6-sol` has 2 evaluated cells, `harness:gemini-cli:gemini-3.6-flash` 2, `oneshot:gemini:gemini-3.7-flash` 7; harness terra / luna have none** — flash (the planner) answered on 0/6 keys and pro (the judge) intermittently for the whole window, so only the 8 compare_v2 prompts are covered and none of compare_v3's 4 new prompts has run. Full table, per-prompt grid and re-pricing notes: `bench/out/codex_tiers_v3/report.md`.Fixed judge `gemini:gemini-3.1-pro-preview` for every cell; `infra_failed` / outage-text cells excluded (`dropped`), not scored 0; codex USD re-priced from recorded tokens with `codeverse.models.pricing` (terra/luna price rows post-date the runs, so `results.jsonl` shows 0.00 for terra). All 44 codex invocations (24 one-shot argv, 20 harness trajectory argv) carry `--model gpt-5.6-<tier>` and `-c model_reasoning_effort=high`; the un-tiered `oneshot:codex` arm resolves to sol@high via `~/.codex/config.toml`.@@ -125,7 +125,7 @@ Fixed judge `gemini:gemini-3.1-pro-preview` for every cell; `infra_failed` / out| harness:codex:gpt-5.6-sol | 2 | 0 | 0.928 | 0.928 | 2/2 | 100% | 0.26 | 6.97 | 7.23 || oneshot:codex (config = sol@high) | 8 | 0 | 0.637 | 0.600 | 1/8 | 100% | 0 | 0.33 | 2.60 || oneshot:codex:gpt-5.6-sol | 8 | 0 | 0.627 | 0.600 | 1/8 | 100% | 0 | 0.34 | 2.74 |-| harness:api-agent:gemini:gemini-3.7-flash | 2 | 0 | 0.600 | 0.600 | 0/2 | 100% | 0.64 | 0 | — |+| harness:gemini-cli:gemini-3.6-flash | 2 | 0 | 0.600 | 0.600 | 0/2 | 100% | 0.64 | 0 | — || oneshot:codex:gpt-5.6-terra | 8 | 0 | 0.481 | 0.551 | 2/8 | 88% | 0 | 0.14 | 0.55 || oneshot:claude-code | 8 | 0 | 0.472 | 0.600 | 0/8 | 75% | 0 | 1.17 | — || oneshot:codex:gpt-5.6-luna | 8 | 0 | 0.344 | 0.324 | 1/8 | 75% | 0 | 0.01 | 0.11 |@@ -259,7 +259,7 @@ verdict rule is blunt on purpose (`bench/_ab_report.verdict_of`, stated once):**That rule is a screen, not a proof, and the numbers say by how much.** Measured2026-08-24 with two A/A runs — arms identical by construction — on the *same* prompt-`ctrl_med_dining_chair` at rounds 1, `api-agent:gemini:gemini-3.7-flash`, fixed judge+`ctrl_med_dining_chair` at rounds 1, `gemini-cli:gemini-3.6-flash`, fixed judge`gemini-3.1-pro-preview` n=2:| run | control | variant | delta | verdict the rule printed |diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.mdindex 7c8e4de1..bf2a7003 100644--- a/harness/docs/INSTALL.md+++ b/harness/docs/INSTALL.md@@ -359,7 +359,7 @@ export GEMINI_API_KEYS="key1,key2,key3" # e.g. in ~/.bashrc### 8.2 Subscription CLIs (all optional)Only needed if you want `--generator gemini-cli:… | claude-code:… | codex:… | agy:…`.-The default generator (`api-agent:gemini:gemini-3.7-flash`) needs none of them.+The default generator (`gemini-cli:gemini-3.6-flash`) needs none of them.```bashnpm i -g @google/gemini-cli # gemini (0.53.0 here)diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.mdindex ea61803b..ca20d366 100644--- a/harness/docs/RUNBOOK.md+++ b/harness/docs/RUNBOOK.md@@ -74,7 +74,7 @@ round, then ≈ $0.36 / ~7 min per refine (give scenes `--max-minutes 60 --max-u| id | what runs | notes ||---|---|---|-| `api-agent:gemini:gemini-3.7-flash` (default) | in-process tool loop with file tools + every spatial tool | cheapest agentic path; the only backend whose transcripts feed repair-pair mining |+| `gemini-cli:gemini-3.6-flash` (default) | in-process tool loop with file tools + every spatial tool | cheapest agentic path; the only backend whose transcripts feed repair-pair mining || `single-shot:gemini:gemini-3.7-flash` | one structured-output call → multi-file envelope, no tools | fastest/cheapest; baseline for "raw model" deltas || `gemini-cli:gemini-3.7-flash` | `gemini -p … --approval-mode yolo --skip-trust --output-format json` | see gotchas below || `claude-code:<model>` | `claude -p … --dangerously-skip-permissions --mcp-config trajectories/<label>_rNN/mcp.json --strict-mcp-config …` | local subscription — test lightly |@@ -184,7 +184,7 @@ call the `texture_pass` / `texture_preview` tools mid-session.--judge gemini:gemini-3.1-pro-preview --rounds 2 --parallel 4 [--tier easy] [--id furn_easy_stool] [--limit 6] [--out bench/out/x]3dcv bench report bench/out/static_objects_v1 # report.md + self-contained report.html (gallery)python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml \- --arms harness:api-agent:gemini:gemini-3.7-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1+ --arms harness:gemini-cli:gemini-3.6-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1```Results stream to `results.jsonl` (resumable). Batteries: `static_objects_v1` (24),`articulated_v1` (12), `scenes_v1` (12), `compare_v1` (8, harness-vs-one-shot).diff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.mdindex d5f7486a..ce390384 100644--- a/harness/docs/SKILLS.md+++ b/harness/docs/SKILLS.md@@ -299,7 +299,7 @@ Two contradiction checks are worth separating, because they answer different que### The rig`bench/ab_plan.py`, arms differing in exactly one thing — `CV3D_SKILLS=on` on the variant —-on `static_objects_v2`, `--rounds 1`, paired, generator `api-agent:gemini:gemini-3.7-flash`,+on `static_objects_v2`, `--rounds 1`, paired, generator `gemini-cli:gemini-3.6-flash`,fixed judge `gemini:gemini-3.1-pro-preview` at `n_samples 2`, `--max-in-flight 8` against32–48 of pool headroom, `--wait-for-provider`. The eight prompt ids are **the same eight`bench/out/plan_loop/C0` used for its A/A**, so the noise floor below was measured on thisdiff --git a/harness/docs/TEASER.md b/harness/docs/TEASER.mdindex cd105313..ae9fe788 100644--- a/harness/docs/TEASER.md+++ b/harness/docs/TEASER.md@@ -49,7 +49,7 @@ rebuilt (§5).| 05 graphics | Accretion disc | GLSL | flash | 0.753 | reads || 05 graphics | Rain on a window | GLSL | flash | 0.909 | usable |-`flash` = `api-agent:gemini:gemini-3.7-flash`. Judge = `gemini-3.1-pro-preview`+`flash` = `gemini-cli:gemini-3.6-flash`. Judge = `gemini-3.1-pro-preview`(flash × 3 fallback). Per card the page shows: the prompt, the language(s), the generator,the judged score, the round count, the wall-clock, the run slug, and an honest note.@@ -117,10 +117,10 @@ suffixed `_v2` / `_v3`, with the CLI flags that are not expressible in `BenchPro(`--style`, `--must-not`, `--candidates`, `--profile`) recorded as comments above it.```-3dcv bench run bench/prompts/teaser_v1_static.yaml --generator api-agent:gemini:gemini-3.7-flash-3dcv bench run bench/prompts/teaser_v1_articulated.yaml --generator api-agent:gemini:gemini-3.7-flash-3dcv bench run bench/prompts/teaser_v1_scene.yaml --generator api-agent:gemini:gemini-3.7-flash-3dcv bench run bench/prompts/teaser_v1_graphics.yaml --generator api-agent:gemini:gemini-3.7-flash+3dcv bench run bench/prompts/teaser_v1_static.yaml --generator gemini-cli:gemini-3.6-flash+3dcv bench run bench/prompts/teaser_v1_articulated.yaml --generator gemini-cli:gemini-3.6-flash+3dcv bench run bench/prompts/teaser_v1_scene.yaml --generator gemini-cli:gemini-3.6-flash+3dcv bench run bench/prompts/teaser_v1_graphics.yaml --generator gemini-cli:gemini-3.6-flash```The three hero pieces used `--generator codex:gpt-5.6-sol` instead (penny-farthing, radialdiff --git a/harness/tests/agents/test_api_agent.py b/harness/tests/agents/test_api_agent.pydeleted file mode 100644index 2c090fb0..00000000--- a/harness/tests/agents/test_api_agent.py+++ /dev/null@@ -1,345 +0,0 @@-"""ApiAgent loop with a scripted FakeChatModel (+ one live gemini test)."""--from __future__ import annotations--import json-from pathlib import Path--import pytest--from codeverse.agents.api_agent import FRESHNESS_NUDGE, ApiAgent-from codeverse.agents.api_tools import ToolOutcome-from codeverse.agents.context import FACTS_TAG, compact_messages, message_chars-from codeverse.config import get_settings-from codeverse.contracts.agent import AgentJob-from codeverse.contracts.chat import (- ChatMessage,- ChatRequest,- ChatResponse,- TextPart,- ToolCallPart,- ToolResultPart,- ToolSpec,-)-from codeverse.contracts.common import Usage---class FakeChatModel:- """Replays scripted responses; records every request."""-- provider, model = "fake", "fake-1"-- def __init__(self, script: list[ChatResponse]):- self.script = list(script)- self.requests: list[ChatRequest] = []-- @property- def id(self) -> str:- return "fake:fake-1"-- def supports_vision(self) -> bool:- return True-- def generate(self, request: ChatRequest) -> ChatResponse:- self.requests.append(request)- if not self.script:- return ChatResponse(text="out of script", usage=Usage(input_tokens=1, output_tokens=1, cost_usd=0.001))- r = self.script.pop(0)- if isinstance(r, Exception):- raise r- return r---def call(name: str, **args) -> ToolCallPart:- return ToolCallPart(id=f"c{abs(hash((name, json.dumps(args, sort_keys=True)))) % 10000}", name=name, arguments=args)---def resp(text: str = "", *calls: ToolCallPart) -> ChatResponse:- return ChatResponse(text=text, tool_calls=list(calls), usage=Usage(input_tokens=10, output_tokens=5, cost_usd=0.01))---class FakeSpatial:- """Stands in for the registry bridge: one `build` tool that records calls."""-- def __init__(self, *a, **k):- self.calls: list[dict] = []- self.tools = {"build": True}-- def specs(self):- return [ToolSpec(name="build", description="build it", parameters={"type": "object", "properties": {}})]-- def names(self):- return {"build"}-- def call(self, name, args):- self.calls.append(args)- return ToolOutcome("build ok: 12 tris", numbers={"tris": 12})---def _job(ws, **kw) -> AgentJob:- base = dict(workspace=str(ws.root), prompt="make src/hello.txt say hi", label="api", timeout_s=60, max_turns=8,- spatial_tools=False)- base.update(kw)- return AgentJob(**base)---def test_loop_writes_file_and_finishes(tmp_ws):- fake = FakeChatModel([- resp("let me look", call("list_files", glob="src/**/*")),- resp("", call("write_file", path="src/hello.txt", content="hi\n")),- resp("Done: wrote src/hello.txt"),- ])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws))- assert res.ok and res.exit_reason == "completed" and res.text.startswith("Done"), res.errors- assert (tmp_ws.src / "hello.txt").read_text() == "hi\n"- assert [f.path for f in res.files_changed] == ["src/hello.txt"] and res.tool_calls == 2- assert res.usage.input_tokens == 30 and res.usage.cost_usd == pytest.approx(0.03)- # tool results fed back as role=tool messages- last_req = fake.requests[-1]- assert last_req.messages[-1].role == "tool" and isinstance(last_req.messages[-1].parts[0], ToolResultPart)- assert last_req.tools and {t.name for t in last_req.tools} >= {"read_file", "write_file", "edit_file", "list_files", "run_shell"}- # transcript- kinds = [json.loads(ln)["kind"] for ln in Path(res.transcript_path).read_text().splitlines()]- assert kinds[0] == "system" and kinds.count("assistant") == 3 and kinds.count("tool_result") == 2- rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())- assert rec["nudged"] is False and "write_file" in rec["tools"]---def test_system_prompt_uses_agents_md_and_append(tmp_ws):- (tmp_ws.root / "AGENTS.md").write_text("RULES HERE")- fake = FakeChatModel([resp("done")])- ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, system_append="APPEND"))- assert fake.requests[0].system.startswith("RULES HERE") and fake.requests[0].system.endswith("APPEND")---def test_freshness_nudge_once(tmp_ws, monkeypatch):- monkeypatch.setattr("codeverse.agents.api_agent.SpatialTools", FakeSpatial)- fake = FakeChatModel([- resp("", call("write_file", path="src/a.txt", content="x")),- resp("all done"), # claims done without build → nudge- resp("", call("build")), # obeys- resp("", call("edit_file", path="src/a.txt", old="x", new="y")),- resp("really done"), # edited after build again, but nudged already → accept- ])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, spatial_tools=True))- assert res.ok and res.text == "really done"- nudges = [m for r in fake.requests for m in r.messages if m.role == "user" and m.text == FRESHNESS_NUDGE]- assert nudges # nudge was injected- rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())- assert rec["nudged"] is True and "build" in rec["tools"]---def test_run_build_alias_and_unknown_tool(tmp_ws, monkeypatch):- monkeypatch.setattr("codeverse.agents.api_agent.SpatialTools", FakeSpatial)- fake = FakeChatModel([resp("", call("run_build"), call("bogus", x=1)), resp("done")])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, spatial_tools=True))- assert res.ok- tool_msg = fake.requests[1].messages[-1]- parts = {p.name: p for p in tool_msg.parts}- assert "build ok" in parts["run_build"].content and parts["bogus"].is_error---def test_max_turns_and_budget(tmp_ws):- fake = FakeChatModel([resp("", call("list_files")) for _ in range(20)])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, max_turns=3))- assert not res.ok and res.exit_reason == "budget" and "max_turns" in res.errors[0]- fake = FakeChatModel([resp("", call("list_files")) for _ in range(20)])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, extra={"max_usd": 0.015}))- assert not res.ok and res.exit_reason == "budget" and "max_usd" in res.errors[0]---def test_model_error_retry_then_fail(tmp_ws):- class Boom(RuntimeError):- retryable = True-- fake = FakeChatModel([Boom("503"), resp("", call("list_files")), Boom("bad"), Boom("bad"), Boom("bad")])- fake.script[2].retryable = False- import codeverse.agents.api_agent as mod-- orig = mod.time.sleep- mod.time.sleep = lambda s: None- try:- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws))- finally:- mod.time.sleep = orig- assert not res.ok and res.exit_reason == "error" and "model error" in res.errors[0]---def test_write_outside_roots_is_refused(tmp_ws):- fake = FakeChatModel([resp("", call("write_file", path="artifacts/x.glb", content="z")), resp("ok")])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws))- assert res.ok and not (tmp_ws.artifacts / "x.glb").exists()- assert fake.requests[1].messages[-1].parts[0].is_error---def test_compaction():- msgs = [ChatMessage.user("task")]- for i in range(12):- msgs.append(ChatMessage(role="assistant", parts=[TextPart(text=f"t{i}"), call("read_file", path=f"f{i}")]))- msgs.append(ChatMessage(role="tool", parts=[ToolResultPart(call_id=f"c{i}", name="read_file", content="X" * 1000)]))- before = message_chars(msgs)- out = compact_messages(msgs, keep_recent=4, facts="- nothing yet")- assert message_chars(out) < before / 2- assert out[0].text == "task" and out[1].text.startswith(FACTS_TAG)- assert out[-1] is msgs[-1] and "compacted" in out[3].parts[0].content- again = compact_messages(out, keep_recent=4, facts="- new facts")- assert sum(1 for m in again if m.role == "user" and m.text.startswith(FACTS_TAG)) == 1---def test_compaction_triggers_in_loop(tmp_ws, monkeypatch):- monkeypatch.setattr("codeverse.agents.api_agent.COMPACT_AT_CHARS", 2000)- (tmp_ws.src / "big.txt").write_text("Z" * 1500)- fake = FakeChatModel([resp("", call("read_file", path="src/big.txt")) for _ in range(8)] + [resp("done")])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, max_turns=12))- assert res.ok- kinds = [json.loads(ln)["kind"] for ln in Path(res.transcript_path).read_text().splitlines()]- assert "compact" in kinds- assert any(m.text.startswith(FACTS_TAG) for m in fake.requests[-1].messages if m.role == "user")---def test_live_api_agent_gemini(tmp_ws):- if not get_settings().gemini_api_keys:- pytest.skip("no gemini keys")- agent = ApiAgent("gemini:gemini-3.7-flash")- res = agent.run(AgentJob(workspace=str(tmp_ws.root), label="live", timeout_s=240, max_turns=8, spatial_tools=False,- prompt="Create the file src/hello.txt containing exactly the word 'hi' (use write_file), "- "then read it back to verify, then reply DONE."))- assert res.ok, res.errors- assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"- assert res.usage.input_tokens > 0 and res.tool_calls >= 1---def test_job_images_ride_on_the_first_user_message(tmp_ws, tmp_path):- """Until 2026-08-26 no image reached an agent session: GenerationTask.images fed the- single-shot path only, so a `--image` reference was seen by the planner and the judge- and never by the code writer, and a refine session got "what the judge saw" as prose- without the sheet the prose was written about."""- from codeverse.contracts.chat import ImagePart-- png = tmp_path / "sheet.png"- png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 32)- fake = FakeChatModel([resp("Done")])- job = _job(tmp_ws)- job = job.model_copy(update={"images": [ImagePart(path=str(png), label="the contact sheet the judge scored (round 0)")]})- ApiAgent("fake:fake-1", chat_model=fake).run(job)- first = fake.requests[0].messages[0]- imgs = [pt for pt in first.parts if isinstance(pt, ImagePart)]- assert imgs and imgs[0].path == str(png), "the image must be a part of the FIRST user message"- assert "judge scored" in (imgs[0].label or "")---# ------------------------------------------------------ per-turn retry budget (audit 2026-08-26 §5.1)-class _Clock:- """Fake ``time`` for the agent loop: ``monotonic()`` moves only when a test moves it."""-- def __init__(self, t: float = 1000.0):- self.t = t- self.slept: list[float] = []-- def monotonic(self) -> float:- return self.t-- def sleep(self, s: float) -> None:- self.slept.append(s)- self.t += s---def test_each_turn_gets_a_retry_budget_clipped_to_what_the_session_can_afford(tmp_ws, monkeypatch):- """Audit 2026-08-26 §5.1: 66 give-up spans of the model's 900 s deadline (up to 3 in a row on- one turn: median 923 s, p90 2 743 s) were 30 % of the storm day's waiting, ~1 430 s per run.- A turn's call retries for as long as the answer it asked for plausibly needs (at least- TURN_WAIT_MAX_S, at most TURN_WAIT_CEILING_S) and NEVER past the session deadline,- floored at 20 s so a late turn still gets one real attempt."""- import codeverse.agents.api_agent as mod-- envelope = max(mod.TURN_WAIT_MAX_S, min(mod.TURN_WAIT_CEILING_S,- mod.TURN_TOKENS / mod.TURN_SLOW_TOKENS_PER_S + mod.TURN_WAIT_OVERHEAD_S))- for timeout_s, want in ((6000, envelope), (60, 60.0), (5, 20.0)):- monkeypatch.setattr(mod, "time", _Clock())- fake = FakeChatModel([resp("", call("list_files")), resp("done")])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, timeout_s=timeout_s))- assert res.ok, res.errors- assert [r.max_wait_s for r in fake.requests] == [want, want], timeout_s---def test_a_turn_stops_retrying_once_the_session_deadline_has_passed(tmp_ws, monkeypatch):- """The deadline used to be checked only at the top of a turn: a turn that met it inside the- retry loop still slept 2 s + 4 s and re-entered the model's whole retry machine twice more- (97 sessions overshot their timeout on 2026-08-26 by 182 s median / 1 154 s p90)."""- import codeverse.agents.api_agent as mod-- clock = _Clock()- monkeypatch.setattr(mod, "time", clock)-- class Boom(RuntimeError):- retryable = True-- class StormModel(FakeChatModel):- def generate(self, request: ChatRequest) -> ChatResponse:- self.requests.append(request)- clock.t += request.max_wait_s # the model spent its whole budget retrying- raise Boom("503 high demand")-- fake = StormModel([])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, timeout_s=100))- assert not res.ok and res.exit_reason == "error"- assert fake.requests[0].max_wait_s == 100.0- assert len(fake.requests) == 1, "no retry once the deadline has passed"- assert clock.slept == [], "and no 2 s / 4 s sleep past it"- assert "deadline passed" in res.errors[0]- rows = [json.loads(ln) for ln in Path(res.transcript_path).read_text().splitlines()]- (err_row,) = [r for r in rows if r["kind"] == "model_error"]- assert err_row["deadline_passed"] is True and err_row["retryable"] is True---def cut(text: str = "thinking...") -> ChatResponse:- """A turn that ran out of output tokens mid-thought: partial text, no tool call."""- return ChatResponse(text=text, tool_calls=[], finish_reason="MAX_TOKENS",- usage=Usage(input_tokens=10, output_tokens=637, cost_usd=0.02))---def test_a_turn_truncated_while_thinking_is_nudged_not_treated_as_finished(tmp_ws):- """art_med_tool_chest, 2026-08-27: turn 5 spent 15 359 thinking tokens, hit- MAX_TOKENS, emitted partial text and no tool call — and `if not resp.tool_calls`- recorded the session as completed with zero files written."""- from codeverse.agents.api_agent import TRUNCATED_NUDGE-- fake = FakeChatModel([- cut("<thought>let me work out the hinge axis and"),- resp("", call("write_file", path="src/model.py", content="import bpy\n")),- resp("done"),- ])- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws))- assert res.ok and res.files_changed, "a truncated turn must not end the session"- assert (tmp_ws.src / "model.py").is_file()- assert any(m.text == TRUNCATED_NUDGE for r in fake.requests for m in r.messages if m.role == "user")---def test_repeated_truncation_fails_the_session_instead_of_looping(tmp_ws):- from codeverse.agents.api_agent import MAX_TRUNCATED_NUDGES-- fake = FakeChatModel([cut()] * (MAX_TRUNCATED_NUDGES + 2))- res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws))- assert not res.ok and res.exit_reason == "truncated"- assert any("output tokens" in e for e in res.errors)---def test_a_truncated_turn_widens_the_output_envelope(tmp_ws):- """The model was not misbehaving: thinking grew 13 -> 3 144 -> 15 359 tokens on a hard- problem and 15 359 + 637 hit the 16 000 default exactly. planner has grown its budget- on truncation for months; the agent loop took the default and never moved."""- from codeverse.agents.api_agent import TURN_TOKENS, TURN_TOKENS_GROWTH, TURN_TOKENS_MAX-- fake = FakeChatModel([- cut("<thought>the hinge axis and"),- resp("", call("write_file", path="src/model.py", content="import bpy\n")),- resp("done"),- ])- ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws))- asked = [r.max_output_tokens for r in fake.requests]- assert asked[0] == TURN_TOKENS- # TURN_TOKENS already IS the model's declared ceiling, so growth clamps there: the- # invariant is "never shrink, never exceed the ceiling" — it survives the default moving- assert TURN_TOKENS <= asked[1] <= TURN_TOKENS_MAX- assert asked[1] == min(TURN_TOKENS_MAX, int(TURN_TOKENS * TURN_TOKENS_GROWTH))diff --git a/harness/tests/agents/test_api_tools.py b/harness/tests/agents/test_api_tools.pydeleted file mode 100644index 96b935ff..00000000--- a/harness/tests/agents/test_api_tools.py+++ /dev/null@@ -1,168 +0,0 @@-"""FileTools confinement + run_shell policy (allow-list, no inline code, workspace-only paths, never raises)."""--from __future__ import annotations--import os--from codeverse.agents.api_tools import FileTools-from codeverse.workspace import Workspace---def _tools(ws: Workspace) -> FileTools:- return FileTools(ws, ["src", "public"])---def test_write_read_edit_list(tmp_ws: Workspace):- t = _tools(tmp_ws)- out = t.call("write_file", {"path": "src/a.txt", "content": "hello world\n"})- assert not out.is_error and "created src/a.txt" in out.text- assert t.call("read_file", {"path": "src/a.txt"}).text == "hello world\n"- e = t.call("edit_file", {"path": "src/a.txt", "old": "world", "new": "there"})- assert not e.is_error and t.call("read_file", {"path": "src/a.txt"}).text == "hello there\n"- assert t.call("edit_file", {"path": "src/a.txt", "old": "nope", "new": "x"}).is_error- t.call("write_file", {"path": "src/b.txt", "content": "aa aa"})- assert t.call("edit_file", {"path": "src/b.txt", "old": "aa", "new": "b"}).is_error # ambiguous- assert not t.call("edit_file", {"path": "src/b.txt", "old": "aa", "new": "b", "all": True}).is_error- listing = t.call("list_files", {"glob": "src/*.txt"}).text- assert "src/a.txt" in listing and "src/b.txt" in listing- assert t.writes == ["src/a.txt", "src/a.txt", "src/b.txt", "src/b.txt"]---def test_path_sandbox(tmp_ws: Workspace):- t = _tools(tmp_ws)- assert t.call("write_file", {"path": "../escape.txt", "content": "x"}).is_error- assert t.call("write_file", {"path": "artifacts/x.txt", "content": "x"}).is_error- assert t.call("write_file", {"path": "/etc/passwd", "content": "x"}).is_error- assert t.call("read_file", {"path": ".git/HEAD"}).is_error- assert t.call("read_file", {"path": "../../etc/hostname"}).is_error- (tmp_ws.artifacts / "build.json").write_text("{}")- assert t.call("read_file", {"path": "artifacts/build.json"}).text == "{}" # reads outside write roots are fine- # symlink escape- os.symlink("/etc", tmp_ws.src / "etc_link")- assert t.call("write_file", {"path": "src/etc_link/x", "content": "x"}).is_error---def test_run_shell_allowlist(tmp_ws: Workspace):- t = _tools(tmp_ws)- (tmp_ws.src / "ok.py").write_text("x = 1\n")- out = t.call("run_shell", {"cmd": "python -m py_compile src/ok.py"})- assert not out.is_error and "rc=0" in out.text- assert t.call("run_shell", {"cmd": "rm -rf src"}).is_error- assert t.call("run_shell", {"cmd": "ls src | cat"}).is_error- assert t.call("run_shell", {"cmd": "cat /etc/passwd"}).is_error- (tmp_ws.src / "exit3.py").write_text("import sys; sys.exit(3)\n")- bad = t.call("run_shell", {"cmd": "python src/exit3.py"})- assert bad.is_error and "rc=3" in bad.text- (tmp_ws.src / "slow.py").write_text("import time; time.sleep(30)\n")- slow = t.call("run_shell", {"cmd": "python src/slow.py", "timeout_s": 5})- assert slow.is_error and "timeout" in slow.text---def test_run_shell_rejects_inline_code_and_escaping_paths(tmp_ws: Workspace):- """Regression: `python -c` / `node -e` / `..` paths used to bypass write_roots and the path check entirely."""- t = _tools(tmp_ws)- outside = tmp_ws.root.parent / "outside.txt"- denied = [- f"python -c \"open('{outside}','w').write('x')\"",- "python3 -c 'import subprocess; subprocess.run([\"id\"])'",- "python -Bc 'print(1)'", # combined short flags- "python -i",- "python -",- "python -m http.server",- "python -mhttp.server",- "python -cm py_compile", # = python -c "m"- "python -mc py_compile",- "node -e \"require('fs').writeFileSync('../outside2.txt','y')\"",- "node -pe 1",- "node --eval 1",- "node --eval=1",- "node --require=../x.js src/a.js",- "node -r ../x.js src/a.js",- "cat ../../../../../../etc/hostname",- "cat /etc/hostname",- "cat .git/HEAD",- "ls ~",- "find src -exec rm {} ;",- "find src -delete",- ]- for cmd in denied:- out = t.call("run_shell", {"cmd": cmd})- assert out.is_error and "rc=" not in out.text, (cmd, out.text)- assert not outside.exists() and not (tmp_ws.root.parent / "outside2.txt").exists()- # allowed shapes keep working- (tmp_ws.src / "a.js").write_text("const x = 1;\n")- (tmp_ws.src / "m.py").write_text("y = 2\n")- for cmd in ("node --check src/a.js", "python -m py_compile src/m.py", "python3 -m json.tool --help",- "grep -rn const src", "find src -name '*.js'", "ls -la src", "wc -l src/a.js", "head -n 1 src/a.js",- f"cat {tmp_ws.root}/src/a.js"):- out = t.call("run_shell", {"cmd": cmd})- assert "rc=0" in out.text, (cmd, out.text)- # symlink inside the workspace that points outside is resolved and refused- os.symlink("/etc", tmp_ws.src / "etc_link")- assert t.call("run_shell", {"cmd": "cat src/etc_link/hostname"}).is_error---def test_call_never_raises(tmp_ws: Workspace):- """ValueError / UnicodeDecodeError used to escape call() and crash ApiAgent.run."""- t = _tools(tmp_ws)- (tmp_ws.src / "b.bin").write_bytes(b"a\xffb")- (tmp_ws.src / "a.js").write_text("hello")- for name, args in [("run_shell", {"cmd": "ls src", "timeout_s": "soon"}),- ("run_shell", {"cmd": "ls src", "timeout_s": "60.0"}),- ("run_shell", {"cmd": "ls src", "timeout_s": None}),- ("edit_file", {"path": "src/b.bin", "old": "a", "new": "b"}),- ("edit_file", {"path": "src/a.js", "old": "hello", "new": None}),- ("write_file", {"path": "src/c.js", "content": None}),- ("list_files", {"glob": None}),- ("read_file", {"path": 7})]:- out = t.call(name, args) # must not raise- assert isinstance(out.text, str)- assert not t.call("run_shell", {"cmd": "ls src", "timeout_s": "soon"}).is_error- e = t.call("edit_file", {"path": "src/b.bin", "old": "a", "new": "b"})- assert e.is_error and "UTF-8" in e.text and (tmp_ws.src / "b.bin").read_bytes() == b"a\xffb"---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/agents/test_context.py b/harness/tests/agents/test_context.pydeleted file mode 100644index 0c80b22c..00000000--- a/harness/tests/agents/test_context.py+++ /dev/null@@ -1,23 +0,0 @@---def test_compaction_stubs_the_file_bodies_the_model_already_wrote():- """Measured 2026-08-27 (fancy_bl_windsor_chair assemble, 60 turns): 29 write_file- calls were 49 % of a conversation that reached 113 956 input tokens, and every later- turn re-processed all of it. The file is on disk; read_file can fetch it."""- from codeverse.agents.context import compact_messages, message_chars- from codeverse.contracts.chat import ChatMessage, ToolCallPart-- body = "import bpy\n" * 400- msgs = [ChatMessage.user("build a chair")]- for i in range(10):- msgs.append(ChatMessage(role="assistant", parts=[- ToolCallPart(id=f"c{i}", name="write_file",- arguments={"path": f"src/parts/p{i}.py", "content": body})]))- msgs.append(ChatMessage.user(f"wrote p{i}"))- before = message_chars(msgs)- after = message_chars(compact_messages(msgs, keep_recent=4))- assert after < before / 2, f"{before} -> {after}: the written bodies must not survive"- kept = compact_messages(msgs, keep_recent=4)- assert kept[0].text == "build a chair" # the task is never touched- tail_call = next(p for p in kept[-2].parts if isinstance(p, ToolCallPart))- assert tail_call.arguments["content"] == body, "recent turns stay verbatim"diff --git a/harness/tests/agents/test_edit_scope.py b/harness/tests/agents/test_edit_scope.pydeleted file mode 100644index 072bc768..00000000--- a/harness/tests/agents/test_edit_scope.py+++ /dev/null@@ -1,55 +0,0 @@-"""``edit_only``: a refine session may not overwrite part files the round did not name.--Measured 2026-08-25 over 128 judged refine rounds on static objects: the rounds that-REGRESSED had rewritten a median 6 of 9 part files, the rounds that improved 4 of 8, and-the regressions' worst-dropping criterion was structure_plausibility with zero gate errors-— working geometry the task never mentioned was replaced, and nothing deterministic saw-it. The prompt already said "keep everything else as it is"; only the tool can hold it.-"""--from __future__ import annotations--import pytest--from codeverse.agents.api_tools import FileTools, PathDenied---def test_a_scoped_session_cannot_overwrite_a_neighbouring_part(scoped_ws):- ws = scoped_ws- ft = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"], always_writable=["src/model.py"])- assert not ft.write_file("src/parts/seat.py", "# new seat\n").is_error, "the named file is editable"- with pytest.raises(PathDenied) as ei: # the agent loop turns PathDenied into a tool error- ft.write_file("src/parts/leg.py", "# rewritten leg\n")- assert "leg.py" in str(ei.value) and "seat.py" in str(ei.value), "the refusal names the file and the allowed list"- assert (ws.root / "src" / "parts" / "leg.py").read_text() == "# leg\n", "and nothing was written"- assert ft.scope_denials == ["src/parts/leg.py"], "denials are counted so the rate can be measured"---def test_the_entry_file_is_writable_only_by_its_owner(scoped_ws):- """Adding a part means a new file AND an import line in the entry: both must work for- the owner. Without ``always_writable`` (owns_entry=False) the entry is just another- out-of-scope existing file — the api-agent side of CLI entry ownership."""- ws = scoped_ws- ft = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"], always_writable=["src/model.py"])- assert not ft.write_file("src/parts/armrest.py", "# new part\n").is_error- assert not ft.write_file("src/model.py", "# entry + import\n").is_error- assert ft.scope_denials == []- denied = FileTools(ws, ["src", "public"], edit_only=["src/parts/seat.py"])- with pytest.raises(PathDenied):- denied.write_file("src/model.py", "# hijack\n")---def test_no_scope_means_the_old_behaviour(scoped_ws):- """Baseline sessions and unscoped refines (target 'overall') keep the whole tree."""- ft = FileTools(scoped_ws, ["src", "public"])- assert ft.edit_only is None- assert not ft.write_file("src/parts/leg.py", "# fine\n").is_error---def test_scope_never_widens_the_write_roots(scoped_ws):- """edit_only narrows; it must not let a listed path escape src/ or public/."""- ws = scoped_ws- (ws.root / "artifacts").mkdir(exist_ok=True)- ft = FileTools(ws, ["src", "public"], edit_only=["artifacts/x.txt"])- with pytest.raises(PathDenied, match="only allowed under"):- ft.write_file("artifacts/x.txt", "nope")diff --git a/harness/tests/agents/test_read_only.py b/harness/tests/agents/test_read_only.pydeleted file mode 100644index 16702c62..00000000--- a/harness/tests/agents/test_read_only.py+++ /dev/null@@ -1,83 +0,0 @@-"""``AgentJob.read_only`` / ``FileTools(read_only=…)``: a harness-owned file inside the write roots is-readable, never writable.--Measured 2026-08-26 (bench/out/seed_v1, aurora brief, gemini-3.7-flash api-agent, seeding ON): the-``recipes.seeded`` event fired and the finished run's ``src/common.glsl`` carried no seeded block and-no ``curtain(`` — the agent overwrote the file with its own helpers. Verified code the agent can-rewrite is not verified for long; ``src/recipes.glsl`` is therefore a file it can only call into.-"""--from __future__ import annotations--import pytest--from codeverse.agents.api_tools import FileTools, PathDenied-from codeverse.contracts.agent import AgentJob, AgentResult-from codeverse.contracts.common import HARNESS_OWNED_SRC, Language-from codeverse.tracks.generation import GenerationTask, run_agent_task-from codeverse.workspace import Workspace--RECIPES = "src/recipes.glsl"-SEEDED = "// harness-owned\nfloat curtain(vec2 p) { return 0.0; }\n"---def _ws(tmp_path):- ws = Workspace(tmp_path / "run").create()- ws.src.mkdir(parents=True, exist_ok=True)- (ws.src / "recipes.glsl").write_text(SEEDED)- (ws.src / "shader.frag").write_text("void mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(1.0); }\n")- return ws---def test_a_read_only_file_can_be_read_but_not_written_or_edited(tmp_path):- ws = _ws(tmp_path)- ft = FileTools(ws, ["src", "public"], read_only=[RECIPES])- assert ft.read_file(RECIPES).text == SEEDED and not ft.read_file(RECIPES).is_error- with pytest.raises(PathDenied) as ei:- ft.write_file(RECIPES, "float curtain(vec2 p) { return 1.0; }\n")- assert "harness-owned" in str(ei.value) and "call them" in str(ei.value) and RECIPES in str(ei.value)- with pytest.raises(PathDenied, match="harness-owned"):- ft.edit_file(RECIPES, "0.0", "1.0")- assert (ws.src / "recipes.glsl").read_text() == SEEDED, "nothing was written"- assert ft.read_only_denials == [RECIPES, RECIPES] and ft.scope_denials == []- # the agent loop sees a tool error, not an exception; the other files stay writable- out = ft.call("write_file", {"path": RECIPES, "content": "x"})- assert out.is_error and "harness-owned" in out.text- assert not ft.write_file("src/shader.frag", "void mainImage(out vec4 f, in vec2 c) { f = vec4(0.5); }\n").is_error- assert not ft.write_file("src/common.glsl", "float mine(float x) { return x; }\n").is_error---def test_read_only_holds_under_edit_only_too(tmp_path):- """A refine session scoped to the recipe file still cannot write it: read_only beats edit_only."""- ws = _ws(tmp_path)- ft = FileTools(ws, ["src", "public"], edit_only=[RECIPES], always_writable=[RECIPES], read_only=[RECIPES])- with pytest.raises(PathDenied, match="harness-owned"):- ft.write_file(RECIPES, "x")- assert FileTools(ws, ["src"]).read_only == frozenset() and not FileTools(ws, ["src"]).write_file(RECIPES, SEEDED).is_error---class _CaptureAgent:- kind = "fake"- model = "fake"- id = "fake:fake"-- def __init__(self):- self.jobs: list[AgentJob] = []-- def available(self):- return True, "ok"-- def run(self, job: AgentJob) -> AgentResult:- self.jobs.append(job)- return AgentResult(ok=False, exit_reason="completed")--[email protected](("language", "expected"), [("glsl_shader", [RECIPES]), ("blender", []), ("opengl_python", []), ("", [])])-def test_the_job_carries_the_languages_harness_owned_files(tmp_path, language, expected):- ws = _ws(tmp_path)- if language:- ws.write_json(ws.spec_path, {"prompt": "aurora", "track": "graphics" if language != "blender" else "static_object", "language": language})- agent = _CaptureAgent()- run_agent_task(ws, agent=agent, task=GenerationTask(label="baseline", prompt="p", round=0, kind="baseline"), retry_silent_bail=False)- assert agent.jobs[-1].read_only == expected- assert AgentJob(workspace="w", prompt="p").read_only == [] and HARNESS_OWNED_SRC == {Language.GLSL_SHADER: (RECIPES,)}diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.pyindex 387c7931..c3ccf4c2 100644--- a/harness/tests/cost/test_instrument.py+++ b/harness/tests/cost/test_instrument.py@@ -49,8 +49,14 @@ class FakeChat:class FakeAgent:- kind = "api-agent"- model = "gemini:gemini-3.7-flash"+ """A backend whose individual model calls already reach the ledger. Until+ 2026-08-28 the in-process ``api-agent`` was the only one and the KIND decided;+ every shipped backend is a vendor CLI now, so a self-metering backend declares+ itself with ``meters_own_calls`` — that seam is what these tests pin."""++ kind = "self-metering"+ meters_own_calls = True+ model = "gemini:gemini-3.6-flash"def __init__(self, chat, turns: int = 3):self.chat, self.turns, self.seen_turns = chat, turns, 0@@ -74,6 +80,7 @@ class FakeAgent:class CliAgent(FakeAgent):kind = "gemini-cli"+ meters_own_calls = False # a vendor CLI bills as ONE session rowdef run(self, job: AgentJob) -> AgentResult:self.seen_turns = job.max_turns@@ -102,7 +109,7 @@ def test_a_failed_call_is_recorded_and_re_raised(tmp_path: Path):assert row.outcome == "timeout" and row.stage is Stage.PLAN and row.cost_usd == 0.0-def test_api_agent_turns_are_metered_once_each_with_the_job_round(tmp_path: Path):+def test_self_metered_turns_are_recorded_once_each_with_the_job_round(tmp_path: Path):chat = MeteredChatModel(FakeChat())with run_ledger(tmp_path, run="r1"):MeteredAgent(FakeAgent(chat)).run(AgentJob(workspace=str(tmp_path), prompt="p", label="refine",@@ -160,7 +167,7 @@ def test_the_proxy_forwards_everything_else():assert m.id == "gemini:gemini-3.7-flash" and m.provider == "gemini" and m.supports_vision()assert m.pool == "the-key-pool"agent = MeteredAgent(FakeAgent(chat))- assert agent.kind == "api-agent" and agent.available() == (True, "ok")+ assert agent.kind == "self-metering" and agent.available() == (True, "ok")def test_get_chat_model_hands_out_a_metered_model(monkeypatch: pytest.MonkeyPatch):@@ -252,7 +259,8 @@ def test_a_backend_may_declare_that_it_meters_itself(tmp_path: Path):from codeverse.cost.instrument import meters_own_callscli = CliAgent(FakeChat())- assert meters_own_calls(cli) is False and meters_own_calls(FakeAgent(FakeChat())) is True+ assert meters_own_calls(cli) is False # a vendor CLI bills as one session+ assert meters_own_calls(FakeAgent(FakeChat())) is True # ...unless it declares otherwisecli.meters_own_calls = True # type: ignore[attr-defined]assert meters_own_calls(cli) is Truediff --git a/harness/tests/cost/test_profiles.py b/harness/tests/cost/test_profiles.pyindex f75cbbfe..9733aa99 100644--- a/harness/tests/cost/test_profiles.py+++ b/harness/tests/cost/test_profiles.py@@ -164,11 +164,11 @@ def test_an_explicit_flag_beats_the_profile(tmp_path: Path):runs = tmp_path / "runs"r = runner.invoke(app, ["make", "a clay pot", "--runs-dir", str(runs), "--no-run","--profile", "economy", "--rounds", "4", "--max-usd", "9",- "--generator", "api-agent:gemini:gemini-3.7-flash"])+ "--generator", "gemini-cli:gemini-3.6-flash"])assert r.exit_code == 0, r.outputspec = json.loads(next(runs.iterdir()).joinpath("spec.json").read_text())assert spec["budget"]["max_rounds"] == 4 and spec["budget"]["max_usd"] == 9.0- assert spec["backends"]["generator"] == "api-agent:gemini:gemini-3.7-flash"+ assert spec["backends"]["generator"] == "gemini-cli:gemini-3.6-flash"assert spec["backends"]["judge"] == "gemini:gemini-3.7-flash" # unstated → still the profile's@@ -235,12 +235,12 @@ def test_the_flag_and_the_env_var_resolve_to_the_same_dial(name, monkeypatch):"rounds": 2, "candidates": 1, "texture": False,"judge_max_px": 1024, "judge_montages": 3, "judge_detail_crops": 2,"agent_max_turns": 0, "max_usd": 1.50, "max_minutes": 30.0}),- ("balanced", {"generator": "api-agent:gemini:gemini-3.7-flash",+ ("balanced", {"generator": "gemini-cli:gemini-3.6-flash","judge": "gemini:gemini-3.1-pro-preview", "judge_samples": 1,"rounds": 4, "candidates": 1, "texture": False,"judge_max_px": 1024, "judge_montages": 3, "judge_detail_crops": 2,"agent_max_turns": 0, "max_usd": 5.0, "max_minutes": 60.0}),- ("quality", {"generator": "api-agent:gemini:gemini-3.7-flash",+ ("quality", {"generator": "gemini-cli:gemini-3.6-flash","judge": "gemini:gemini-3.1-pro-preview", "judge_samples": 3,"rounds": 4, "candidates": 2, "texture": True,"judge_max_px": 1024, "judge_montages": 3, "judge_detail_crops": 2,diff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.pyindex 2617a284..3dd1fa56 100644--- a/harness/tests/orchestrator_tracks/test_cost_latency.py+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py@@ -129,11 +129,14 @@ def test_every_zone_gets_exactly_one_owner_file():# ----------------------------------------------------------------------------- single-shot assets-def test_single_shot_agent_id_only_derives_from_api_backends():- assert single_shot_agent_id("api-agent:gemini:gemini-3.7-flash") == "single-shot:gemini:gemini-3.7-flash"+def test_single_shot_needs_a_chat_model_not_a_coding_agent():+ """Single-shot is ONE api call for an asset file — the cheap path before a full agent+ session. The coding agent is always a vendor CLI now (2026-08-28), which exposes no+ chat model, so the model comes from the run's planner backend."""+ assert single_shot_agent_id("gemini-cli:gemini-3.6-flash", "gemini:gemini-3.6-flash") == "single-shot:gemini:gemini-3.6-flash"assert single_shot_agent_id("single-shot:gemini:x") == "single-shot:gemini:x"- assert single_shot_agent_id("gemini-cli:gemini-3.7-flash") == "" # CLI subscription: no chat model- assert single_shot_agent_id("claude-code:opus") == "" and single_shot_agent_id("fake:x") == ""+ assert single_shot_agent_id("gemini-cli:gemini-3.6-flash") == "" # no chat model given+ assert single_shot_agent_id("claude-code:opus", "not-an-id") == "" # not '<provider>:<model>'class _ChatServices(FakeServices):diff --git a/harness/tests/skills/test_delivery.py b/harness/tests/skills/test_delivery.pyindex 7b9ae0f1..26476816 100644--- a/harness/tests/skills/test_delivery.py+++ b/harness/tests/skills/test_delivery.py@@ -26,10 +26,12 @@ def test_a_native_loader_is_never_handed_a_second_index():def test_a_loaderless_backend_gets_both_the_index_and_the_tool():- """Measured 2026-08-25: the three native loaders read 5 of 5 routed bundles; api-agent- read 0 of 5 from a MANDATORY paragraph while making 52 read_file calls. Prose is not- an affordance, so a backend without a loader gets the routed set as a tool."""- d = delivery_for("api-agent")+ """Measured 2026-08-25: the native loaders read 5 of 5 routed bundles while a+ loaderless backend read 0 of 5 from a MANDATORY paragraph, making 52 read_file calls+ instead. Prose is not an affordance. Every SHIPPED backend has a native loader+ since the in-process one was deleted (2026-08-28), so this is the policy for a+ backend nobody has classified."""+ d = delivery_for("some-future-cli")assert not d.native_loader and d.needs_index and d.needs_tool@@ -44,14 +46,14 @@ def test_an_unclassified_backend_gets_the_safe_answer():def test_a_qualified_kind_resolves_to_its_backend():"""`codex:gpt-5.6-sol` is codex; the model suffix must not fall through to unknown."""assert delivery_for("codex:gpt-5.6-sol") == delivery_for("codex")- assert delivery_for("api-agent:gemini:gemini-3.7-flash") == delivery_for("api-agent")+ assert delivery_for("gemini-cli:gemini-3.6-flash") == delivery_for("gemini-cli")def test_claude_code_reads_its_own_root_and_nobody_else_does():"""Read out of the shipped binaries, not assumed: claude-code 2.1 has no `.agents`skill root at all, and the other three have no `.claude` one."""assert delivery_for("claude-code").root == CLAUDE_SKILL_ROOT- for kind in ("codex", "gemini-cli", "agy", "api-agent"):+ for kind in ("codex", "gemini-cli", "agy"):assert delivery_for(kind).root == AGENTS_SKILL_ROOT, kind@@ -71,7 +73,7 @@ def test_adding_a_backend_is_one_row():import pathlibroot = pathlib.Path(__file__).resolve().parents[2] / "codeverse"- names = ("claude-code", "gemini-cli", "api-agent")+ names = ("claude-code", "gemini-cli", "codex")offenders = []for py in (root / "skills").rglob("*.py"):if py.name in ("delivery.py", "prompting.py"):@@ -83,61 +85,9 @@ def test_adding_a_backend_is_one_row():# ------------------------------------------------------------------ the read_skill tool-def _workspace_with_skills(tmp_path, agent_kind="api-agent"):- from codeverse.agents.materialize import materialize_workspace- from codeverse.skills import attach_skills- from codeverse.workspace import Workspace-- ws = Workspace(tmp_path / "ws")- ws.create()- materialize_workspace(ws, agent_kind=agent_kind, contract_md="(contract)",- cookbook_rel=".c3v/cookbook.md", spatial_tools=False, mcp_command=[])- attach_skills(ws.root, track="static_object", language="blender", kind="baseline",- agent_kind=agent_kind)- return ws---def test_the_tool_discovers_the_routed_set_off_the_workspace(tmp_path):- """Not threaded through AgentJob: the bundles are already on disk for this round, so- the tool reads what was actually written and cannot disagree with it."""- from codeverse.agents.api_skills import SkillTools-- st = SkillTools(_workspace_with_skills(tmp_path))- assert st.listed, "nothing discovered"- spec = st.specs()[0]- assert spec.name == "read_skill"- assert spec.parameters["properties"]["name"]["enum"] == st.listed- for name in st.listed:- assert name in spec.description, "the model must be able to choose without opening one"---def test_the_read_control_is_never_offered(tmp_path):- """It exists to catch a probe reporting a read nobody made; offering it would invite- exactly that."""- from codeverse.agents.api_skills import SkillTools- from codeverse.skills.materialize import CONTROL_NAME-- assert CONTROL_NAME not in SkillTools(_workspace_with_skills(tmp_path)).listed---def test_reading_records_ground_truth_and_rejects_an_unrouted_name(tmp_path):- from codeverse.agents.api_skills import SkillTools-- st = SkillTools(_workspace_with_skills(tmp_path))- first = st.listed[0]- out = st.read_skill(first)- assert not out.is_error and len(out.text) > 200- assert st.reads == [first], "the read rate needs ground truth, not a probe"- bad = st.read_skill("cv3d-not-routed")- assert bad.is_error and "not routed" in bad.text- assert st.reads == [first], "a rejected call must not count as a read"---def test_a_workspace_with_no_skills_advertises_no_tool(tmp_path):- """The feature being off must not leave a tool that always errors."""- from codeverse.agents.api_skills import SkillTools- from codeverse.workspace import Workspace-- ws = Workspace(tmp_path / "bare")- ws.create()- assert SkillTools(ws).specs() == []+++# The in-process skill-reading TOOL (agents/api_skills.py) went with the api-agent on+# 2026-08-28: every remaining backend is a vendor CLI with a native loader, so a bundle+# is delivered as files and read by the vendor's own mechanism. The four tests that+# drove that tool are gone with it; delivery_for() above still pins the routing policy.