Official Codebase of 3DCodeVerse
Python
tests: skills, prompts, scene_prompts, languages — 104 tests go that cover no line another test does not (−893 lines)
gaoypeng0e7be30520a6
diff --git a/harness/tests/languages/test_ast_lint.py b/harness/tests/languages/test_ast_lint.pyindex 776ecc31..818fb153 100644--- a/harness/tests/languages/test_ast_lint.py+++ b/harness/tests/languages/test_ast_lint.py@@ -2,39 +2,25 @@from __future__ import annotations-import ast-import codeverse3d.languages.blender as blender_lintimport codeverse3d.languages.cadquery as cadquery_lintimport codeverse3d.languages.opengl_python as opengl_lintimport codeverse3d.languages.urdf as urdf_lint-from codeverse3d.contracts.artifacts import GateFinding, Severity-from codeverse3d.languages._ast_lint import BASE_FORBIDDEN_IMPORTS, check_imports, dotted--# ----------------------------------------------------------------- superset (drift fails here)---def test_base_forbidden_imports_shape() -> None:- assert len(BASE_FORBIDDEN_IMPORTS) == 14- # blender legitimately allows os/sys — the base set must never grow them- assert "os" not in BASE_FORBIDDEN_IMPORTS and "sys" not in BASE_FORBIDDEN_IMPORTS- assert {"subprocess", "webbrowser", "ftplib", "smtplib", "importlib"} <= BASE_FORBIDDEN_IMPORTS+from codeverse3d.contracts.artifacts import Severity+from codeverse3d.languages._ast_lint import BASE_FORBIDDEN_IMPORTSdef test_language_forbidden_sets_are_supersets_of_base() -> None:assert BASE_FORBIDDEN_IMPORTS <= blender_lint.FORBIDDEN_IMPORTSassert BASE_FORBIDDEN_IMPORTS <= cadquery_lint.FORBIDDEN_IMPORTSassert BASE_FORBIDDEN_IMPORTS <= opengl_lint.DANGEROUS_MODULES- assert BASE_FORBIDDEN_IMPORTS <= urdf_lint.FORBIDDEN_IMPORTS # was a hand-copied subset until 2026-08-29---def test_language_specific_extras_survive() -> None:+ assert BASE_FORBIDDEN_IMPORTS <= urdf_lint.FORBIDDEN_IMPORTSassert "pathlib" in blender_lint.FORBIDDEN_IMPORTSassert {"os", "sys", "OCP", "build123d"} <= cadquery_lint.FORBIDDEN_IMPORTSassert {"os", "sys", "time", "datetime", "io", "tempfile", "signal"} <= opengl_lint.DANGEROUS_MODULES# blender's documented allowance: os/sys stay importable (call rules catch abuse)assert {"os", "sys"} <= blender_lint.ALLOWED_IMPORTS- assert not ({"os", "sys"} & blender_lint.FORBIDDEN_IMPORTS)+ assert not ({"os", "sys"} & (blender_lint.FORBIDDEN_IMPORTS | BASE_FORBIDDEN_IMPORTS))def test_base_modules_error_in_every_language_lint() -> None:@@ -58,69 +44,10 @@ def test_base_modules_error_in_every_language_lint() -> None:assert any(f.severity == Severity.WARN and "'os'" in f.message for f in findings)-# ----------------------------------------------------------------- check_imports / dotted---def _mk(kind: str, mod: str, line: int) -> GateFinding:- return GateFinding(gate="lint:test", severity=Severity.ERROR if kind == "forbidden" else Severity.WARN,- message=f"{kind}:{mod}", data={"line": line})---def test_check_imports_routes_forbidden_unexpected_allowed() -> None:- out = check_imports({"subprocess": 1, "mystery": 2, "math": 3},- forbidden=frozenset({"subprocess"}), allowed=frozenset({"math"}), make_finding=_mk)- assert [(f.message, f.severity) for f in out] == [- ("forbidden:subprocess", Severity.ERROR), ("unexpected:mystery", Severity.WARN)]- assert [f.data["line"] for f in out] == [1, 2]---def test_dotted_chains() -> None:- def expr(src: str) -> ast.AST:- return ast.parse(src, mode="eval").body-- assert dotted(expr("bpy.ops.render.render")) == "bpy.ops.render.render"- assert dotted(expr("name")) == "name"- assert dotted(ast.parse("wp.box(1).rotate", mode="eval").body) == "<expr>.rotate"- assert dotted(expr("(a + b)")) == ""- # the same function is what the language lints re-export- assert blender_lint.dotted is dotted and cadquery_lint.dotted is dotted---# ----------------------------------------------------------------------------- safe_parse (2026-08-25)-def test_safe_parse_turns_parser_crashes_into_findings(monkeypatch):- """compare_v4_calm: a generated bpy file made CPython 3.11's ``ast.parse`` raise- ``SystemError: AST constructor recursion depth mismatch`` and the whole harness round- died in ``build_once``. Every python lint now goes through ``safe_parse`` and reports- a lint ERROR the agent can act on instead."""- import ast-- from codeverse3d.languages._ast_lint import describe_parse_failure, safe_parse-- tree, exc = safe_parse("x = 1\n")- assert isinstance(tree, ast.Module) and exc is None- tree, exc = safe_parse("x = (\n", "src/model.py")- assert tree is None and isinstance(exc, SyntaxError)- msg, hint, line = describe_parse_failure(exc)- assert msg.startswith("SyntaxError:") and "fix the syntax near line" in hint-- def boom(*a, **k):- raise SystemError("AST constructor recursion depth mismatch (before=54, after=62)")-- monkeypatch.setattr(ast, "parse", boom)- tree, exc = safe_parse("x = 1\n")- assert tree is None and isinstance(exc, SystemError)- msg, hint, line = describe_parse_failure(exc)- assert "SystemError" in msg and "deeper than the parser" in msg and "flatten" in hint and line is None- tree, exc = safe_parse("x = 1\n") # RecursionError / MemoryError take the same path- monkeypatch.setattr(ast, "parse", lambda *a, **k: (_ for _ in ()).throw(RecursionError("maximum recursion depth exceeded")))- tree, exc = safe_parse("x = 1\n")- assert tree is None and isinstance(exc, RecursionError)--def test_every_python_lint_survives_a_parser_crash(monkeypatch):+ """A parser crash (SystemError on 3.11, compare_v4_calm) is a lint ERROR, not a dead round."""import ast- from codeverse3d.contracts.artifacts import Severityfrom codeverse3d.languages.blender import lint_blender_sourcefrom codeverse3d.languages.cadquery import lint_cadquery_sourcefrom codeverse3d.languages.opengl_python import lint_source as lint_gl@@ -141,7 +68,7 @@ def test_every_python_lint_survives_a_parser_crash(monkeypatch):("urdf", lambda: lint_model_text(src, ["base"]))):findings = run() # must not raiseerrs = [f for f in findings if f.severity == Severity.ERROR]- assert errs and "SystemError" in errs[0].message, (name, findings)+ assert errs and "deeper than the parser" in errs[0].message, (name, findings)def test_real_deeply_nested_source_does_not_escape_the_lint():@@ -152,15 +79,3 @@ def test_real_deeply_nested_source_does_not_escape_the_lint():deep = "import bpy\nx = " + " + ".join(["1"] * 40_000) + "\n"rep = lint_blender_source(deep)assert isinstance(rep.passed, bool)---def test_the_runtime_registry_covers_every_language():- """get_runtime was a 7-branch if-chain whose last arm was an unreachable- fall-through; as a table, a missing row is a KeyError at call time instead. This- is the drift guard that makes the table safe."""- from codeverse3d.contracts.common import Language- from codeverse3d.languages.base import _RUNTIMES, get_runtime-- assert set(_RUNTIMES) == set(Language), "every Language needs a runtime row"- for lang in Language:- assert get_runtime(lang).language is langdiff --git a/harness/tests/languages/test_gl_common_entry.py b/harness/tests/languages/test_gl_common_entry.pyindex 3d5cde10..41007fb3 100644--- a/harness/tests/languages/test_gl_common_entry.py+++ b/harness/tests/languages/test_gl_common_entry.py@@ -1,8 +1,7 @@-"""_gl_common consolidation + ENTRY_FILE adoption across the language runtimes (offline)."""+"""_gl_common.make_host (offline)."""from __future__ import annotations-from codeverse3d.contracts.common import ENTRY_FILE, Languagefrom codeverse3d.languages import _gl_commonfrom codeverse3d.spatial.gl_render import GlHost@@ -12,17 +11,3 @@ def test_make_host_prefers_injected_host() -> None:assert _gl_common.make_host(injected, 99.0) is injectedbuilt = _gl_common.make_host(None, 7.5)assert isinstance(built, GlHost) and built is not injected---def test_runtimes_lead_with_the_entry_file_table() -> None:- from codeverse3d.languages.blender import ENTRY_REL, BlenderRuntime- from codeverse3d.languages.cadquery import CadQueryRuntime- from codeverse3d.languages.glsl_shader import GlslShaderRuntime- from codeverse3d.languages.opengl_python import OpenGLPythonRuntime- from codeverse3d.languages.threejs import ThreeJsRuntime- from codeverse3d.languages.urdf import UrdfBlenderRuntime-- assert ENTRY_FILE[Language.BLENDER] == ENTRY_REL- for rt in (BlenderRuntime, CadQueryRuntime, GlslShaderRuntime, OpenGLPythonRuntime,- ThreeJsRuntime, UrdfBlenderRuntime):- assert rt.entry_globs[0] == ENTRY_FILE[rt.language], rt.__name__diff --git a/harness/tests/prompts/test_files.py b/harness/tests/prompts/test_files.pyindex 9da95db0..bf694b7b 100644--- a/harness/tests/prompts/test_files.py+++ b/harness/tests/prompts/test_files.py@@ -8,10 +8,10 @@ from fnmatch import fnmatchimport jinja2import pytest-from codeverse3d.contracts.common import TRACK_LANGUAGES, Language, Track+from codeverse3d.contracts.common import Languagefrom codeverse3d.prompts import load_text, renderfrom codeverse3d.prompts.catalog import language_prompt-from tests.prompts.conftest import DOC_FILES, PROMPT_FILES, PROMPTS_DIR, is_template, read_prompt+from tests.prompts.conftest import PROMPT_FILES, PROMPTS_DIR, is_template, read_prompt#: files nothing in the package loads, each with the reason it still shipsUNREACHED = {@@ -53,27 +53,6 @@ def test_every_prompt_file_is_reached_by_the_package() -> None:assert set(PROMPT_FILES) - reached == UNREACHED[email protected]("rel", [f for f in DOC_FILES if f.endswith("cookbook.md")])-def test_cookbook_structure(rel: str) -> None:- text = read_prompt(rel)- headings = [line[3:].strip() for line in text.splitlines() if line.startswith("## ")]- assert len(headings) >= 5, f"{rel}: cookbooks are chaptered with '## ' headings"- assert len(headings) == len(set(headings)), f"{rel}: duplicate section headings"- assert "pitfalls" in " | ".join(headings).lower(), f"{rel}: needs a Pitfalls chapter"--- # a shader draws in screen space: it has no metres and no 3D frame to state- "rel", sorted(language_prompt(lang, "contract.md") for t, langs in TRACK_LANGUAGES.items() if t is not Track.GRAPHICS- for lang in langs)-)-def test_contract_content(rel: str) -> None:- text = read_prompt(rel)- assert "COMPLETE minimal example" in text, f"{rel}: must carry a complete runnable example"- low = text.lower()- assert "meter" in low or "metre" in low, f"{rel}: units must be stated"--def test_frames_consistent_with_conventions() -> None:"""Contracts restate the frame; they must agree with conventions.py (Z-up −Y-frontfor blender/cadquery/urdf, Y-up +Z-front for the three.js languages)."""@@ -87,25 +66,8 @@ def test_frames_consistent_with_conventions() -> None:assert "+Z front" in text or "+Z is the front" in text, f"{rel}: must state +Z front"-def test_system_prompts_cover_the_laws() -> None:- hc = read_prompt("system/harness_contract.md")- for needle in ("artifacts/", "render_sheet", "check_connectivity", "2 mm",- "Definition of done", "ground", "seed"):- assert needle.lower() in hc.lower(), f"harness_contract.md must mention {needle!r}"--def test_every_language_ships_a_system_prompt_a_contract_and_a_cookbook() -> None:- """The generator's system prompt, the authoring contract and the cookbook are per- LANGUAGE and live in the prompt corpus, found by ``prompts.catalog.language_prompt``.-- The system prompt used to be an f-string in each track class, and the three static-object- languages shared one sentence with the name swapped in — bpy mesh modelling,- CadQuery's B-rep workplanes and three.js BufferGeometry, told the same thing.- A missing file here means a language silently falls back to nothing (``language_text``- reads a file a language does not ship as "").- """- from codeverse3d.contracts.common import Language- from codeverse3d.prompts.catalog import language_prompt+ """A missing per-language file silently reads as "" through ``language_text``."""from codeverse3d.tracks.prompting import language_system_promptfor lang in Language:diff --git a/harness/tests/prompts/test_snippets_static.py b/harness/tests/prompts/test_snippets_static.pyindex f24ee115..87ef5ecf 100644--- a/harness/tests/prompts/test_snippets_static.py+++ b/harness/tests/prompts/test_snippets_static.py@@ -1,81 +1,18 @@-"""Static validity of every fenced snippet: python parses, XML/URDF parses, JS parses."""+"""Static checks on fenced snippets the run tests cannot see: URDF frame recipe, GLSL-in-JS, the single-shot format."""from __future__ import annotations-import astimport re-import shutil-import subprocessimport xml.etree.ElementTree as ETimport numpy as npimport pytest-from tests.prompts.conftest import DOC_FILES, blocks, read_prompt+from tests.prompts.conftest import blocks, read_prompt-PY_FILES = [f for f in DOC_FILES if f.split("/")[0] in ("blender", "cadquery", "urdf")]-JS_FILES = [f for f in DOC_FILES if f.split("/")[0] in ("threejs", "scene_threejs")]XML_FILES = ["urdf/contract.md", "urdf/cookbook.md"][email protected]("rel", PY_FILES)-def test_python_blocks_parse(rel: str) -> None:- found = 0- for i, body in enumerate(blocks(rel, "python")):- try:- ast.parse(body)- except SyntaxError as e: # pragma: no cover - failure path- pytest.fail(f"{rel} python block {i} does not parse: {e}")- found += 1- assert found > 0, f"{rel}: expected at least one python block"--[email protected]("rel", XML_FILES)-def test_xml_blocks_are_valid_urdf(rel: str) -> None:- found = 0- for i, body in enumerate(blocks(rel, "xml")):- root = ET.fromstring(body)- assert root.tag == "robot" and root.get("name"), f"{rel} xml block {i}: not a <robot>"- links = {ln.get("name") for ln in root.findall("link")}- children = set()- for j in root.findall("joint"):- jtype = j.get("type")- parent = j.find("parent").get("link")- child = j.find("child").get("link")- assert parent in links and child in links, f"{rel} block {i}: joint {j.get('name')} references unknown link"- assert child not in children, f"{rel} block {i}: link {child} has two parents"- children.add(child)- origin = j.find("origin")- assert origin is not None and origin.get("rpy", "0 0 0").split() == ["0", "0", "0"], \- f"{rel} block {i}: joint {j.get('name')} must have rpy='0 0 0' (frame recipe)"- limit = j.find("limit")- if jtype in ("revolute", "prismatic"):- assert limit is not None and limit.get("lower") is not None and limit.get("upper") is not None, \- f"{rel} block {i}: {jtype} joint {j.get('name')} needs lower/upper"- assert float(limit.get("lower")) < float(limit.get("upper"))- if jtype == "continuous":- assert limit is None or (limit.get("lower") is None and limit.get("upper") is None)- axis = j.find("axis")- if jtype != "fixed":- v = [float(x) for x in axis.get("xyz").split()]- assert abs(sum(a * a for a in v) - 1.0) < 1e-6, f"{rel} block {i}: non-unit axis on {j.get('name')}"- roots = links - children- assert len(roots) == 1, f"{rel} block {i}: expected a single root link, got {roots}"- for ln in root.findall("link"):- vis, col = ln.findall("visual"), ln.findall("collision")- assert len(vis) == 1 and len(col) == 1, f"{rel} block {i}: link {ln.get('name')} needs one <visual> + one <collision>"- vo, co = vis[0].find("origin"), col[0].find("origin")- assert vo is not None and co is not None and vo.get("xyz") == co.get("xyz"), \- f"{rel} block {i}: link {ln.get('name')}: collision origin must equal the visual origin"- for tag in (vis[0], col[0]):- mesh = tag.find("geometry/mesh")- assert mesh is not None and mesh.get("filename") == f"meshes/{ln.get('name')}.glb", \- f"{rel} block {i}: link {ln.get('name')} must reference meshes/<link>.glb"- assert mesh.get("scale") is None, f"{rel} block {i}: mesh scale is forbidden"- found += 1- assert found > 0, f"{rel}: expected at least one xml block"--def _is_template(body: str) -> bool:"""Fill-in skeletons carry symbolic origins (``PX PY PZ``) — not FK-checkable."""return any(not _NUM.match(tok) for el in ET.fromstring(body).iter("origin") for tok in el.get("xyz", "0 0 0").split())@@ -110,21 +47,6 @@ def test_xml_examples_follow_the_enforced_frame_recipe(rel: str, tmp_path) -> Noassert checked > 0, f"{rel}: expected at least one FK-checkable xml block"[email protected]("rel", JS_FILES)-def test_js_blocks_syntax(rel: str, tmp_path) -> None:- node = shutil.which("node")- if node is None:- pytest.skip("node not available")- bs = blocks(rel, "js")- assert bs, f"{rel}: expected at least one js block"- for i, body in enumerate(bs):- p = tmp_path / f"block_{i}.mjs"- p.write_text(body)- proc = subprocess.run([node, "--check", str(p)], capture_output=True, text=True, timeout=30)- assert proc.returncode == 0, f"{rel} js block {i} syntax error:\n{proc.stderr[-1500:]}"--def test_glsl_strings_are_sane() -> None:"""GLSL lives inside JS template strings; audit the obvious silent killersINSIDE the js code blocks (prose may mention them as pitfalls)."""diff --git a/harness/tests/scene_prompts/test_prompt_assembler_contract.py b/harness/tests/scene_prompts/test_prompt_assembler_contract.pyindex ef6ca028..a1c73e8f 100644--- a/harness/tests/scene_prompts/test_prompt_assembler_contract.py+++ b/harness/tests/scene_prompts/test_prompt_assembler_contract.py@@ -44,23 +44,14 @@ def test_generated_scene_js_is_what_we_think_it_is(generated: str) -> None:assert "tickEnv" not in generated and "userData.tick" not in generated-def test_zone_prompt_teaches_the_export_and_hook_the_assembler_calls(zone_prompt: str) -> None:- assert "export function build(ctx)" in zone_prompt- assert "userData.update" in zone_prompt- # the historical bug: the prompt asked for `userData.tick`, a hook nothing calls.- # It may only appear now as an explicit warning.- for line in zone_prompt.splitlines():- if "userData.tick" in line:- assert "never called" in line, f"zone prompt still advertises userData.tick: {line!r}"---def test_env_prompt_teaches_ctx_signature_and_update(env_prompt: str) -> None:- assert "buildEnv(ctx)" in env_prompt- assert "buildEnv(THREE, scene)" not in env_prompt- assert "update(t, dt)" in env_prompt- assert "tickEnv" in env_prompt and "NEVER called" in env_prompt- # the assembler greps this out of env.js to place the overview cameras- assert "SUN_AZIMUTH_DEG" in env_prompt+def test_the_prompts_teach_the_hooks_the_assembler_calls(zone_prompt: str, env_prompt: str) -> None:+ assert "export function build(ctx)" in zone_prompt and "userData.update" in zone_prompt+ # the historical bug: `userData.tick`, a hook nothing calls, may appear only as a warning+ assert all("never called" in ln for ln in zone_prompt.splitlines() if "userData.tick" in ln)+ assert "buildEnv(ctx)" in env_prompt and "buildEnv(THREE, scene)" not in env_prompt+ assert "update(t, dt)" in env_prompt and "tickEnv" in env_prompt and "NEVER called" in env_prompt+ asset = load_text("tracks/scene_asset.j2")+ assert "group.userData.update" in asset and "`userData.tick` is never called" in assetdef test_env_prompt_sun_azimuth_matches_the_assembler_regex(env_prompt: str) -> None:@@ -69,9 +60,3 @@ def test_env_prompt_sun_azimuth_matches_the_assembler_regex(env_prompt: str) ->example = re.search(r"`?export const SUN_AZIMUTH_DEG[^`\n]*", env_prompt)assert example, "env prompt must show the export the assembler looks for"assert _SUN_RE.search("export const SUN_AZIMUTH_DEG = 235;")---def test_asset_prompt_uses_the_hook_zones_can_forward() -> None:- text = load_text("tracks/scene_asset.j2")- assert "group.userData.update" in text- assert "`userData.tick` is never called" in textdiff --git a/harness/tests/scene_prompts/test_quality_teaching.py b/harness/tests/scene_prompts/test_quality_teaching.pyindex 496ddb9d..0e2698f3 100644--- a/harness/tests/scene_prompts/test_quality_teaching.py+++ b/harness/tests/scene_prompts/test_quality_teaching.py@@ -1,99 +1,23 @@-"""What the scene prompts, cookbook and rubric must TEACH about picture quality.--Every item here maps to a defect the v1 bench judges actually wrote up (flat ground,-identical cones, hard world edge, diorama-on-a-plane, undressed, monochrome light,-invisible motion). The tests are cheap guards that the teaching does not silently-disappear from a prompt during a refactor.-"""+"""What the scene rubric scores and the prompts inline about picture quality (v1 bench defects)."""from __future__ import annotations-import pytest-from codeverse3d.judges.rubrics import load_rubricfrom codeverse3d.prompts import load_text-[email protected](scope="module")-def cookbook() -> str:- return load_text("scene_threejs/cookbook.md")---def test_cookbook_carries_the_numbers_the_recipes_depend_on(cookbook: str) -> None:- for token in ("vertexColors", "setColorAt", "InstancedMesh", "shadow.mapSize",- "cameraMask", "buildHorizonRing", "TIME_OF_DAY", "hazeMix"):- assert token in cookbook, token---def test_planner_asks_for_density_layering_and_subject_framing() -> None:- text = load_text("tracks/plan_scene.j2")- for token in ("DENSITY COUNTS", "DEPTH ROLE", "foreground frame", "silhouette ring",- "HERO motion", "fill hue", "SUBJECT"):- assert token in text, token---def test_planner_is_told_that_must_acceptance_caps_the_run() -> None:- """One unmet `must` caps the run at 0.60 (judges.caps.missing_must_acceptance). A scene- whose pictures score 0.81 must not lose 0.13 because the planner over-specified a detail- and then marked it `must` — measured on cq_japanese_garden_v2 r00 (0.809 → 0.729 → 0.60)."""- from codeverse3d.judges.rubrics import load_rubric-- caps = {c.id: c for c in load_rubric("scene_v1").caps}- assert caps["missing_must_acceptance"].cap == 0.60- text = load_text("tracks/plan_scene.j2")- assert "priority: should" in text- assert "caps the whole run" in text or "caps the\n whole run" in text- assert "at most 4-6 items `must`" in text---def test_zone_prompt_demands_variation_dressing_and_visible_motion() -> None:- text = load_text("tracks/scene_zone.j2")- for token in ("3 distinct silhouettes", "hue jitter", "density counts",- "foreground frame", "nothing_moves", "cameraMask"):- assert token in text, token---def test_env_prompt_demands_blended_ground_horizon_and_colour_contrast() -> None:- text = load_text("tracks/scene_env.j2")- for token in ("flat_ground", "silhouette ring", "fog far", "60", "Shadow texel"):- assert token in text, token---def test_refine_prompt_maps_judge_complaints_to_chapters() -> None:- text = load_text("tracks/scene_refine.j2")- for title in ("Ground that reads real", "Horizon: the world must not end",- "Vegetation that reads real", "Set dressing", "Scene layering",- "Atmosphere: time-of-day triads", "Motion you can SEE"):- assert title in text, title---# --------------------------------------------------------------------------- rubricCOMPOSITION_DEFECTS = ("flat_ground", "monotonous_vegetation", "empty_midground","undressed_scene", "thin_atmosphere")-def test_scene_rubric_scores_the_composition_defects() -> None:+def test_scene_rubric_craft_defects_inform_and_cannot_zero_a_scene() -> None:r = load_rubric("scene_v1")- ids = {d.id for d in r.defects}- assert set(COMPOSITION_DEFECTS) <= ids+ assert set(COMPOSITION_DEFECTS) <= {d.id for d in r.defects}for did in COMPOSITION_DEFECTS:d = r.defect(did)- assert 0.0 < d.penalty <= 0.05, f"{did}: keep the new craft penalties small"- assert d.cap is None, f"{did}: craft defects inform, they do not cap"---def test_scene_rubric_penalties_cannot_zero_a_good_scene() -> None:- r = load_rubric("scene_v1")+ assert 0.0 < d.penalty <= 0.05 and d.cap is None, didassert sum(d.penalty for d in r.defects) <= 0.62-def test_scene_rubric_has_the_diorama_anchor() -> None:- r = load_rubric("scene_v1")- comp = r.criterion("composition_and_camera")- assert "0.5" in comp.anchors and "diorama" in comp.anchors["0.5"].lower()- assert "foreground" in comp.anchors["1.0"].lower()--def test_extra_anchor_levels_reach_the_judge_prompt() -> None:from codeverse3d.judges.prompt_builder import _rubric_block@@ -104,11 +28,8 @@ def test_extra_anchor_levels_reach_the_judge_prompt() -> None:assert idx == sorted(idx)-# --------------------------------------------------------------------------- deliverydef test_the_quality_chapters_travel_INSIDE_the_zone_and_env_prompts() -> None:- """Naming a chapter is not teaching it: on scenes_v1 not one of the 20 zone/env- sessions fetched cookbook chapters on demand, so the chapters that decide the score are inlined- into the brief itself (`tracks.prompting.cookbook_sections`)."""+ """The chapters that decide the score are inlined into the brief (no session fetched them on demand)."""from codeverse3d.tracks.scene import ENV_RECIPES, ZONE_RECIPEScookbook = load_text("scene_threejs/cookbook.md")@@ -140,9 +61,7 @@ def test_cookbook_sections_inlines_whole_chapters_and_clips_safely(tmp_path) ->def test_the_env_and_zone_briefs_hand_the_enclosure_to_env_for_an_interior() -> None:- """2026-09-07: six interior runs were "not enclosed" because no brief said whose the walls- are. The env brief claims them (and the openings, and the light) only when the plan- says interior; the zone brief forbids building them and puts fixtures flush to the bounds."""+ """Six interior runs were "not enclosed": the env brief owns the walls only when the plan says interior."""from codeverse3d.prompts import renderbase = dict(title="t", spec_prompt="p", setting="s", mood="m", bounds="b", environment="e", frame_doc="", contract="",@@ -157,18 +76,3 @@ def test_the_env_and_zone_briefs_hand_the_enclosure_to_env_for_an_interior() ->zone_out = render("tracks/scene_zone.j2", **base, interior=False)assert "never build walls or a roof" in zone_in and "flush against the inner face" in zone_inassert "never build walls" not in zone_out---def test_the_zone_brief_says_builders_are_already_at_size() -> None:- """2026-09-08 (loop 14 round 0): a 1.15 m stove placed at 3.60 m and 0.48 m lamps at 0.03 m —- the asset API states every size, and nothing told the zone author to place at scale 1."""- from codeverse3d.prompts import render-- base = dict(title="t", spec_prompt="p", setting="s", mood="m", bounds="b", environment="e", frame_doc="", contract="",- zones_table="", cameras="", effects="", animation="", asset_api="", textures="", recipes="", constraints_text="",- references="", skills="", tool_cards="", zone_name="Z", zone_description="d", zone_bbox="bb", zone_contents=["Stove"],- zone_file="src/zones/z.js", neighbours=[], layout="", interior=False)- text = render("tracks/scene_zone.j2", **base)- assert "place it at scale 1" in text and "> 2.5x or < 0.4x is an ERROR" in text- # three runs (codex1, loop 14, loop 18) lost a round to a hero whose flue a zone stretched to the roof- assert "never stretch or re-scale a part of a placed clone" in text and "SEPARATE object" in textdiff --git a/harness/tests/skills/test_config.py b/harness/tests/skills/test_config.pyindex 1ae8c29e..5c900ce9 100644--- a/harness/tests/skills/test_config.py+++ b/harness/tests/skills/test_config.py@@ -1,9 +1,4 @@-"""The skill switches are ``Settings`` fields: ON by default, tolerant of garbage, live.--``tracks/plan_features.py`` exists because a wave A/B'd a switch nothing read and printed-"keep, mean delta +0.344" for two byte-identical arms. These tests are what keep-``C3D_SKILLS`` from becoming that switch.-"""+"""The skill switches are ``Settings`` fields: ON by default, tolerant of garbage, live (never a dead A/B switch)."""from __future__ import annotations@@ -21,27 +16,14 @@ def _settings(monkeypatch, **env: str) -> Settings:return Settings()-def test_on_by_default(monkeypatch):- """Flipped 2026-09-22 (owner): every backend is a vendor CLI with a native skill loader,- and the whole library routes — the cap of 5 per session is the cost knob, not the switch."""- s = _settings(monkeypatch)- assert (s.skills, s.skills_unverified, s.skills_max) == (True, True, 5)--[email protected]("raw, want", [("on", True), ("1", True), ("true", True), ("YES", True),- ("off", False), ("0", False), ("no", False), ("", True),- ("maybe", True)])-def test_flag_spellings(monkeypatch, raw, want):- """Unset or empty is the default (ON); garbage warns and keeps the default — a typo in- a bench command runs the arm that never set it, never a crash (D44 c)."""- assert _settings(monkeypatch, C3D_SKILLS=raw).skills is want---def test_unverified_can_still_be_turned_off(monkeypatch):- assert _settings(monkeypatch, C3D_SKILLS_UNVERIFIED="0").skills_unverified is False[email protected]("raw, want", [("off", False), ("", True), ("maybe", True)])+def test_on_by_default_and_garbage_keeps_the_default(monkeypatch, raw, want):+ """Default ON (D-rule, owner 2026-09-22); garbage warns and keeps it, never a crash (D44 c)."""+ s = _settings(monkeypatch, C3D_SKILLS=raw)+ assert (s.skills, s.skills_unverified, s.skills_max) == (want, True, 5)[email protected]("raw, want", [("3", 3), ("0", 0), ("-1", 5), ("nope", 5), ("", 5)])[email protected]("raw, want", [("3", 3), ("-1", 5), ("nope", 5)])def test_max_is_never_a_crash(monkeypatch, raw, want):assert _settings(monkeypatch, C3D_SKILLS_MAX=raw).skills_max == want@@ -52,8 +34,7 @@ def test_the_switches_are_live():def test_doctor_reports_the_default_and_the_gemini_pin(monkeypatch):- """`3dcode doctor --skills`: ON is the healthy state now, and gemini-cli's skills.enabled- must be pinned in the per-session system settings (a user file could turn it off)."""+ """ON is healthy, and gemini-cli's skills.enabled must be pinned per session."""from codeverse3d.doctor import check_skillsmonkeypatch.delenv("C3D_SKILLS", raising=False)diff --git a/harness/tests/skills/test_delivery.py b/harness/tests/skills/test_delivery.pyindex 3e34d814..63f6b155 100644--- a/harness/tests/skills/test_delivery.py+++ b/harness/tests/skills/test_delivery.py@@ -1,43 +1,12 @@-"""One shared library, one place that knows how each backend receives it.--The owner's requirement: every coding agent shares ONE skill set, extending to a new-backend must be minimal, and the organisation has to hold up. So the whole per-backend-policy is one row per backend in `skills/prompting.py` — which discovery root — and every-consumer asks it rather than re-deriving. These tests pin that.-"""+"""Each backend's skill discovery root is one row in skills/prompting.py."""from __future__ import annotationsfrom codeverse3d.skills.prompting import AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT, skill_path-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 skill_path("x", agent_kind="codex:gpt-5.6-sol") == skill_path("x", agent_kind="codex")- assert skill_path("x", agent_kind="claude-code:opus") == skill_path("x", agent_kind="claude-code")--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; an unlisted kind (a- test's fake agent) reads the shared one."""- assert skill_path("c3d-x", agent_kind="claude-code") == f"{CLAUDE_SKILL_ROOT}/c3d-x/SKILL.md"- for kind in ("codex", "gemini-cli", "agy", "some-future-cli", ""):+ """claude-code 2.1 has no `.agents` root, the others no `.claude` one; a model suffix never matters."""+ assert skill_path("c3d-x", agent_kind="claude-code:opus") == f"{CLAUDE_SKILL_ROOT}/c3d-x/SKILL.md"+ for kind in ("codex:gpt-5.6-sol", "gemini-cli", "agy", "some-future-cli", ""):assert skill_path("c3d-x", agent_kind=kind) == f"{AGENTS_SKILL_ROOT}/c3d-x/SKILL.md", kind---def test_adding_a_backend_is_one_row():- """The guard behind the claim: if per-backend knowledge spreads back out of- prompting.py, this catches it."""- import pathlib-- root = pathlib.Path(__file__).resolve().parents[2] / "codeverse3d"- names = ("claude-code", "gemini-cli", "codex")- offenders = []- for py in (root / "skills").rglob("*.py"):- if py.name == "prompting.py":- continue- text = py.read_text()- if any(f'"{n}"' in text or f"'{n}'" in text for n in names):- offenders.append(py.name)- assert not offenders, f"per-backend knowledge leaked out of prompting.py into {offenders}"diff --git a/harness/tests/skills/test_delivery_reaches_the_session.py b/harness/tests/skills/test_delivery_reaches_the_session.pydeleted file mode 100644index f7aae97c..00000000--- a/harness/tests/skills/test_delivery_reaches_the_session.py+++ /dev/null@@ -1,95 +0,0 @@-"""A routed bundle only exists if a GENERATING session is told about it.--The read loop measured c3d-scene-composition / -lighting / -motion at 0 opens out of 3-listings each and read it as a wording problem. It was not: the scene track did all of-its baseline generation in its pre-round hook (then ``prepare()``; the declared ``stages``-since) — the env and zones stages called-``tracks.generation.generate`` directly — while ``skills_hook.attach_for_round`` was only-reached from ``steps.run_round``. ``SceneTrack.baseline_tasks`` returns ``[]``, so round 0-listed the bundles to a round that had no generation task to consume them. That was-exactly "listed 3, opened 0", and no rewrite of a SKILL.md could have fixed it.--CLOSED 2026-08-25 (curate wave): ``SceneTrack._env_stage`` / ``_zones_stage`` now go-through the skill hook (``SceneTrack._stage_session``; ``scene.js`` is assembled, no session). These tests-keep every agent-driving module on the hook, so the gap cannot reopen quietly. The scene-bundles' read rate is UNMEASURED against this delivery — that is the next wave's first-experiment, and until it runs their ledger rows stay ``mixed``/``inherited``, not-``measured``.-"""--from __future__ import annotations--from collections import Counter--import pytest--from codeverse3d.contracts.common import Language, Track-from codeverse3d.contracts.plan import ScenePlan-from codeverse3d.proc import EventLog, read_jsonl_lenient-from codeverse3d.workspace import Workspace---def scene_run(tmp_path, monkeypatch):- from codeverse3d.config import Settings- from codeverse3d.tracks.planner import plan_example- from codeverse3d.tracks.scene import SceneTrack- from tests.orchestrator_tracks.conftest import make_spec- from tests.orchestrator_tracks.fakes import FakeAgent, FakeJudge, FakeRuntime, FakeServices- from tests.orchestrator_tracks.test_tracks import _planner, _scene_writer-- monkeypatch.setenv("C3D_SKILLS", "1")- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- plan.assets = [a for a in plan.assets if a.kind == "threejs"]- for z in plan.zones:- z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0,- prompt="a small harbour at dusk")- ws = Workspace(tmp_path / "runs" / "harbour_skills")- agent = FakeAgent(_scene_writer)- track = SceneTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)),- agent=agent, planner_model=_planner(plan.model_dump(mode="json")),- settings=Settings(), runtime=FakeRuntime(Language.SCENE_THREEJS))- rec = track.run(spec, ws)- return rec, agent, ws---def test_every_scene_generation_stage_gets_skills_before_its_sessions(scene_run) -> None:- """One real run proves routing, ordering and telemetry together."""- rec, agent, ws = scene_run- events = EventLog(ws.events_path).read()- attachments = [e for e in events if e.get("event") == "skills.attached"]- by_kind = {e["kind"]: e for e in attachments if e.get("kind") in {"env", "zone"}}-- assert Counter(e.get("kind") for e in attachments) >= Counter({"env": 1, "zone": 1})- assert all(sum(e.get("kind") == kind for e in attachments) == 1 for kind in by_kind)- assert {"c3d-scene-composition", "c3d-scene-lighting"} <= set(by_kind["env"]["skills"])- assert {"c3d-scene-composition", "c3d-scene-motion"} <= set(by_kind["zone"]["skills"])- # R3 is object-only: the bbox sheet's measure / check_contract / isolate loop has no scene tools- assert "c3d-bbox-contract" not in by_kind["zone"]["skills"]-- def belongs(kind: str, event: dict) -> bool:- label = str(event.get("label", ""))- return event.get("event") == "generate.done" and (- label == kind or (kind == "zone" and label.startswith(("zone_", "zones_")))- )-- for kind in by_kind:- attach_at = events.index(by_kind[kind])- generated_at = [i for i, event in enumerate(events) if belongs(kind, event)]- assert generated_at and all(attach_at < i for i in generated_at), kind- assert sum(belongs("zone", event) for event in events) == 1 # D70: one session owns every zone file- assert Counter(job.kind for job in agent.jobs) >= Counter({"env": 1, "zone": 1})-- telemetry_path = ws.root / "telemetry" / "skills.jsonl"- assert telemetry_path.is_file()- telemetry = read_jsonl_lenient(telemetry_path, dicts_only=True)- assert all(sum(row.get("kind") == kind for row in telemetry) == 1 for kind in by_kind)-- baseline_at = next(i for i, event in enumerate(events)- if event.get("event") == "round.start" and event.get("kind") == "baseline")- build_at = next(i for i, event in enumerate(events[baseline_at:], baseline_at)- if event.get("event") == "build.done")- assert events[baseline_at]["n_tasks"] == 0- assert not any(e.get("event") == "generate.done" for e in events[baseline_at:build_at])- assert len(rec.rounds) == 1diff --git a/harness/tests/skills/test_end_to_end.py b/harness/tests/skills/test_end_to_end.pyindex 0aa0c777..ab115114 100644--- a/harness/tests/skills/test_end_to_end.py+++ b/harness/tests/skills/test_end_to_end.py@@ -1,11 +1,4 @@-"""One real track run with the switch on: attach → index → prompt → probe → record.--Every other test here exercises a piece. This one runs the actual round loop (with the-repo's own fakes: no network, no Blender, no node) and asserts the four things a battery-depends on — the bundles reach the workspace, the index reaches the agent's prompt file,-the round record carries what was attached, and the previous round's gate findings change-what the next round gets.-"""+"""One real track run with the switch on: attach → index → prompt → probe → record → reroute on the gates."""from __future__ import annotations@@ -139,16 +132,3 @@ def test_enabled_run_delivers_routes_repairs_and_records_skills(run):repair = next(job for job in agent.jobs if job.kind == "repair")assert "c3d-threejs-shader-traps" in repair.promptassert rec.rounds[0].notes.startswith("repair attempts: 1/2 (fixed)")---def test_the_switch_off_leaves_no_trace(tmp_path, chair_plan, settings, monkeypatch):- monkeypatch.setenv("C3D_SKILLS", "0") # ON is the default since 2026-09-22; off must be said- ws = Workspace(tmp_path / "runs" / "chair_off")- track = StaticObjectTrack(services=FakeServices(contract_errors=1), judge=FakeJudge(scores=(0.55, 0.7, 0.85)),- agent=FakeAgent(_agent_writer),- planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),- settings=settings, runtime=FakeRuntime(Language.THREEJS))- rec = track.run(make_spec(max_rounds=3), ws)- assert all(r.skills is None for r in rec.rounds)- assert not (ws.root / ".agents").exists() and not (ws.root / "telemetry" / "skills.jsonl").exists()- assert MARK_BEGIN not in (ws.root / "AGENTS.md").read_text()diff --git a/harness/tests/skills/test_freshness.py b/harness/tests/skills/test_freshness.pyindex e322327b..897ff55e 100644--- a/harness/tests/skills/test_freshness.py+++ b/harness/tests/skills/test_freshness.py@@ -217,8 +217,6 @@ def test_every_named_cookbook_section_exists():from codeverse3d.prompts.catalog import PROMPT_DIRSfrom codeverse3d.prompts.sections import split_sections- # the language-id → prompts/<dir> mapping has ONE home now (prompts/catalog.py);- # this test used to import the third of its copies_PROMPT_DIR = {k.value: v for k, v in PROMPT_DIRS.items()}for s in SKILLS:diff --git a/harness/tests/skills/test_hook.py b/harness/tests/skills/test_hook.pyindex fe1f6298..7b26b197 100644--- a/harness/tests/skills/test_hook.py+++ b/harness/tests/skills/test_hook.py@@ -1,9 +1,4 @@-"""``tracks/skills_hook``: the round's view of the skill system, and its failure modes.--The hook is where a bug would be most expensive: it runs inside every round, and its job-is to be invisible when the switch is off and harmless when anything goes wrong. So the-tests below spend most of their attention on the off path and the broken path.-"""+"""``tracks/skills_hook``: invisible when the switch is off, harmless when anything breaks."""from __future__ import annotations@@ -12,7 +7,6 @@ from types import SimpleNamespace as NSimport pytest-from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severityfrom codeverse3d.tracks import skills_hook as H@@ -45,46 +39,6 @@ def test_the_switch_off_means_no_files_no_events_no_record(ctx, monkeypatch):assert H.repair_pointers(ctx, None) == ""-def test_the_switch_on_attaches_records_and_measures(ctx, monkeypatch):- monkeypatch.setenv("C3D_SKILLS", "on")- got = H.attach_for_round(ctx, index=0, kind="baseline")- assert got and got.listed- assert (ctx.ws.root / ".agents" / "skills" / got.listed[0] / "SKILL.md").is_file()- assert ctx.events[0][0] == "skills.attached"- assert any(k.startswith("skill:") for k in ctx.prompt_hashes)- usage = H.record_usage(ctx, index=0, kind="baseline")- assert usage is not None and usage.listed == got.listed and usage.deep == []- assert (ctx.ws.root / "telemetry" / "skills.jsonl").is_file()- assert ctx.events[-1][0] == "skills.read"---def test_the_previous_rounds_findings_route_the_repair_sheet(ctx, monkeypatch):- monkeypatch.setenv("C3D_SKILLS", "on")- gates = [GateReport(gate="connectivity", passed=False, findings=[GateFinding(- gate="connectivity", severity=Severity.ERROR,- message="part 'Leg' is floating: nearest supported part is 'Seat' at 4.0 mm")])]- got = H.attach_for_round(ctx, index=1, kind="repair", findings=gates)- assert "c3d-part-contact" in got.listed- assert "connectivity/floating_part" in got.reasons["c3d-part-contact"]- assert got.selections[0].gate_fired---def test_round_zero_never_looks_for_a_previous_round(ctx, monkeypatch):- monkeypatch.setenv("C3D_SKILLS", "on")- got = H.attach_for_round(ctx, index=0, kind="baseline")- assert all(not s.gate_fired for s in got.selections)---def test_repair_pointers_name_the_skill_that_answers_the_current_lint(ctx, monkeypatch):- monkeypatch.setenv("C3D_SKILLS", "on")- H.attach_for_round(ctx, index=0, kind="repair")- lint = GateReport(gate="lint:blender", passed=False, findings=[GateFinding(- gate="lint:blender", severity=Severity.WARN,- message="src/parts/trigger.py is never imported by src/model.py → its part is not built")])- text = H.repair_pointers(ctx, lint)- assert "c3d-blender-forms" in text--def test_single_shot_inlines_one_body_into_every_task(ctx, monkeypatch):monkeypatch.setenv("C3D_SKILLS", "on")ctx.single_shot = True@@ -102,13 +56,6 @@ def test_single_shot_inlines_one_body_into_every_task(ctx, monkeypatch):assert out[0].prompt.endswith("write the chair") and got.inlined in out[0].prompt-def test_an_agent_session_never_gets_an_inlined_body(ctx, monkeypatch):- monkeypatch.setenv("C3D_SKILLS", "on")- H.attach_for_round(ctx, index=0, kind="baseline")- tasks = [NS(prompt="p")]- assert H.with_inlined_skill(ctx, tasks) == tasks--def test_a_broken_library_costs_the_skills_not_the_round(ctx, monkeypatch, caplog):monkeypatch.setenv("C3D_SKILLS", "on")monkeypatch.setenv("C3D_SKILLS_DIR", "/definitely/not/a/directory")diff --git a/harness/tests/skills/test_loader.py b/harness/tests/skills/test_loader.pyindex 489815af..7043e59d 100644--- a/harness/tests/skills/test_loader.py+++ b/harness/tests/skills/test_loader.py@@ -6,33 +6,16 @@ from pathlib import Pathimport pytest-from codeverse3d.skills import all_skills, bundle_dirs, iter_skills, load_skill+from codeverse3d.skills import iter_skills, load_skillfrom codeverse3d.skills.model import (BODY_MAX_LINES,SkillError,parse_skill,- split_frontmatter,validate_bundle,)from tests.skills.conftest import write_bundle-def test_parses_frontmatter_body_and_references(tmp_path: Path):- d = write_bundle(tmp_path, "c3d-demo", description="What it does. When to use it.",- references={"traps.md": "x\n", "table.md": "y\n"})- s = parse_skill(d)- assert s.name == "c3d-demo" and s.dir == d and s.path == d / "SKILL.md"- assert s.description.startswith("What it does")- assert s.license == "Apache-2.0" and s.evidence == "measured" and s.verified == "2026-08-25"- assert s.references == ("references/table.md", "references/traps.md")- assert s.body_tokens > 0 and s.body_lines >= 1---def test_a_directory_argument_finds_the_skill_file(tmp_path: Path):- d = write_bundle(tmp_path, "c3d-demo")- assert parse_skill(d).name == parse_skill(d / "SKILL.md").name--@pytest.mark.parametrize("text, expect", [("no frontmatter at all\n", "missing YAML frontmatter"),("---\nname: [1, 2]\n---\nbody\n", "must match"),@@ -41,8 +24,6 @@ def test_a_directory_argument_finds_the_skill_file(tmp_path: Path):("---\nname: c3d-demo\ndescription: d\nwhen_to_use: x\n---\nbody\n", "unknown frontmatter key"),("---\nname: c3d-demo\ndescription: use <script> tags\n---\nbody\n", "prompt-injection"),("---\nname: c3d_demo\ndescription: d\n---\nbody\n", "must match"),- ("---\nname: c3d--demo\ndescription: d\n---\nbody\n", "must match"),- ("---\nname: C3d-Demo\ndescription: d\n---\nbody\n", "must match"),("---\n- a\n- b\n---\nbody\n", "must be a YAML mapping"),("---\nname: c3d-demo\ndescription: d\nmetadata:\n a:\n b: c\n---\nbody\n", "must be a scalar"),])@@ -70,11 +51,6 @@ def test_description_length_is_the_spec_limit(tmp_path: Path):parse_skill(d)-def test_split_frontmatter_keeps_the_body_verbatim():- fm, body = split_frontmatter("---\nname: a\n---\nline1\nline2\n")- assert fm == "name: a" and body == "line1\nline2\n"--def test_validate_reports_budget_evidence_and_layout(tmp_path: Path):d = write_bundle(tmp_path, "c3d-big", evidence="guesswork", body="x\n" * (BODY_MAX_LINES + 5))(d / "references" / "deeper").mkdir()@@ -96,21 +72,6 @@ def test_validate_wants_a_verified_date(tmp_path: Path):assert any("verified" in i for i in validate_bundle(d))-def test_a_clean_bundle_has_no_issues(tmp_path: Path):- assert validate_bundle(write_bundle(tmp_path, "c3d-demo")) == []---def test_iteration_skips_modules_dunder_dirs_and_claims(tmp_path: Path):- write_bundle(tmp_path, "c3d-demo")- (tmp_path / "_claims").mkdir()- (tmp_path / "_claims" / "c3d-demo.toml").write_text("")- (tmp_path / "__pycache__").mkdir()- (tmp_path / "loader.py").write_text("x = 1\n")- (tmp_path / "not-a-bundle").mkdir()- assert [p.name for p in bundle_dirs(tmp_path)] == ["c3d-demo"]- assert list(all_skills(tmp_path)) == ["c3d-demo"]--def test_a_broken_bundle_is_skipped_not_fatal_but_strict_raises(tmp_path: Path, caplog):write_bundle(tmp_path, "c3d-good")bad = tmp_path / "c3d-bad"diff --git a/harness/tests/skills/test_materialize_prompting.py b/harness/tests/skills/test_materialize_prompting.pyindex 8eb6bc2a..635eb60a 100644--- a/harness/tests/skills/test_materialize_prompting.py+++ b/harness/tests/skills/test_materialize_prompting.py@@ -1,10 +1,4 @@-"""Materialisation into both discovery roots, and the per-backend prompt text (T6).--Two things here are load-bearing and were verified against the shipped CLIs rather than-assumed: claude-code reads only ``.claude/skills`` (no ``.agents`` skill root), and codex-refuses symlinks inside a skill tree. Both are asserted below, because a CLI upgrade that-changes either ships an empty index and nothing else fails.-"""+"""Materialisation into both discovery roots, and the per-backend prompt text (T6)."""from __future__ import annotations@@ -41,60 +35,21 @@ def ws(tmp_path: Path) -> Path:return root-def _plan(n=3):- from types import SimpleNamespace as NS-- return NS(parts=[NS(name=f"P{i}", instances=1, symmetry="none", children=[]) for i in range(n)], summary="")--# --------------------------------------------------------------------------- files-def test_bundles_land_in_both_discovery_roots_as_real_files(ws, library):- skills = [library["c3d-part-contact"], library["c3d-blender-forms"]]- written = materialize_skills(ws, skills)- for root in SKILL_ROOTS:- for s in skills:- f = ws / root / s.name / "SKILL.md"- assert f.is_file() and not f.is_symlink()- assert f.read_text() == s.path.read_text()- assert (ws / root / s.name / "references" / "worked_example.md").is_file()- # 2 roots x (2 skills + the read control) x (SKILL.md + one reference)- assert len(written) == 2 * 3 * 2---def test_a_never_routed_control_bundle_goes_in_beside_the_real_ones(ws, library):- """Signal 4: the probe's own falsification.-- Nothing routes it, nothing indexes it, and if it comes back opened then whatever- opened it was not the agent choosing to read a skill — git's own diff does it, and so- does every CLI's activation. Without this the read rate would report 100% forever.- """+def test_bundles_and_the_read_control_land_in_both_roots_as_real_files(ws, library):+ """codex refuses symlinks; the never-routed control falsifies the read probe (git diff opens files too)."""from codeverse3d.skills.materialize import CONTROL_NAME-- materialize_skills(ws, [library["c3d-part-contact"]])- for root in SKILL_ROOTS:- d = ws / root / CONTROL_NAME- assert (d / "SKILL.md").is_file() and (d / "references" / "control.md").is_file()- assert CONTROL_NAME not in index_block([library["c3d-part-contact"]])from codeverse3d.skills.registry import ROUTED_SKILLS- assert CONTROL_NAME not in ROUTED_SKILLS---def test_the_control_survives_a_reroute_and_never_counts_as_a_stale_bundle(ws, library):- from codeverse3d.skills.materialize import CONTROL_NAME-- materialize_skills(ws, [library["c3d-part-contact"], library["c3d-bbox-contract"]])- materialize_skills(ws, [library["c3d-bbox-contract"]])- for root in SKILL_ROOTS:- assert (ws / root / CONTROL_NAME / "SKILL.md").is_file()- assert (ws / root / "c3d-bbox-contract").is_dir() # still routed: kept- assert not (ws / root / "c3d-part-contact").exists() # no longer routed: removed---def test_nothing_in_a_materialised_tree_is_a_symlink_because_codex_refuses_them(ws, library):- materialize_skills(ws, [library["c3d-part-contact"]])+ skills = [library["c3d-part-contact"], library["c3d-blender-forms"]]+ written = materialize_skills(ws, skills)for root in SKILL_ROOTS:+ for s in skills:+ assert (ws / root / s.name / "SKILL.md").read_text() == s.path.read_text()+ assert (ws / root / CONTROL_NAME / "references" / "control.md").is_file()assert not any(p.is_symlink() for p in (ws / root).rglob("*"))+ assert len(written) == 2 * 3 * 2 # 2 roots x (2 skills + control) x (SKILL.md + one reference)+ assert CONTROL_NAME not in index_block(skills) and CONTROL_NAME not in ROUTED_SKILLSdef test_atime_equals_mtime_after_writing_so_the_read_probe_has_a_zero_point(ws, library):@@ -104,9 +59,7 @@ def test_atime_equals_mtime_after_writing_so_the_read_probe_has_a_zero_point(ws,def test_an_empty_selection_still_sweeps_last_rounds_bundles(ws, library):- """attach_skills' empty-selection early return used to skip the sweep entirely:- last round's bundles stayed live in both discovery roots, where the native CLIs- discover skills by directory (V4b). An empty route is a legal desired set."""+ """V4b: an empty route still removes last round's bundles — native CLIs discover by directory."""materialize_skills(ws, [library["c3d-part-contact"]])out = attach_skills(ws, track="static_object", language="threejs", kind="generation", library={})assert out.listed == []@@ -123,10 +76,6 @@ def test_native_loader_backends_get_one_sentence_and_no_second_index(library):assert index_tokens(skills) < 60-def test_an_empty_route_adds_no_text_at_all(library):- assert index_block([]) == ""--def test_repair_pointers_name_only_the_gate_fired_skills(library):sel = select("static_object", "blender", "repair", signals={"multi_part": True},findings=["connectivity/interpenetration"], library=library)@@ -156,36 +105,3 @@ def test_the_index_is_written_into_every_body_file_and_is_replaceable(ws, librarassert body.count(MARK_BEGIN) == 1 and "c3d-part-contact" not in body and "c3d-bbox-contract" in bodywrite_index(ws, "")assert MARK_BEGIN not in (ws / "AGENTS.md").read_text()---def test_write_index_ignores_body_files_a_workspace_does_not_have(tmp_path: Path):- assert write_index(tmp_path, "hello") == []---# --------------------------------------------------------------------------- attach-def test_attach_routes_writes_and_reports(ws, library):- got = attach_skills(ws, track="static_object", language="blender", kind="baseline",- plan=_plan(), library=library, max_skills=5, allow_unverified=False)- assert got.listed and got.index_tokens > 0- assert set(got.reasons) == set(got.listed)- for root in SKILL_ROOTS:- assert all((ws / root / n / "SKILL.md").is_file() for n in got.listed)- assert MANDATE in (ws / "AGENTS.md").read_text()- assert got.inlined == ""---def test_attach_for_a_single_shot_session_inlines_instead_of_writing_files(ws, library):- got = attach_skills(ws, track="static_object", language="blender", kind="baseline",- plan=_plan(), library=library, single_shot=True,- max_skills=5, allow_unverified=False)- assert got.inlined and got.index_tokens == 0- assert not any((ws / root / n).exists() for root in SKILL_ROOTS for n in got.listed)- assert MARK_BEGIN not in (ws / "AGENTS.md").read_text()---def test_attach_with_nothing_routed_clears_the_section(ws, library):- write_index(ws, "stale")- got = attach_skills(ws, track="graphics", language="glsl_shader", kind="asset",- library=library, max_skills=5, allow_unverified=False)- assert got.listed == []- assert MARK_BEGIN not in (ws / "AGENTS.md").read_text()diff --git a/harness/tests/skills/test_only_switch.py b/harness/tests/skills/test_only_switch.pyindex fb820f46..4bfd9d0e 100644--- a/harness/tests/skills/test_only_switch.py+++ b/harness/tests/skills/test_only_switch.py@@ -1,10 +1,4 @@-"""``C3D_SKILLS_ONLY``: route exactly one bundle, so an effect A/B can attribute its delta.--``C3D_SKILLS=1`` routes up to five bundles. A delta measured against that is a delta of-the SET, and the wave's question is per bundle. The switch restricts the LIBRARY rather-than filtering the selection afterwards, and the difference is testable: with a filter,-the cap could spend its slots on higher-priority sheets and drop the one under test.-"""+"""``C3D_SKILLS_ONLY``: route exactly one bundle, so an effect A/B can attribute its delta."""from __future__ import annotations@@ -36,42 +30,20 @@ def _listed(ws, **kw):plan=_Plan(), **kw).listed-def test_unset_routes_the_whole_set(ws):- listed = _listed(ws)- assert len(listed) > 1- assert "c3d-bbox-contract" in listed--[email protected]("name", ["c3d-bbox-contract", "c3d-blender-forms", "c3d-repeats-and-mirrors"])-def test_only_routes_exactly_that_bundle(ws, name):- assert _listed(ws, only=frozenset({name})) == [name]--def test_the_cap_cannot_drop_the_bundle_under_test(ws):- """The reason it restricts the library and not the selection. bbox-contract ranks- below blender-forms and part-contact in the default set, so a max of 1 applied to the- FULL routing would hand back somebody else's bundle."""+ """It restricts the library, not the selection: a max of 1 over the full routing picks another bundle."""assert _listed(ws, max_skills=1)[0] != "c3d-bbox-contract"assert _listed(ws, only=frozenset({"c3d-bbox-contract"}), max_skills=1) == ["c3d-bbox-contract"]-def test_a_bundle_its_own_rules_do_not_fire_for_is_still_not_routed(ws):- """`only` narrows what MAY be routed; it never forces an attachment. urdf-joints has- no row that fires on a blender static_object, so the arm attaches nothing — and an A/B- on it would correctly measure no difference rather than a fabricated one."""- assert _listed(ws, only=frozenset({"c3d-urdf-joints"})) == []--def test_an_unknown_name_attaches_nothing_rather_than_everything(ws, caplog):- """A typo must make the variant visibly identical to its control, not silently- measure the full five-bundle set."""+ """A typo makes the variant visibly identical to its control, never the full set."""assert _listed(ws, only=frozenset({"c3d-typo"})) == []assert "C3D_SKILLS_ONLY" in caplog.textdef test_the_switch_reaches_the_router(ws, monkeypatch):- """``only=`` omitted, attach_skills reads ``C3D_SKILLS_ONLY`` (a comma list, blanks- ignored) — the variant child of an effect A/B sets nothing else."""+ """``only=`` omitted, attach_skills reads ``C3D_SKILLS_ONLY`` (a comma list, blanks ignored)."""monkeypatch.setenv("C3D_SKILLS_ONLY", " c3d-bbox-contract , ")get_settings.cache_clear()assert _listed(ws) == ["c3d-bbox-contract"], "attach_skills must consult the switch when only= is omitted"diff --git a/harness/tests/skills/test_packaging.py b/harness/tests/skills/test_packaging.pyindex f349d763..904f4b33 100644--- a/harness/tests/skills/test_packaging.py+++ b/harness/tests/skills/test_packaging.py@@ -1,18 +1,10 @@-"""A wheel that ships no SKILL.md routes nothing, silently (T: packaging).--This is not hypothetical. The comment above ``[tool.setuptools.package-data]`` records-the last time it happened: the scene starter tree and ``languages/**/*.md`` were missing-from the wheel, so ``skeleton.write_example()`` rglob'd an absent directory and wrote ZERO-files while reporting success. A skill library fails the same way and even more quietly —-the run passes, the index is empty, and the read rate reads 0% as if the model ignored it.-"""+"""A wheel that ships no SKILL.md routes nothing, silently — as the starter tree once went missing."""from __future__ import annotationsimport shutilimport subprocessimport sys-import tomllibimport zipfilefrom pathlib import Path@@ -22,12 +14,6 @@ HARNESS = Path(__file__).resolve().parents[2]PROBE = "c3d-packaging-probe"-def test_package_data_declares_the_skill_tree():- data = tomllib.loads((HARNESS / "pyproject.toml").read_text())- globs = data["tool"]["setuptools"]["package-data"]["codeverse3d"]- assert "skills/**/*" in globs--@pytest.mark.slowdef test_a_built_wheel_actually_contains_the_bundles(tmp_path: Path):"""Builds a real wheel. A probe bundle is added when the library is still empty, so@@ -66,14 +52,3 @@ def test_a_built_wheel_actually_contains_the_bundles(tmp_path: Path):if made_probe:shutil.rmtree(probe, ignore_errors=True)shutil.rmtree(HARNESS / "build", ignore_errors=True)---def test_skills_dir_is_the_package_directory_importlib_resources_names():- """``skills_dir`` uses ``__file__``, as prompts and rubrics do: pin that it is the same- directory the import system resolves, so an installed wheel still finds the bundles."""- from importlib.resources import files-- from codeverse3d.skills import skills_dir-- assert Path(str(files("codeverse3d.skills"))) == skills_dir()diff --git a/harness/tests/skills/test_registry.py b/harness/tests/skills/test_registry.pyindex 93808da0..d2a85f94 100644--- a/harness/tests/skills/test_registry.py+++ b/harness/tests/skills/test_registry.py@@ -28,12 +28,6 @@ def test_info_findings_are_census_not_defects():assert finding_kind("lint:blender", "named objects: ['Seat', 'Leg']", "info") is None-def test_unknown_gates_and_empty_text_are_none_not_a_crash():- assert finding_kind("", "") is None- assert finding_kind("brand_new_gate", "something happened", "error") is None- assert finding_kind("connectivity", "", "error") is None--def test_finding_kinds_accepts_reports_findings_and_strings():class F:def __init__(self, gate, message, severity="warn"):@@ -69,10 +63,7 @@ def test_rule_ids_are_unique_and_the_design_numbers_are_all_present():def test_every_routed_skill_is_actually_in_the_library():- """The cut's real invariant: retiring a bundle must retire its rows in the same commit.-- A route naming an absent bundle is silently skipped by the router, so this would not- crash a run — it would just make the ledger describe routing that never happens."""+ """A route naming an absent bundle is silently skipped: retire its rows with the bundle."""from codeverse3d.skills import all_skillsassert not (set(r.skill for r in ROUTES) - set(all_skills()))@@ -86,12 +77,6 @@ def test_gate_fired_rows_always_outrank_standing_rows():assert all(r.priority >= 90 for r in fired)-def test_every_row_carries_a_reason_and_a_known_skill():- for r in ROUTES:- assert r.why and len(r.why) > 20, r.rule- assert r.skill.startswith("c3d-")--def test_route_finding_patterns_are_real_kinds_or_families():families = {k.split("/", 1)[0] for k in (finding_kind(g, m, s) or ""for g, m, s in ((r["gate"], r["message"], r["severity"]) for r in GOLDEN))}@@ -102,6 +87,7 @@ def test_route_finding_patterns_are_real_kinds_or_families():def test_matches_finding_supports_exact_and_family_patterns():+ """E1: repair pointers route through Route.matches_finding."""row = Route("X", "c3d-part-contact", 95, findings=("connectivity/*", "joint_sweep/link_overlap"))assert row.matches_finding(["connectivity/floating_part"]) == "connectivity/floating_part"assert row.matches_finding(["joint_sweep/link_overlap"]) == "joint_sweep/link_overlap"diff --git a/harness/tests/skills/test_router.py b/harness/tests/skills/test_router.pyindex 247fed07..2ddb77a5 100644--- a/harness/tests/skills/test_router.py+++ b/harness/tests/skills/test_router.py@@ -1,8 +1,4 @@-"""Routing: the table, the cap, the priorities, the coverage guarantee (T5).--Nobody declares ``skills: [...]``; if the derivation is wrong, the wrong sheet is in the-prompt and the cost is paid anyway. So every law in design §5.2 is a test here.-"""+"""Routing on a synthetic library: which sheet each plan signal and gate finding attaches (T5, design §5.2)."""from __future__ import annotations@@ -27,20 +23,6 @@ def skills_for(track, language, kind, *, plan=None, **kw):return [s.skill for s in select(track, language, kind, signals=plan_signals(plan), **kw)]-# --------------------------------------------------------------------------- signals-def test_plan_signals_read_the_typed_fields():- s = plan_signals(NS(parts=[part(instances=4), part(symmetry="mirror_x", children=[NS(name="Burr")])],- joints=[NS(type="revolute")], summary="", effects=[]))- assert s["n_parts"] == 2 and s["multi_part"] is True- assert s["has_instances"] and s["has_symmetry"] and s["has_assemblies"] and s["has_joints"]- assert s["joint_types"] == ["revolute"]---def test_plan_signals_of_a_missing_plan_are_all_false_not_an_exception():- s = plan_signals(None)- assert s["n_parts"] == 0 and not s["multi_part"] and not s["has_custom_shader"]--def test_custom_shader_is_detected_from_effects_or_from_words():assert plan_signals(NS(effects=[NS(kind="glsl_material", description="water")]))["has_custom_shader"]assert plan_signals(NS(summary="a raymarched tunnel"))["has_custom_shader"]@@ -57,20 +39,8 @@ def test_a_repair_round_spends_its_budget_on_what_broke(library):assert "R2" in got[0].rules and "connectivity/interpenetration" in got[0].reason-def test_the_cap_cuts_the_low_priority_tail_not_the_gate_fired_head(library):- full = select("articulated_object", "urdf_blender", "refine", signals=plan_signals(static_plan(instances=2)),- findings=["joint_sweep/link_overlap"], library=library, max_skills=99)- capped = select("articulated_object", "urdf_blender", "refine", signals=plan_signals(static_plan(instances=2)),- findings=["joint_sweep/link_overlap"], library=library, max_skills=2)- assert [s.name for s in capped] == [s.name for s in full[:2]]- assert capped[0].priority >= capped[-1].priority--def test_quiet_kinds_attach_nothing_unless_a_gate_fired(library):- """Law 4: asset / asset_fix / reference sessions are short and narrow.-- A gate-fired row still reaches them when its own kind filter allows it — R15/R17/R19- are kind-agnostic by design, R2/R4 are not, and this pins both halves."""+ """Law 4: quiet sessions get only kind-agnostic gate-fired rows (R15/R17/R19, not R2/R4)."""for kind in QUIET_KINDS:assert select("scene", "scene_threejs", kind, signals=plan_signals(static_plan()), library=library) == []fired = select("scene", "scene_threejs", kind, signals=plan_signals(static_plan()),@@ -93,18 +63,14 @@ def test_inherited_unverified_bundles_are_off_until_the_switch_says_otherwise(liassert "c3d-cadquery-forms" in [s.name for s in on]-def test_a_single_part_plan_does_not_get_the_contact_sheet(library):- one = skills_for("static_object", "blender", "baseline", plan=static_plan(1), library=library)- many = skills_for("static_object", "blender", "baseline", plan=static_plan(3), library=library)- assert "c3d-part-contact" not in [s.name for s in one]- assert "c3d-part-contact" in [s.name for s in many]---def test_repeats_skill_needs_instances_or_symmetry(library):- plain = skills_for("static_object", "blender", "baseline", plan=static_plan(), library=library)- mirrored = skills_for("static_object", "blender", "baseline", plan=static_plan(symmetry="mirror_x"), library=library)- assert "c3d-repeats-and-mirrors" not in [s.name for s in plain]- assert "c3d-repeats-and-mirrors" in [s.name for s in mirrored][email protected]("skill, without, with_", [+ ("c3d-part-contact", static_plan(1), static_plan(3)),+ ("c3d-repeats-and-mirrors", static_plan(), static_plan(symmetry="mirror_x")),+])+def test_a_plan_signal_decides_a_standing_row(library, skill, without, with_):+ off, on = ([s.name for s in skills_for("static_object", "blender", "baseline", plan=p, library=library)]+ for p in (without, with_))+ assert skill not in off and skill in ondef test_language_rows_do_not_leak_across_languages(library):@@ -120,27 +86,3 @@ def test_scene_gate_findings_route_the_matching_scene_skill(library):("gl_frames/motion_or_detail", "c3d-scene-motion")):got = select("scene", "scene_threejs", "repair", findings=[finding], library=library, max_skills=1)assert got and got[0].name == want, finding---def test_a_route_row_without_a_bundle_is_skipped_not_a_crash(library_dir):- from codeverse3d.skills import all_skills-- (library_dir / "c3d-blender-forms" / "SKILL.md").unlink()- lib = all_skills(library_dir)- got = [s.name for s in skills_for("static_object", "blender", "baseline", plan=static_plan(), library=lib)]- assert got and "c3d-blender-forms" not in got---def test_selection_carries_the_rule_and_the_reason(library):- got = select("static_object", "blender", "baseline", signals=plan_signals(static_plan()), library=library)- by_name = {s.name: s for s in got}- assert by_name["c3d-part-contact"].rules == ("R1",)- assert by_name["c3d-part-contact"].reason.startswith("R1: ")- assert not by_name["c3d-part-contact"].gate_fired--[email protected]("max_skills", [0, 1, 3])-def test_max_skills_is_honoured_exactly(library, max_skills):- got = select("articulated_object", "urdf_blender", "baseline", signals=plan_signals(static_plan(instances=2)),- library=library, max_skills=max_skills)- assert len(got) == min(max_skills, 5)diff --git a/harness/tests/skills/test_routing_property.py b/harness/tests/skills/test_routing_property.pyindex e265a402..0c506ea8 100644--- a/harness/tests/skills/test_routing_property.py+++ b/harness/tests/skills/test_routing_property.py@@ -8,8 +8,7 @@ import randomimport pytestfrom codeverse3d.skills import all_skills, bundle_dirs, select, skills_dir-from codeverse3d.skills.model import EVIDENCE_INHERITED-from codeverse3d.skills.registry import QUIET_KINDS, ROUTED_SKILLS, ROUTES, plan_signals+from codeverse3d.skills.registry import ROUTES, plan_signalspytestmark = pytest.mark.skipif(not bundle_dirs(), reason=f"no bundles in {skills_dir()} yet")@@ -106,33 +105,6 @@ def test_every_corpus_finding_kind_routes_sanely_from_every_session():assert answered_somewhere, f"{finding} is classified but no route answers it"-def test_a_quiet_kind_stays_quiet_until_a_gate_fires():- for track, language in itertools.product(TRACKS, LANGUAGES):- for kind in QUIET_KINDS:- sig = {"multi_part": True, "has_instances": True, "has_custom_shader": True}- assert select(track, language, kind, signals=sig, library=LIBRARY) == []---def test_junk_inputs_degrade_to_empty_and_never_raise():- for bad in JUNK:- combos = [(bad, "blender", "baseline"), ("static_object", bad, "baseline"),- ("static_object", "blender", bad), (bad, bad, bad)]- for track, language, kind in combos:- got = select(track, language, kind, signals={"multi_part": True}, library=LIBRARY)- assert isinstance(got, list) and len(got) <= 5, (track, language, kind)- assert all(skill.name in ROUTED_SKILLS for skill in got)---def test_none_and_broken_inputs_are_survivable():- for signals in (None, {}, {"multi_part": None}, {"nonsense": object()}):- assert isinstance(select("static_object", "blender", "baseline",- signals=signals, library=LIBRARY), list)- for findings in ((), None, [], ["not/a/real/kind"], ["", None]):- assert isinstance(select("static_object", "blender", "repair",- findings=findings, library=LIBRARY), list)- assert select("static_object", "blender", "baseline", library={}) == []--def test_every_track_language_pair_a_run_can_present_routes_something():"""A pair the harness actually drives must not come back empty at baseline, or thelibrary has a hole the read-rate metric would report as apathy."""@@ -146,16 +118,6 @@ def test_every_track_language_pair_a_run_can_present_routes_something():assert got, f"{track}/{language} routes nothing at baseline"-def test_an_unverified_bundle_is_off_by_default_everywhere():- thin = {n for n, s in LIBRARY.items() if s.evidence == EVIDENCE_INHERITED}- if not thin:- pytest.skip("every shipped bundle is measured or mixed")- for track, language, kind in BASE_INPUTS:- got = {s.name for s in select(track, language, kind, signals={"multi_part": True},- library=LIBRARY, findings=LIVE_KINDS)}- assert not (got & thin), f"{sorted(got & thin)} routed without C3D_SKILLS_UNVERIFIED"--def test_a_random_walk_of_mixed_findings_never_breaks_an_invariant():rng = random.Random(20260825)for _ in range(2000):diff --git a/harness/tests/skills/test_telemetry.py b/harness/tests/skills/test_telemetry.pyindex 19b271e7..8e723dd6 100644--- a/harness/tests/skills/test_telemetry.py+++ b/harness/tests/skills/test_telemetry.py@@ -1,9 +1,4 @@-"""The read probe — the measurement that replaces "0 of 16 read_cookbook calls".--If these tests are wrong, every later conclusion about whether skills work is wrong, so-they pin the semantics explicitly: surfaced != deep, and a bundle with no references-cannot be probed for depth and says so.-"""+"""The read probe's semantics: surfaced != deep, the control, transcript before atime."""from __future__ import annotations@@ -17,11 +12,9 @@ from codeverse3d.skills.materialize import attach_skillsfrom codeverse3d.skills.telemetry import (SKILLS_FILE,TELEMETRY_DIR,- append_usage,probe_reads,)from tests.skills.conftest import write_bundle-from tests.skills.test_materialize_prompting import _plan@pytest.fixture@@ -32,6 +25,12 @@ def ws(tmp_path: Path) -> Path:return root+def _plan(n=3):+ from types import SimpleNamespace as NS++ return NS(parts=[NS(name=f"P{i}", instances=1, symmetry="none", children=[]) for i in range(n)], summary="")++def _attach(ws, library, **kw):return attach_skills(ws, track="static_object", language="blender", kind="baseline",plan=_plan(), library=library,@@ -44,37 +43,15 @@ def _touch_read(path: Path) -> None:os.utime(path, (st.st_mtime + 30, st.st_mtime))-def test_nothing_read_means_nothing_read(ws, library):- got = _attach(ws, library)- usage = probe_reads(ws, got)- assert usage.listed == got.listed- assert usage.surfaced == [] and usage.deep == [] and usage.body_tokens_read == 0- assert usage.deep_read_rate == 0.0---def test_opening_skill_md_is_surfaced_but_not_deep(ws, library):- got = _attach(ws, library)- name = got.listed[0]- _touch_read(ws / ".agents" / "skills" / name / "SKILL.md")- usage = probe_reads(ws, got)- assert usage.surfaced == [name] and usage.deep == []---def test_opening_a_reference_is_the_deep_signal(ws, library):+def test_skill_md_is_surfaced_a_reference_is_deep_and_the_claude_copy_counts(ws, library):got = _attach(ws, library)- name = got.listed[0]- _touch_read(ws / ".agents" / "skills" / name / "references" / "worked_example.md")+ a, b = got.listed[:2]+ _touch_read(ws / ".agents" / "skills" / a / "references" / "worked_example.md")+ _touch_read(ws / ".claude" / "skills" / b / "SKILL.md") # claude-code reads only that rootusage = probe_reads(ws, got)- assert usage.deep == [name] and usage.surfaced == [name] # deep implies reached- assert usage.body_tokens_read == next(r.body_tokens for r in usage.reads if r.name == name)- assert 0 < usage.deep_read_rate <= 1---def test_the_claude_copy_counts_too_because_claude_code_reads_only_that_root(ws, library):- got = _attach(ws, library)- name = got.listed[0]- _touch_read(ws / ".claude" / "skills" / name / "SKILL.md")- assert probe_reads(ws, got).surfaced == [name]+ assert usage.surfaced == [a, b] and usage.deep == [a] # deep implies reached+ assert usage.body_tokens_read == next(r.body_tokens for r in usage.reads if r.name == a)+ assert usage.deep_read_rate == 1 / len(got.listed)def test_a_bundle_with_no_references_says_depth_is_unmeasurable(tmp_path, ws):@@ -87,27 +64,8 @@ def test_a_bundle_with_no_references_says_depth_is_unmeasurable(tmp_path, ws):assert read.deep_measurable is False and read.deep is False-def test_usage_is_appended_as_one_json_line_per_session(ws, library):- got = _attach(ws, library)- usage = probe_reads(ws, got)- append_usage(ws, usage, round=0, kind="baseline", agent="gemini-cli:gemini-3.6-flash")- append_usage(ws, usage, round=1, kind="refine", agent="gemini-cli:gemini-3.6-flash")- rows = [json.loads(x) for x in (ws / TELEMETRY_DIR / SKILLS_FILE).read_text().splitlines()]- assert [r["round"] for r in rows] == [0, 1]- assert rows[0]["listed"] == usage.listed and "index_tokens" in rows[0]---def test_the_control_bundle_is_materialised_and_starts_unread(ws, library):- from codeverse3d.skills.materialize import materialize_skills-- materialize_skills(ws, [library["c3d-part-contact"]])- usage = probe_reads(ws, _materialized(library, "c3d-part-contact"))- assert usage.control_present and not usage.control_read--def test_a_control_that_was_opened_makes_the_rate_unmeasurable(ws, library):- """The whole point: a session where everything looks read is a session that measured- nothing, and it must say so instead of reporting a confident 100%."""+ """Everything looking read means nothing was measured: the rate is None, not 100%."""from codeverse3d.skills.materialize import CONTROL_NAME, materialize_skillsfrom codeverse3d.skills.prompting import AGENTS_SKILL_ROOT@@ -120,12 +78,7 @@ def test_a_control_that_was_opened_makes_the_rate_unmeasurable(ws, library):def test_git_diff_alone_trips_the_control(tmp_path, library): # noqa: PLR0915- """The confound that invalidated the original design, reproduced.-- ``Workspace.changed_files`` runs `git add -A -N` then `git diff --numstat` after every- agent session, and git reads each untracked file to diff it. That flips every bundle- file to "read" with no agent involved at all.- """+ """``Workspace.changed_files``' `git add -A -N` + `git diff` reads every untracked bundle file."""import subprocessfrom codeverse3d.skills.materialize import materialize_skills@@ -244,19 +197,6 @@ def test_a_call_the_cli_marked_failed_read_nothing(ws, library):assert probe_reads(ws, got).surfaced == []-def test_an_agent_that_opens_the_control_is_reported_not_called_blind(ws, library):- import time-- from codeverse3d.skills.materialize import CONTROL_NAME-- got = _attach(ws, library)- _session(ws, "baseline", [{"tool": "read_file", "args": {"file_path": f".agents/skills/{CONTROL_NAME}/SKILL.md"}}],- t=time.time() + 1)- usage = probe_reads(ws, got)- assert usage.evidence == "transcript" and usage.control_read- assert usage.deep_read_rate == 0.0 # exact: it read the control, and nothing else--def test_the_path_match_is_exact_about_names_and_about_reading():from codeverse3d.skills.telemetry import _called