Official Codebase of 3DCodeVerse
Python
skills: the machinery — a routed, spec-conformant skill library whose reads we can measure
gaoypengf73313211022
diff --git a/harness/codeverse/agents/api_agent.py b/harness/codeverse/agents/api_agent.pyindex fa53dc73..a7a50a70 100644--- a/harness/codeverse/agents/api_agent.py+++ b/harness/codeverse/agents/api_agent.py@@ -189,6 +189,13 @@ class _Loop: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 = turnparts.append(ToolResultPart(call_id=call.id, name=call.name, content=out.text, images=out.images, is_error=out.is_error))diff --git a/harness/codeverse/agents/claude_code.py b/harness/codeverse/agents/claude_code.pyindex 5104a3ab..c9a71088 100644--- a/harness/codeverse/agents/claude_code.py+++ b/harness/codeverse/agents/claude_code.py@@ -34,7 +34,11 @@ from codeverse.config import get_settingsfrom codeverse.contracts.agent import AgentJob, AgentResultfrom codeverse.contracts.common import Usage-ALLOWED_TOOLS = ("Read", "Edit", "Write", "MultiEdit", "Glob", "Grep",+#: ``--allowedTools``. "Skill" is claude-code 2.1's model-invoked skill tool: without it+#: the bundles the harness materialises into ``ws/.claude/skills/`` are listed at session+#: start and then DENIED on activation, which reads in the transcript as the model+#: ignoring them. It only ever opens files already inside the workspace.+ALLOWED_TOOLS = ("Read", "Edit", "Write", "MultiEdit", "Glob", "Grep", "Skill","Bash(node:*)", "Bash(python:*)", "Bash(python3:*)", "Bash(ls:*)", "mcp__c3v__*")IDLE_GRACE_S = 300.0diff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.pyindex 23a50be3..7c73ca05 100644--- a/harness/codeverse/agents/materialize.py+++ b/harness/codeverse/agents/materialize.py@@ -10,6 +10,17 @@ MCP wiring:* codex → ``-c`` overrides returned in :class:`Materialized.codex_overrides`* agy (Antigravity) → no per-workspace MCP; the body documents the CLI fallback.+Skills: the routed ``SKILL.md`` bundles are written per ROUND, not here — the set depends+on the round's kind and the previous round's gate findings (``codeverse/skills``,+``tracks/skills_hook.py``). ``skills.materialize.write_index`` then edits a marked section+into the three body files this module writes, so there is exactly one shared head and no+new one (docs/COST.md §13 measured and reverted a second head at +2,925 tokens/call).+Nothing here needs to change for the CLIs to see them: codex's per-tool approval override+below is scoped to ``mcp_servers.3dcv.*`` and cannot reach its skills loader, and+gemini-cli's ``activate_skill`` consent is already covered by ``--approval-mode yolo``+(``agents/gemini_cli.py``). claude-code needed one change — ``Skill`` in its+``--allowedTools``, see ``agents/claude_code.py``.+Ignore files: ``.geminiignore`` / ``.aiexclude`` hide only noise (:data:`IGNORE_LINES`);``.gemini/settings.json`` gets ``context.fileFiltering.respectGitIgnore=false`` because theworkspace ``.gitignore`` hides ``artifacts/`` + ``trajectories/`` from git and gemini-clidiff --git a/harness/codeverse/cli/doctor.py b/harness/codeverse/cli/doctor.pyindex a43ff47d..b9ac60cb 100644--- a/harness/codeverse/cli/doctor.py+++ b/harness/codeverse/cli/doctor.py@@ -256,7 +256,38 @@ def check_mcp() -> list[Row]:return [("mcp", "WARN", f"codeverse.spatial.mcp_server not importable ({e})")]-def run_doctor(*, live: bool = False, gpu: bool = True) -> list[Row]:+def check_skills() -> list[Row]:+ """The static half of the live CLI smoke: is the library there, valid, and reachable?++ A CLI upgrade that moves its skills root ships an empty index and the run still+ passes — the failure is invisible except as a read rate of zero a battery later. So+ the wiring gets a check you can run before spending money."""+ from codeverse.agents.claude_code import ALLOWED_TOOLS+ from codeverse.skills import bundle_dirs, skills_dir, validate_bundle+ from codeverse.skills.config import skills_enabled+ from codeverse.skills.materialize import SKILL_ROOTS+ from codeverse.skills.registry import ROUTED_SKILLS++ rows: list[Row] = [("skills switch", "OK" if skills_enabled() else "WARN",+ "CV3D_SKILLS=on" if skills_enabled() else "CV3D_SKILLS is off (default): no skill is attached")]+ dirs = bundle_dirs()+ if not dirs:+ rows.append(("skills library", "WARN", f"no bundles under {skills_dir()}"))+ else:+ bad = {d.name: validate_bundle(d) for d in dirs}+ bad = {k: v for k, v in bad.items() if v}+ rows.append(("skills library", "FAIL" if bad else "OK",+ f"{len(dirs)} bundles, {len(bad)} invalid" + (f": {', '.join(bad)}" if bad else "")))+ missing = [n for n in ROUTED_SKILLS if n not in {d.name for d in dirs}]+ if missing:+ rows.append(("skills routing", "WARN", f"{len(missing)} routed skill(s) have no bundle: {', '.join(missing[:4])}…"))+ rows.append(("skills discovery", "OK", "materialised into " + " + ".join(SKILL_ROOTS)))+ rows.append(("claude-code Skill tool", "OK" if "Skill" in ALLOWED_TOOLS else "FAIL",+ "in --allowedTools" if "Skill" in ALLOWED_TOOLS else "missing: claude-code would deny skill activation"))+ return rows+++def run_doctor(*, live: bool = False, gpu: bool = True, skills: bool = False) -> list[Row]:rows: list[Row] = []rows += check_python_deps()rows += check_blender()@@ -267,6 +298,8 @@ def run_doctor(*, live: bool = False, gpu: bool = True) -> list[Row]:rows += check_pool(live)rows += check_clis()rows += check_mcp()+ if skills:+ rows += check_skills()return rows@@ -275,12 +308,13 @@ def doctor(ctx: typer.Context,live: Annotated[bool, typer.Option("--live", help="make one tiny Gemini call")] = False,gpu: Annotated[bool, typer.Option("--gpu/--no-gpu", help="probe headless Chrome WebGL")] = True,+ skills: Annotated[bool, typer.Option("--skills", help="also check the skill library and its discovery wiring")] = False,as_json: Annotated[bool, typer.Option("--json")] = False,) -> None:"""Check python deps, Blender, node/three/puppeteer, keys, CLIs and MCP."""if ctx.invoked_subcommand:return- rows = run_doctor(live=live, gpu=gpu)+ rows = run_doctor(live=live, gpu=gpu, skills=skills)if as_json:console.print_json(json.dumps([{"check": c, "status": s, "detail": d} for c, s, d in rows]))else:diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.pyindex 1519bc33..4485b43e 100644--- a/harness/codeverse/cli/main.py+++ b/harness/codeverse/cli/main.py@@ -23,6 +23,7 @@ from codeverse.cli.cost_cmd import cost_appfrom codeverse.cli.doctor import doctor_appfrom codeverse.cli.flywheel_cmd import flywheel_appfrom codeverse.cli.gallery_cmd import gallery_app+from codeverse.cli.skills_cmd import skills_appfrom codeverse.cli.texture_cmd import texture_appfrom codeverse.cli.tools_cmd import toolsfrom codeverse.config import get_settings@@ -36,6 +37,7 @@ app.add_typer(gallery_app, name="gallery", help="Look at runs locally: `serve` oapp.add_typer(bench_app, name="bench", help="Prompt batteries: run + report.")app.add_typer(cost_app, name="cost", help="Cost audit: per stage/role/model, waste, $ per passing artifact.")app.add_typer(doctor_app, name="doctor", help="Environment checks.")+app.add_typer(skills_app, name="skills", help="The skill library: list / show / validate / read-rate report.")app.add_typer(texture_app, name="texture", help="Text-to-image texturing: object pass / scene pack.")app.command("tools", help="List spatial tools or run one: `3dcv tools list` | `3dcv tools <name> --json '{...}' --workspace ws`.")(tools)diff --git a/harness/codeverse/cli/skills_cmd.py b/harness/codeverse/cli/skills_cmd.pynew file mode 100644index 00000000..75f04e5e--- /dev/null+++ b/harness/codeverse/cli/skills_cmd.py@@ -0,0 +1,153 @@+"""``3dcv skills`` — look at the library, validate it, and read the read-rate.++``report`` is the command that matters. The whole system exists because a tool that+exists is not a tool that gets used (``read_cookbook``: 0 of 16 zone sessions), so the+first question about any battery is not "did the score move" but "did anyone open the+file". Everything else here is plumbing for that answer.+"""++from __future__ import annotations++import contextlib+import json+from pathlib import Path+from typing import Annotated++import typer++from codeverse.cli._fmt import console, err_console++skills_app = typer.Typer(invoke_without_command=True, help="The skill library: list / show / validate / read-rate report.")+++@skills_app.callback(invoke_without_command=True)+def _root(ctx: typer.Context) -> None:+ if ctx.invoked_subcommand is None:+ console.print(ctx.get_help())+++@skills_app.command("list")+def list_skills(+ routes: Annotated[bool, typer.Option("--routes", help="show the rules that can attach each skill")] = False,+) -> None:+ """Every bundle in the library, with its evidence label and body size."""+ from rich.table import Table++ from codeverse.skills import iter_skills+ from codeverse.skills.registry import ROUTED_SKILLS, ROUTES++ found = list(iter_skills())+ t = Table(title="3dcv skills")+ for col in ("name", "evidence", "verified", "lines", "~tokens", "refs", *(["routes"] if routes else [])):+ t.add_column(col)+ for s in found:+ row = [s.name, s.evidence, s.verified, str(s.body_lines), str(s.body_tokens), str(len(s.references))]+ if routes:+ row.append(",".join(r.rule for r in ROUTES if r.skill == s.name))+ t.add_row(*row)+ console.print(t)+ missing = [n for n in ROUTED_SKILLS if n not in {s.name for s in found}]+ if missing:+ console.print(f"[yellow]{len(missing)} routed skill(s) have no bundle yet:[/] {', '.join(missing)}")+++@skills_app.command("show")+def show_skill(name: Annotated[str, typer.Argument(help="skill name")]) -> None:+ """Print one bundle's frontmatter and body."""+ from codeverse.skills import load_skill+ from codeverse.skills.loader import SkillError++ try:+ s = load_skill(name)+ except SkillError as e:+ err_console.print(f"[red]{e}[/]")+ raise typer.Exit(code=1) from e+ console.print(f"[bold]{s.name}[/] ({s.body_lines} lines, ~{s.body_tokens} tokens, evidence={s.evidence})")+ console.print(f"[dim]{s.path}[/]\n")+ console.print(s.description + "\n")+ console.print(s.body)+++@skills_app.command("validate")+def validate(+ strict: Annotated[bool, typer.Option("--strict", help="also fail on a routed skill with no bundle")] = False,+) -> None:+ """Check every bundle against the open spec and our budget/evidence rules."""+ from codeverse.skills import bundle_dirs, validate_bundle+ from codeverse.skills.claims import check_claims+ from codeverse.skills.loader import SkillError, parse_skill+ from codeverse.skills.registry import ROUTED_SKILLS++ dirs = bundle_dirs()+ bad = 0+ for d in dirs:+ issues = validate_bundle(d)+ with contextlib.suppress(SkillError): # a parse failure is already reported above+ issues += check_claims(parse_skill(d))+ if issues:+ bad += 1+ console.print(f"[red]FAIL[/] {d.name}")+ for i in issues:+ console.print(f" - {i}")+ else:+ console.print(f"[green]ok[/] {d.name}")+ missing = [n for n in ROUTED_SKILLS if n not in {d.name for d in dirs}]+ if missing:+ style = "red" if strict else "yellow"+ console.print(f"[{style}]{len(missing)} routed skill(s) have no bundle:[/] {', '.join(missing)}")+ console.print(f"\n{len(dirs) - bad}/{len(dirs)} bundles valid")+ if bad or (strict and missing):+ raise typer.Exit(code=1)+++@skills_app.command("report")+def report(+ runs_dir: Annotated[Path, typer.Argument(help="a runs root, a bench out dir, or one workspace")],+ as_json: Annotated[bool, typer.Option("--json")] = False,+) -> None:+ """Deep-read rate per skill and per backend — the number that replaces "0 of 16".++ Targets from the design: >= 60% for CLI backends, >= 80% for api-agent. A skill+ under 20% over 20 sessions is merged or deleted.+ """+ from rich.table import Table++ rows: list[dict] = []+ for p in sorted(Path(runs_dir).rglob("telemetry/skills.jsonl")):+ for line in p.read_text().splitlines():+ try:+ rows.append(json.loads(line))+ except json.JSONDecodeError:+ continue+ if not rows:+ err_console.print(f"[yellow]no telemetry/skills.jsonl under {runs_dir}[/] (was CV3D_SKILLS on?)")+ raise typer.Exit(code=1)++ per: dict[tuple[str, str], list[int]] = {}+ for r in rows:+ backend = str(r.get("agent", "?")).split(":", 1)[0]+ reads = {x["name"]: x for x in r.get("reads", [])}+ for name in r.get("listed", []):+ cell = per.setdefault((name, backend), [0, 0, 0])+ cell[0] += 1+ got = reads.get(name) or {}+ cell[1] += 1 if got.get("surfaced") else 0+ cell[2] += 1 if got.get("deep") else 0+ if as_json:+ console.print_json(json.dumps([+ {"skill": k[0], "backend": k[1], "listed": v[0], "surfaced": v[1], "deep": v[2],+ "deep_read_rate": round(v[2] / v[0], 3) if v[0] else None}+ for k, v in sorted(per.items())]))+ return+ t = Table(title=f"skill read rate ({len(rows)} sessions)")+ for col in ("skill", "backend", "listed", "surfaced", "deep", "deep rate", "verdict"):+ 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+ verdict = "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)+++__all__ = ["skills_app"]diff --git a/harness/codeverse/contracts/run.py b/harness/codeverse/contracts/run.pyindex 0b2540a7..ad51e790 100644--- a/harness/codeverse/contracts/run.py+++ b/harness/codeverse/contracts/run.py@@ -12,6 +12,7 @@ from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement,from codeverse.contracts.common import Usagefrom codeverse.contracts.judgment import Judgmentfrom codeverse.contracts.plan import ArticulatedPlan, GraphicsPlan, ScenePlan, StaticPlan+from codeverse.contracts.skills import SkillsUsagefrom codeverse.contracts.spec import Spec@@ -37,6 +38,8 @@ class RoundRecord(BaseModel):renders: RenderSet | None = Nonejudgment: Judgment | None = Noneusage: Usage = Field(default_factory=Usage)+ skills: SkillsUsage | None = Field(+ default=None, description="skills attached to this round's sessions, and which were actually read")started_at: datetime = Field(default_factory=lambda: datetime.now(UTC))duration_s: float = 0.0notes: str = ""diff --git a/harness/codeverse/contracts/skills.py b/harness/codeverse/contracts/skills.pynew file mode 100644index 00000000..4abf986a--- /dev/null+++ b/harness/codeverse/contracts/skills.py@@ -0,0 +1,50 @@+"""What a round did with its skills — the record shape, kept in contracts with the rest.++Lives here rather than in ``codeverse/skills`` so ``contracts`` stays a leaf package that+``flywheel``, ``gallery`` and the CLI can import without pulling the router in, and so a+stored ``record.json`` can be re-read by a build that has no skill library at all.+"""++from __future__ import annotations++from pydantic import BaseModel, Field+++class SkillRead(BaseModel):+ """The read probe's verdict for one materialised bundle (design §6.4)."""++ name: str+ surfaced: bool = Field(default=False, description="SKILL.md atime > mtime: opened by someone (a discovery scan counts)")+ deep: bool = Field(default=False, description="a references/*.md atime > mtime: the body was read and followed")+ deep_measurable: bool = Field(default=True, description="False when the bundle ships no references/ file to probe")+ body_tokens: int = 0+ first_seen_turn: int | None = Field(default=None, description="api-agent only: exact turn of the first read")+ reason: str = Field(default="", description="which route attached it, and which finding")+++class SkillsUsage(BaseModel):+ """``RoundRecord.skills`` — listed vs read vs what it cost, per round.++ The metric that replaces "0 of 16 read_cookbook calls" is :attr:`deep_read_rate`.+ """++ listed: list[str] = Field(default_factory=list)+ reads: list[SkillRead] = Field(default_factory=list)+ index_tokens: int = 0+ body_tokens_read: int = Field(default=0, description="tokens of the bodies the probe says were read deep")+ inlined: str = Field(default="", description="single-shot: the body inlined into the prompt, '' otherwise")++ @property+ def surfaced(self) -> list[str]:+ return [r.name for r in self.reads if r.surfaced]++ @property+ def deep(self) -> list[str]:+ return [r.name for r in self.reads if r.deep]++ @property+ def deep_read_rate(self) -> float | None:+ return (len(self.deep) / len(self.listed)) if self.listed else None+++__all__ = ["SkillRead", "SkillsUsage"]diff --git a/harness/codeverse/skills/__init__.py b/harness/codeverse/skills/__init__.pynew file mode 100644index 00000000..c594b380--- /dev/null+++ b/harness/codeverse/skills/__init__.py@@ -0,0 +1,111 @@+"""The 3dcv skill library: task-scoped rule sheets, routed automatically, read-measured.++A *skill* is not a renamed cookbook chapter. The cookbook stays the reference manual+(copyable code, reachable by ``read_cookbook``); a skill is <=350 lines of rules and+numbers for one recurring failure class, and it is attached to a session only when the+track / language / kind / plan / **previous round's gate findings** say it applies.++Why the library lives inside the package: every backend reads it from a materialised+workspace copy, but the source of truth ships in the wheel, so it must be package data+(``pyproject.toml`` ``[tool.setuptools.package-data]``) and be resolved through+``importlib.resources`` — a sibling wave already shipped a wheel whose starter tree was+silently empty for exactly this reason.++Public surface for the rest of the harness::++ from codeverse.skills import skills_for, attach_skills, probe_reads++``skills_for`` is pure and testable; ``attach_skills`` writes the routed bundles into a+workspace and returns what it wrote; ``probe_reads`` says afterwards which of them were+actually opened. Everything is behind ``CV3D_SKILLS`` (default off).+"""++from __future__ import annotations++import logging+import os+from collections.abc import Iterator+from pathlib import Path++from codeverse.skills.loader import SKILL_FILE, SkillError, parse_skill, validate_bundle+from codeverse.skills.model import Skill, SkillRef++log = logging.getLogger(__name__)++#: point the library somewhere else (tests, the live CLI smoke, a private overlay)+SKILLS_DIR_ENV = "CV3D_SKILLS_DIR"+++def skills_dir() -> Path:+ """The bundle root, resolved at call time so an installed wheel works too."""+ override = os.environ.get(SKILLS_DIR_ENV, "").strip()+ if override:+ return Path(override).expanduser()+ try:+ from importlib.resources import files++ return Path(str(files("codeverse.skills")))+ except Exception as e: # noqa: BLE001 — a namespace/zip install must not break a run+ log.debug("importlib.resources could not resolve the skill library (%s); using __file__", e)+ return Path(__file__).resolve().parent+++def bundle_dirs(root: Path | None = None) -> list[Path]:+ """Every directory under the library that looks like a bundle, sorted by name.++ ``_claims/`` and ``__pycache__/`` are deliberately invisible: the library shares a+ directory with this package's modules, and a pure tree is what ``skills-ref+ validate`` and the CLIs expect to walk.+ """+ base = Path(root) if root is not None else skills_dir()+ if not base.is_dir():+ return []+ return sorted((p for p in base.iterdir()+ if p.is_dir() and not p.name.startswith(("_", ".")) and (p / SKILL_FILE).is_file()),+ key=lambda p: p.name)+++def iter_skills(root: Path | None = None, *, strict: bool = False) -> Iterator[Skill]:+ """Every valid bundle. A broken one is logged and skipped unless ``strict``.++ Skipping is the right default in a run: one malformed bundle must cost that skill,+ not the battery. ``3dcv skills validate`` and the test suite pass ``strict=True``.+ """+ for d in bundle_dirs(root):+ try:+ yield parse_skill(d)+ except SkillError as e:+ if strict:+ raise+ log.warning("skill %s is invalid and will not be routed: %s", d.name, e)+++def all_skills(root: Path | None = None, *, strict: bool = False) -> dict[str, Skill]:+ """name → Skill for the whole library (empty dict when no bundles ship yet)."""+ return {s.name: s for s in iter_skills(root, strict=strict)}+++def load_skill(name: str, root: Path | None = None) -> Skill:+ """One bundle by name; raises :class:`SkillError` when it is missing or invalid."""+ base = Path(root) if root is not None else skills_dir()+ d = base / name+ if not (d / SKILL_FILE).is_file():+ raise SkillError(f"no skill {name!r} in {base}")+ return parse_skill(d)+++def skill_names(root: Path | None = None) -> list[str]:+ return [p.name for p in bundle_dirs(root)]+++from codeverse.skills.claims import check_claims, claim_values # noqa: E402+from codeverse.skills.config import skills_enabled, skills_max, skills_unverified # noqa: E402+from codeverse.skills.materialize import attach_skills, materialize_skills # noqa: E402+from codeverse.skills.router import plan_signals, select, skills_for # noqa: E402+from codeverse.skills.telemetry import probe_reads # noqa: E402++__all__ = ["SKILLS_DIR_ENV", "Skill", "SkillError", "SkillRef", "all_skills", "attach_skills", "bundle_dirs",+ "check_claims", "claim_values",+ "iter_skills", "load_skill", "materialize_skills", "plan_signals", "probe_reads", "select",+ "skill_names", "skills_dir", "skills_enabled", "skills_for", "skills_max", "skills_unverified",+ "validate_bundle"]diff --git a/harness/codeverse/skills/claims.py b/harness/codeverse/skills/claims.pynew file mode 100644index 00000000..f7b057a3--- /dev/null+++ b/harness/codeverse/skills/claims.py@@ -0,0 +1,104 @@+"""Pin every number a skill quotes to the live constant it came from.++WHY generically, and not one hand-written test per drift: the reference library shipped a+skill that told agents water is metallic for months after the code stopped agreeing, and+caught it once, by hand, for one pair of files. A skill's whole value is that its numbers+are OUR numbers; the moment ``PENETRATION_ERROR_M`` moves, the sentence quoting "10 mm" is+worse than no sentence, because it is confidently wrong.++So each bundle may carry ``skills/_claims/<name>.toml`` — deliberately OUTSIDE the bundle+directory, so ``skills-ref validate`` and every CLI's discovery walk see a pure tree::++ [[claim]]+ key = "penetration_error_m" # shared name across skills+ text = "10 mm" # must appear in the body+ python = "codeverse.spatial.connectivity:PENETRATION_ERROR_M"+ scale = 1000 # optional, applied first+ format = "{:.0f} mm" # optional, default str()++``check_claims`` asserts the constant still formats to ``text`` and that ``text`` still+appears in the body. ``claim_values`` feeds the agreement test: two skills that can be+attached to the same session may not carry two different values for one ``key``.+"""++from __future__ import annotations++import importlib+from pathlib import Path+from typing import Any++from codeverse._compat import tomllib+from codeverse.skills.model import Skill++CLAIMS_DIR = "_claims"+++def claims_path(name: str, root: Path | None = None) -> Path:+ from codeverse.skills import skills_dir++ base = Path(root) if root is not None else skills_dir()+ return base / CLAIMS_DIR / f"{name}.toml"+++def load_claims(name: str, root: Path | None = None) -> list[dict[str, Any]]:+ """The claim rows for one skill ([] when the bundle pins nothing)."""+ p = claims_path(name, root)+ if not p.is_file():+ return []+ data = tomllib.loads(p.read_text())+ rows = data.get("claim") or []+ if not isinstance(rows, list):+ raise ValueError(f"{p}: [[claim]] must be an array of tables")+ return [dict(r) for r in rows]+++def resolve(dotted: str) -> Any:+ """``module:NAME`` or ``module.NAME`` → the live object."""+ mod, _, attr = dotted.partition(":") if ":" in dotted else dotted.rpartition(".")+ if not mod or not attr:+ raise ValueError(f"claim python target {dotted!r} must be 'module:NAME'")+ return getattr(importlib.import_module(mod), attr)+++def render_claim(row: dict[str, Any]) -> str:+ """The string the live constant produces, per this row's scale/format."""+ value = resolve(str(row["python"]))+ scale = row.get("scale")+ if scale is not None:+ value = value * scale+ fmt = row.get("format")+ return format(value, "") if not fmt else str(fmt).format(value)+++def check_claims(skill: Skill, root: Path | None = None) -> list[str]:+ """Every stale or missing claim in one bundle, as human lines (empty == clean)."""+ issues: list[str] = []+ try:+ rows = load_claims(skill.name, root)+ except (ValueError, OSError) as e:+ return [f"claims file unreadable: {e}"]+ for i, row in enumerate(rows):+ where = f"claim[{i}] {row.get('key', '?')}"+ for field in ("key", "text", "python"):+ if not row.get(field):+ issues.append(f"{where}: missing `{field}`")+ if issues and issues[-1].startswith(where):+ continue+ try:+ live = render_claim(row)+ except Exception as e: # noqa: BLE001 — a bad dotted path is a claim problem+ issues.append(f"{where}: cannot resolve {row['python']!r}: {e}")+ continue+ if live != row["text"]:+ issues.append(f"{where}: the constant now renders {live!r}, the body says {row['text']!r}")+ elif row["text"] not in skill.body:+ issues.append(f"{where}: {row['text']!r} no longer appears in the body")+ return issues+++def claim_values(name: str, root: Path | None = None) -> dict[str, str]:+ """``key -> text`` for one bundle — what the agreement test compares across skills."""+ return {str(r["key"]): str(r.get("text", "")) for r in load_claims(name, root) if r.get("key")}+++__all__ = ["CLAIMS_DIR", "check_claims", "claim_values", "claims_path", "load_claims", "render_claim", "resolve"]diff --git a/harness/codeverse/skills/config.py b/harness/codeverse/skills/config.pynew file mode 100644index 00000000..ba76ac9a--- /dev/null+++ b/harness/codeverse/skills/config.py@@ -0,0 +1,70 @@+"""The three switches that gate the whole skill system — read from the environment NOW.++WHY not ``Settings``: ``codeverse.config.get_settings`` is ``lru_cache``d, so a value+read through it is frozen at first touch and an A/B arm that sets the variable after+import gets the control's behaviour. ``bench/ab_plan.py`` differs its arms only by+environment, and a wave once printed "keep, mean delta +0.344" for two byte-identical+arms because the switch it flipped was read by nothing at all+(``codeverse/tracks/plan_features.py``). So: one module, read at call time, registered+in ``plan_features.LIVE_SWITCHES``, and a test that greps the tree to prove it is read.++* ``CV3D_SKILLS`` — off by default. On = route, materialise, measure.+* ``CV3D_SKILLS_MAX`` — attached bundles per session (default 5, design §5.2 law 1).+* ``CV3D_SKILLS_UNVERIFIED`` — also route bundles labelled ``inherited-unverified``+ (cadquery / threejs today: zero graded runs, so their claims are carried, not measured).+"""++from __future__ import annotations++import logging+import os++log = logging.getLogger(__name__)++SKILLS_ENV = "CV3D_SKILLS"+SKILLS_MAX_ENV = "CV3D_SKILLS_MAX"+SKILLS_UNVERIFIED_ENV = "CV3D_SKILLS_UNVERIFIED"++DEFAULT_SKILLS_MAX = 5+_TRUE = frozenset({"1", "on", "true", "yes", "y"})+_FALSE = frozenset({"", "0", "off", "false", "no", "n"})+++def _flag(env: str, default: bool = False) -> bool:+ raw = os.environ.get(env, "").strip().lower()+ if raw in _TRUE:+ return True+ if raw in _FALSE:+ return default+ log.warning("%s=%r is not a boolean; treating it as %s", env, raw, "on" if default else "off")+ return default+++def skills_enabled() -> bool:+ """Is the skill system on for this process? Default OFF until the A/B says otherwise."""+ return _flag(SKILLS_ENV)+++def skills_unverified() -> bool:+ """Route bundles whose evidence label is ``inherited-unverified``? Default no."""+ return _flag(SKILLS_UNVERIFIED_ENV)+++def skills_max(default: int = DEFAULT_SKILLS_MAX) -> int:+ """Cap on bundles attached to one session. A bad value falls back, never crashes a run."""+ raw = os.environ.get(SKILLS_MAX_ENV, "").strip()+ if not raw:+ return default+ try:+ n = int(raw)+ except ValueError:+ log.warning("%s=%r is not an integer; using %d", SKILLS_MAX_ENV, raw, default)+ return default+ if n < 0:+ log.warning("%s=%d is negative; using 0", SKILLS_MAX_ENV, n)+ return 0+ return n+++__all__ = ["DEFAULT_SKILLS_MAX", "SKILLS_ENV", "SKILLS_MAX_ENV", "SKILLS_UNVERIFIED_ENV",+ "skills_enabled", "skills_max", "skills_unverified"]diff --git a/harness/codeverse/skills/loader.py b/harness/codeverse/skills/loader.pynew file mode 100644index 00000000..3f993a38--- /dev/null+++ b/harness/codeverse/skills/loader.py@@ -0,0 +1,170 @@+"""Parse and validate one SKILL.md bundle against the open Agent Skills spec.++WHY this is strict: four of the five agent kinds this harness drives (claude-code,+codex, gemini-cli, agy) discover ``SKILL.md`` **themselves**. A bundle we accept but+they reject is invisible — the run still passes, the skill simply never appears, and+the read-rate metric reports a zero we would misread as "the model ignored it". So the+loader enforces the spec's own rules here, where a test can see them, rather than+finding out from a CLI upgrade six batteries later.++Enforced (agentskills.io, Dec 2025):+ * ``name``: 1-64 chars, ``^[a-z0-9]+(-[a-z0-9]+)*$``, and EQUAL to the parent+ directory name — every discovery implementation keys off the directory.+ * ``description``: 1-1024 chars, and it is the only text a CLI indexes, so it must+ carry both halves (what / when).+ * no ``<`` or ``>`` anywhere in the frontmatter — the spec's prompt-injection rule.+ * only spec keys at the top level; our own fields live under ``metadata`` (a+ string→string map), which is what keeps ``skills-ref validate`` happy.+Budget and evidence rules (ours, design §3/§5.2) are reported by :func:`validate_bundle`+rather than raised, so `3dcv skills validate` can list every problem in one pass.+"""++from __future__ import annotations++import logging+import re+from pathlib import Path++import yaml++from codeverse.skills.model import EVIDENCE_LEVELS, Skill++log = logging.getLogger(__name__)++SKILL_FILE = "SKILL.md"+REFERENCES_DIR = "references"++NAME_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")+NAME_MAX = 64+DESCRIPTION_MAX = 1024+COMPATIBILITY_MAX = 500+#: our body cap: half the spec's recommended 500 lines / 5,000 tokens, because+#: docs/COST.md §4 shows we pay for every prompt byte on every turn, not once.+BODY_MAX_LINES = 350+BODY_MAX_TOKENS = 2500+#: the spec's top-level keys. Anything else belongs in `metadata`.+SPEC_KEYS = frozenset({"name", "description", "license", "compatibility", "metadata", "allowed-tools"})++_FRONTMATTER = re.compile(r"\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*\r?\n?", re.S)+++class SkillError(ValueError):+ """A bundle that the spec — or a CLI implementing it — would reject."""+++def split_frontmatter(text: str) -> tuple[str, str]:+ """``(frontmatter_yaml, body)``; raises when the leading ``---`` block is missing."""+ m = _FRONTMATTER.match(text.lstrip(""))+ if not m:+ raise SkillError("missing YAML frontmatter: the file must start with a '---' line")+ return m.group(1), text[m.end():]+++def _as_str_map(value: object, where: str) -> dict[str, str]:+ if value is None:+ return {}+ if not isinstance(value, dict):+ raise SkillError(f"{where} must be a mapping of strings, got {type(value).__name__}")+ out: dict[str, str] = {}+ for k, v in value.items():+ if isinstance(v, (dict, list)):+ raise SkillError(f"{where}.{k} must be a scalar (the spec allows string→string only)")+ out[str(k)] = "" if v is None else str(v)+ return out+++def parse_skill(path: Path) -> Skill:+ """Read ``<dir>/SKILL.md`` into a :class:`Skill`, or raise :class:`SkillError`."""+ path = Path(path)+ if path.is_dir():+ path = path / SKILL_FILE+ if not path.is_file():+ raise SkillError(f"no {SKILL_FILE} at {path}")+ raw = path.read_text(encoding="utf-8")+ fm_text, body = split_frontmatter(raw)+ if "<" in fm_text or ">" in fm_text:+ raise SkillError("frontmatter contains '<' or '>': the spec forbids them (prompt-injection rule)")+ try:+ data = yaml.safe_load(fm_text) or {}+ except yaml.YAMLError as e:+ raise SkillError(f"frontmatter is not valid YAML: {e}") from e+ if not isinstance(data, dict):+ raise SkillError("frontmatter must be a YAML mapping")++ unknown = sorted(set(data) - SPEC_KEYS)+ if unknown:+ raise SkillError(f"unknown frontmatter key(s) {unknown}; put your own fields under `metadata`")++ name = str(data.get("name") or "").strip()+ dir_name = path.parent.name+ if not name:+ raise SkillError("frontmatter has no `name`")+ if len(name) > NAME_MAX or not NAME_RE.match(name):+ raise SkillError(f"name {name!r} must match {NAME_RE.pattern} and be <= {NAME_MAX} chars")+ if name != dir_name:+ raise SkillError(f"name {name!r} != directory name {dir_name!r}; every CLI keys discovery off the directory")++ description = str(data.get("description") or "").strip()+ if not description:+ raise SkillError(f"{name}: frontmatter has no `description` (a CLI indexes nothing else)")+ if len(description) > DESCRIPTION_MAX:+ raise SkillError(f"{name}: description is {len(description)} chars, the spec allows {DESCRIPTION_MAX}")++ compatibility = str(data.get("compatibility") or "").strip()+ if len(compatibility) > COMPATIBILITY_MAX:+ raise SkillError(f"{name}: compatibility is {len(compatibility)} chars, the spec allows {COMPATIBILITY_MAX}")++ return Skill(+ name=name,+ description=description,+ body=body,+ license=str(data.get("license") or "").strip(),+ compatibility=compatibility,+ metadata=_as_str_map(data.get("metadata"), "metadata"),+ dir=path.parent,+ references=_references(path.parent),+ )+++def _references(bundle: Path) -> tuple[str, ...]:+ d = bundle / REFERENCES_DIR+ if not d.is_dir():+ return ()+ return tuple(sorted(f"{REFERENCES_DIR}/{p.name}" for p in d.iterdir() if p.is_file()))+++def validate_bundle(bundle: Path) -> list[str]:+ """Every problem with one bundle directory, as human lines (empty == clean).++ Structural problems come back as one line; budget/evidence/layout problems are+ listed together so `3dcv skills validate` fixes a bundle in one round trip.+ """+ bundle = Path(bundle)+ try:+ skill = parse_skill(bundle)+ except SkillError as e:+ return [str(e)]+ issues: list[str] = []+ if skill.body_lines > BODY_MAX_LINES:+ issues.append(f"body is {skill.body_lines} lines, cap is {BODY_MAX_LINES} — move depth into {REFERENCES_DIR}/")+ if skill.body_tokens > BODY_MAX_TOKENS:+ issues.append(f"body is ~{skill.body_tokens} tokens, cap is {BODY_MAX_TOKENS}")+ if not skill.body.strip():+ issues.append("body is empty")+ if skill.evidence not in EVIDENCE_LEVELS:+ issues.append(f"metadata.evidence must be one of {list(EVIDENCE_LEVELS)}, got {skill.evidence!r}")+ if not skill.metadata.get("verified"):+ issues.append("metadata.verified (ISO date the claims were last checked) is missing")+ refs = bundle / REFERENCES_DIR+ if refs.is_dir():+ for p in refs.iterdir():+ if p.is_dir():+ issues.append(f"{REFERENCES_DIR}/{p.name}/ is a second level; the spec allows one level of references")+ for p in bundle.rglob("*"):+ if p.is_symlink():+ issues.append(f"{p.relative_to(bundle)} is a symlink; codex refuses symlinks inside a skill tree")+ return issues+++__all__ = ["BODY_MAX_LINES", "BODY_MAX_TOKENS", "DESCRIPTION_MAX", "NAME_MAX", "NAME_RE", "REFERENCES_DIR",+ "SKILL_FILE", "SPEC_KEYS", "SkillError", "parse_skill", "split_frontmatter", "validate_bundle"]diff --git a/harness/codeverse/skills/materialize.py b/harness/codeverse/skills/materialize.pynew file mode 100644index 00000000..67b1bc37--- /dev/null+++ b/harness/codeverse/skills/materialize.py@@ -0,0 +1,168 @@+"""Write the routed bundles into a workspace, as real files, twice.++WHY twice: the discovery roots were read out of the shipped binaries, not assumed.+gemini-cli, codex and agy all read ``<ws>/.agents/skills/<name>/SKILL.md``; claude-code+2.1 reads ``<ws>/.claude/skills/<name>/SKILL.md`` and has **no** ``.agents`` skill root at+all (its ``.agents`` strings are plugin-migration paths). So the same bytes go to both.++WHY copies and not symlinks: codex refuses them outright ("Symbolic links are not allowed+in skills"). A 2-10 KB duplicate in a disposable workspace costs nothing.++WHY ``os.utime`` at the end: the read probe in ``telemetry.py`` says a bundle was opened+when ``atime > mtime``. That only means anything if the two start equal, so+materialisation stamps them equal instead of trusting whatever the copy left behind.+"""++from __future__ import annotations++import logging+import os+import shutil+import time+from collections.abc import Sequence+from pathlib import Path+from typing import Any++from codeverse.skills.config import skills_max, skills_unverified+from codeverse.skills.model import Selection, Skill, SkillsMaterialized+from codeverse.skills.prompting import (+ AGENTS_SKILL_ROOT,+ CLAUDE_SKILL_ROOT,+ index_block,+ index_tokens,+ inline_body,+)+from codeverse.skills.router import plan_signals, select++log = logging.getLogger(__name__)++SKILL_ROOTS = (AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT)+#: the AGENTS.md/GEMINI.md/CLAUDE.md body files a workspace already has+BODY_FILES = ("AGENTS.md", "GEMINI.md", "CLAUDE.md")+MARK_BEGIN = "<!-- 3dcv:skills -->"+MARK_END = "<!-- /3dcv:skills -->"+++def _copy_bundle(skill: Skill, dest_root: Path) -> list[Path]:+ dest = dest_root / skill.name+ if dest.exists():+ shutil.rmtree(dest)+ dest.mkdir(parents=True, exist_ok=True)+ written: list[Path] = []+ shutil.copyfile(skill.path, dest / "SKILL.md")+ written.append(dest / "SKILL.md")+ for rel in skill.references:+ src = skill.dir / rel+ if not src.is_file():+ continue+ out = dest / rel+ out.parent.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(src, out)+ written.append(out)+ return written+++def materialize_skills(ws_root: Path, skills: Sequence[Skill]) -> list[Path]:+ """Copy each bundle into both discovery roots; returns every file written.++ Stale bundles from a previous round are removed, so the workspace always shows the+ set this round actually routed — otherwise the read probe would credit a skill that+ a later round no longer attaches.+ """+ root = Path(ws_root)+ wanted = {s.name for s in skills}+ written: list[Path] = []+ for rel in SKILL_ROOTS:+ base = root / rel+ base.mkdir(parents=True, exist_ok=True)+ for old in base.iterdir():+ if old.is_dir() and old.name not in wanted:+ shutil.rmtree(old, ignore_errors=True)+ for s in skills:+ written += _copy_bundle(s, base)+ now = time.time()+ for p in written:+ os.utime(p, (now, now)) # atime == mtime: the read probe's zero point+ return written+++def write_index(ws_root: Path, text: str) -> list[str]:+ """Replace (or append) the marked skills section in every agent body file.++ A marked section rather than a rewrite of the body: ``agents/materialize.py`` writes+ the body once per run, but the routed set changes per round, and rewriting the whole+ file from here would duplicate its knowledge of what belongs in it.+ """+ block = f"{MARK_BEGIN}\n{text.strip()}\n{MARK_END}\n" if text.strip() else ""+ out: list[str] = []+ for name in BODY_FILES:+ p = Path(ws_root) / name+ if not p.is_file():+ continue+ body = p.read_text()+ if MARK_BEGIN in body and MARK_END in body:+ head, rest = body.split(MARK_BEGIN, 1)+ _, tail = rest.split(MARK_END, 1)+ body = head + block + tail.lstrip("\n")+ elif block:+ body = body.rstrip("\n") + "\n\n" + block+ p.write_text(body)+ out.append(str(p))+ return out+++def attach_skills(+ ws_root: Path,+ *,+ track: str,+ language: str,+ kind: str,+ agent_kind: str,+ plan: Any | None = None,+ findings: Any = (),+ single_shot: bool = False,+ library: dict[str, Skill] | None = None,+ max_skills: int | None = None,+ allow_unverified: bool | None = None,+) -> SkillsMaterialized:+ """Route → write → return what a session will see. The one entry point tracks call.++ The caller decides whether the feature is on (``config.skills_enabled``); this+ function assumes it is, so a test can attach without setting the environment.+ """+ sel: list[Selection] = select(+ track, language, kind,+ signals=plan_signals(plan), findings=findings, library=library,+ max_skills=skills_max() if max_skills is None else max_skills,+ allow_unverified=skills_unverified() if allow_unverified is None else allow_unverified,+ )+ out = SkillsMaterialized(listed=[s.name for s in sel], selections=list(sel),+ reasons={s.name: s.reason for s in sel})+ if not sel:+ write_index(ws_root, "")+ return out++ if single_shot:+ # No read loop: a pointer to a file it cannot open would be pure cost.+ name, text = inline_body(sel)+ out.inlined = name+ out.index_tokens = 0+ if not name:+ out.warnings.append("single-shot: every routed body is over the inline cap; nothing inlined")+ write_index(ws_root, "")+ return out++ try:+ paths = materialize_skills(ws_root, [s.skill for s in sel])+ except OSError as e: # a workspace we cannot write is a run problem, not a skills problem+ out.warnings.append(f"could not materialise skills: {e}")+ log.warning("skills not materialised into %s: %s", ws_root, e)+ return out+ out.paths = [str(p) for p in paths]+ out.index_tokens = index_tokens(sel, agent_kind)+ write_index(ws_root, index_block(sel, agent_kind))+ return out+++__all__ = ["BODY_FILES", "MARK_BEGIN", "MARK_END", "SKILL_ROOTS", "attach_skills",+ "materialize_skills", "write_index"]diff --git a/harness/codeverse/skills/model.py b/harness/codeverse/skills/model.pynew file mode 100644index 00000000..3cebcac6--- /dev/null+++ b/harness/codeverse/skills/model.py@@ -0,0 +1,119 @@+"""Typed shapes for the skill library — one bundle, one selection, one session's usage.++Frozen on purpose: a ``Skill`` is parsed from a file on disk once and then flows into+prompts, workspaces and the run record. If any of those could mutate it, the body we+measured (``body_tokens``) and the body we materialised could silently differ, and the+telemetry in §6.4 of the design would be measuring a file nobody sent.+"""++from __future__ import annotations++from pathlib import Path++from pydantic import BaseModel, Field++from codeverse.contracts.skills import SkillRead, SkillsUsage+from codeverse.cost.guard import text_tokens++#: `metadata.evidence` values. A bundle whose claims are carried over from a reference+#: library but which our own corpus cannot back yet is `inherited-unverified`, and the+#: router refuses it unless CV3D_SKILLS_UNVERIFIED is on (design §5.2 law 3).+EVIDENCE_MEASURED = "measured"+EVIDENCE_INHERITED = "inherited-unverified"+EVIDENCE_MIXED = "mixed"+EVIDENCE_LEVELS = (EVIDENCE_MEASURED, EVIDENCE_MIXED, EVIDENCE_INHERITED)+++class Skill(BaseModel):+ """One SKILL.md bundle, parsed and validated against the open spec (agentskills.io)."""++ model_config = {"frozen": True}++ name: str = Field(description="lowercase-hyphen id; equals the parent directory name")+ description: str = Field(description="what it does AND when to use it; the only text a CLI indexes")+ body: str = Field(default="", description="everything after the frontmatter")+ license: str = ""+ compatibility: str = ""+ metadata: dict[str, str] = Field(default_factory=dict)+ dir: Path = Field(description="the bundle directory (contains SKILL.md)")+ references: tuple[str, ...] = Field(default_factory=tuple, description="references/*.md, bundle-relative")++ @property+ def path(self) -> Path:+ return self.dir / "SKILL.md"++ @property+ def body_tokens(self) -> int:+ """Estimated prompt tokens of the body — the number the budget test asserts."""+ return text_tokens(self.body)++ @property+ def body_lines(self) -> int:+ return len(self.body.splitlines())++ @property+ def evidence(self) -> str:+ return self.metadata.get("evidence", EVIDENCE_INHERITED)++ @property+ def verified(self) -> str:+ """ISO date the bundle's claims were last checked against the harness."""+ return self.metadata.get("verified", "")++ @property+ def when_to_use(self) -> str:+ """Optional long form of the *when* half of ``description`` (metadata key)."""+ return self.metadata.get("when_to_use", "")++ def ref(self) -> SkillRef:+ return SkillRef(name=self.name, description=self.description, body_tokens=self.body_tokens)+++class SkillRef(BaseModel):+ """A skill without its body — what the index block and the run record carry."""++ model_config = {"frozen": True}++ name: str+ description: str+ body_tokens: int = 0+++class Selection(BaseModel):+ """One routed skill **with the reason it was routed**, so telemetry can say WHY.++ astra3d had a human type ``skills: [...]``; we derive the set, which is only an+ improvement if the derivation is auditable after the fact.+ """++ model_config = {"frozen": True}++ skill: Skill+ priority: int+ rules: tuple[str, ...] = Field(description="rule ids that fired, e.g. ('R1', 'R2')")+ reason: str = Field(description="one human line: which rule, and which finding if any")++ @property+ def name(self) -> str:+ return self.skill.name++ @property+ def gate_fired(self) -> bool:+ """True when a previous-round gate finding routed this (design §5.2 law 2)."""+ return self.priority >= 90+++class SkillsMaterialized(BaseModel):+ """What :func:`codeverse.skills.materialize.materialize_skills` wrote into a workspace."""++ listed: list[str] = Field(default_factory=list, description="skill names, in attach order")+ selections: list[Selection] = Field(default_factory=list, description="the routed rows, with the reason each fired")+ paths: list[str] = Field(default_factory=list, description="every SKILL.md written (both roots)")+ reasons: dict[str, str] = Field(default_factory=dict, description="name → why it was attached")+ index_tokens: int = Field(default=0, description="estimated tokens the index/mandate adds to message 0")+ inlined: str = Field(default="", description="single-shot: the one body inlined, '' otherwise")+ warnings: list[str] = Field(default_factory=list)+++__all__ = ["EVIDENCE_INHERITED", "EVIDENCE_LEVELS", "EVIDENCE_MEASURED", "EVIDENCE_MIXED",+ "Selection", "Skill", "SkillRead", "SkillRef", "SkillsMaterialized", "SkillsUsage"]diff --git a/harness/codeverse/skills/prompting.py b/harness/codeverse/skills/prompting.pynew file mode 100644index 00000000..95c89599--- /dev/null+++ b/harness/codeverse/skills/prompting.py@@ -0,0 +1,103 @@+"""The per-backend text — deliberately the smallest thing that can work.++``docs/COST.md`` §13 measured a stable-prefix-first reordering that duplicated the shared+head into four templates: **+2,925 tokens on the average call**, and it still never+reached Gemini's implicit-cache floor, so it was reverted. The lesson the skill system+inherits: **do not invent a new prompt head.** Everything below only adds to text that is+already being sent, and each backend gets the least text that reaches it:++* claude-code / codex / gemini-cli / agy discover ``SKILL.md`` themselves. Writing our+ own index would double-index the same bundles, so they get ONE sentence (~35 tokens).+* api-agent has no loader, so it gets a one-line-per-skill index inside the AGENTS.md+ body, which is already message 0 of the session.+* a single-shot call has no read loop at all: it gets ONE body inlined, so the cost is+ explicit and bounded instead of a pointer nobody can follow.+* on a repair round the gate-fired skills are named beside the findings they answer, in+ the volatile tail — ``tracks/repair.py`` already picks a cookbook section by keyword,+ this is the same idea one level up.++The mandate sentence is 化用'd from the reference block and ~90% shorter: theirs re-asserts+a score claim in every prompt, and a score claim belongs in a measured report.+"""++from __future__ import annotations++from collections.abc import Sequence++from codeverse.cost.guard import text_tokens+from codeverse.skills.model import Selection, Skill++#: where a materialised bundle lives, relative to the workspace root (the `.agents` root+#: is the one gemini-cli, codex and agy all read; claude-code reads its own copy).+AGENTS_SKILL_ROOT = ".agents/skills"+CLAUDE_SKILL_ROOT = ".claude/skills"++#: backends whose own loader indexes the bundles; they must NOT be handed a second index+NATIVE_LOADERS = ("claude-code", "codex", "gemini-cli", "agy")++MANDATE = ("Skills for this task are installed in this workspace. Any whose description matches "+ "your task are MANDATORY — activate and read them before writing code.")++_HEADING = "## Skills"+++def skill_path(name: str, *, agent_kind: str = "") -> str:+ root = CLAUDE_SKILL_ROOT if agent_kind == "claude-code" else AGENTS_SKILL_ROOT+ return f"{root}/{name}/SKILL.md"+++def index_block(skills: Sequence[Skill | Selection], agent_kind: str) -> str:+ """The text appended to the AGENTS.md body for ``agent_kind`` ('' when nothing is added).++ Native-loader backends get the mandate only; api-agent (and anything unknown, which+ is the safe assumption) also gets the one-line-per-skill index it cannot discover.+ """+ items = [s.skill if isinstance(s, Selection) else s for s in skills]+ if not items:+ return ""+ if agent_kind in NATIVE_LOADERS:+ return f"{_HEADING}\n\n{MANDATE}\n"+ lines = [f"- **{s.name}** — {s.description} Read `{skill_path(s.name, agent_kind=agent_kind)}` BEFORE writing code."+ for s in items]+ return f"{_HEADING}\n\n{MANDATE}\n\n" + "\n".join(lines) + "\n"+++def index_tokens(skills: Sequence[Skill | Selection], agent_kind: str) -> int:+ """What the index costs in message 0 — recorded per round so §5.4 is auditable."""+ return text_tokens(index_block(skills, agent_kind))+++def repair_pointers(selections: Sequence[Selection], *, agent_kind: str = "",+ answering: Sequence[str] = ()) -> str:+ """Name the skills that answer THIS failure, beside it (repair rounds only).++ Two ways in: a selection that a previous round's gate already routed, and a name in+ ``answering`` — the skills whose routes cover a finding the current build/lint just+ produced, which is discovered after the round attached its set. Everything else is+ left out: the standing sheets are already in the workspace, and repeating them in the+ volatile tail would pay twice for the same text and say nothing new.+ """+ want = set(answering)+ fired = [s for s in selections if s.gate_fired or s.name in want]+ if not fired:+ return ""+ lines = ["Skills that answer these findings — read before editing:"]+ lines += [f"- {s.name}: {s.reason.split(': ', 1)[-1]} → `{skill_path(s.name, agent_kind=agent_kind)}`"+ for s in fired]+ return "\n".join(lines)+++def inline_body(selections: Sequence[Selection], *, max_tokens: int = 2500) -> tuple[str, str]:+ """``(name, text)`` for the single-shot arm: the one highest-priority body, inlined.++ A single-shot call cannot open a file, so a pointer would be a cost with no benefit+ and would quietly make the arm incomparable with the agent arms. One body, capped.+ """+ for s in selections:+ if s.skill.body_tokens <= max_tokens:+ return s.name, f"{_HEADING} — {s.name}\n\n{s.skill.description}\n\n{s.skill.body.strip()}\n"+ return "", ""+++__all__ = ["AGENTS_SKILL_ROOT", "CLAUDE_SKILL_ROOT", "MANDATE", "NATIVE_LOADERS",+ "index_block", "index_tokens", "inline_body", "repair_pointers", "skill_path"]diff --git a/harness/codeverse/skills/registry.py b/harness/codeverse/skills/registry.pynew file mode 100644index 00000000..77ec7b5d--- /dev/null+++ b/harness/codeverse/skills/registry.py@@ -0,0 +1,246 @@+"""The routing table (design §5.2) and the ONE place gate message text is pattern-matched.++Two things live here and nowhere else:++**finding_kind()** — ``GateFinding`` carries no ``kind`` field (``contracts/artifacts.py``),+so turning "'Lid' and 'Body' interpenetrate by ~7.4 mm" into the stable slug+``connectivity/interpenetration`` needs a classifier. Keeping it in one function means a+gate reword breaks one golden test instead of silently unrouting a repair skill. It+classifies **actionable** findings only: INFO lines ("named objects: [...]") are census,+not defects, and return ``None``.++**ROUTES** — typed rows, evaluated by ``router.py``. A row fires when ALL of its stated+conditions hold; ``priority`` decides who survives the cap, and every gate-fired row sits+at >= 90 so a repair round spends its budget on what actually broke.++Classification is deliberately WIDER than routing: several kinds below have no rule at+all. Naming a defect costs nothing and lets the golden test assert full coverage of the+corpus; routing one is a claim that a skill helps, and that claim needs evidence.+"""++from __future__ import annotations++import re+from dataclasses import dataclass++# --------------------------------------------------------------------------- finding kinds+CONNECTIVITY_INTERPENETRATION = "connectivity/interpenetration"+CONNECTIVITY_STRAY_ISLANDS = "connectivity/stray_islands"+CONNECTIVITY_FLOATING_PART = "connectivity/floating_part"+CONNECTIVITY_NO_GROUND = "connectivity/no_ground_contact"+CONNECTIVITY_NO_GEOMETRY = "connectivity/no_geometry"+CONTRACT_PART_BBOX = "contract/part_bbox"+CONTRACT_INSTANCE_BBOX = "contract/instance_bbox"+CONTRACT_OVERALL_BBOX = "contract/overall_bbox"+CONTRACT_FOOTPRINT = "contract/footprint_offset"+CONTRACT_GROUND_GAP = "contract/ground_gap"+CONTRACT_MISSING_PART = "contract/missing_part"+CONTRACT_INSTANCE_COUNT = "contract/instance_count"+CONTRACT_SCENE_BOUNDS = "contract/scene_bounds"+JOINT_SWEEP_LINK_OVERLAP = "joint_sweep/link_overlap"+JOINT_SWEEP_DISCONNECTED = "joint_sweep/disconnected"+MOTION_WRONG_AXIS = "motion_direction/wrong_axis"+MOTION_SKIPPED = "motion_direction/skipped"+SCENE_DARK_OR_FLAT = "scene_frames/dark_or_flat"+SCENE_CAMERA_PLACEMENT = "scene_frames/camera_placement"+GL_MOTION_OR_DETAIL = "gl_frames/motion_or_detail"+LINT_PART_NOT_IMPORTED = "lint/part_not_imported"+LINT_LINK_NAME = "lint/link_name"+LINT_API_TRAP = "lint/api_trap"+SHADER_COMPILE_OR_BINDING = "shader/compile_or_binding"+DETAIL_DRIFT = "detail_drift/part_moved"+RUNTIME_SLOW = "render_console/slow_or_error"++#: (gate predicate, message regex, kind). Order matters: first match wins.+_RULES: tuple[tuple[str, str, str], ...] = (+ ("connectivity", r"interpenetrate", CONNECTIVITY_INTERPENETRATION),+ ("connectivity", r"tiny disconnected island", CONNECTIVITY_STRAY_ISLANDS),+ ("connectivity", r"is floating", CONNECTIVITY_FLOATING_PART),+ ("connectivity", r"no part touches the ground", CONNECTIVITY_NO_GROUND),+ ("connectivity", r"no mesh parts", CONNECTIVITY_NO_GEOMETRY),+ ("contract", r"\(each instance\)|\(all instances\)", CONTRACT_INSTANCE_BBOX),+ ("contract", r"part '.*' bbox deviates", CONTRACT_PART_BBOX),+ ("contract", r"overall bbox deviates", CONTRACT_OVERALL_BBOX),+ ("contract", r"footprint centre", CONTRACT_FOOTPRINT),+ ("contract", r"floats .* the ground", CONTRACT_GROUND_GAP),+ ("contract", r"missing from the GLB|not found in the exported scene", CONTRACT_MISSING_PART),+ ("contract", r"instance\(s\), plan asks for", CONTRACT_INSTANCE_COUNT),+ ("contract", r"exceeds the planned bounds", CONTRACT_SCENE_BOUNDS),+ ("joint_sweep", r"overlap by", JOINT_SWEEP_LINK_OVERLAP),+ ("joint_sweep", r"apart at rest|nothing physically connects", JOINT_SWEEP_DISCONNECTED),+ ("motion_direction", r"check skipped|checks skipped", MOTION_SKIPPED),+ ("motion_direction", r"WRONG", MOTION_WRONG_AXIS),+ ("scene_frames", r"too dark|flat frame", SCENE_DARK_OR_FLAT),+ ("scene_frames", r"BELOW the ground|inside / touching geometry", SCENE_CAMERA_PLACEMENT),+ ("gl_frames", r"frame-to-frame|visual detail", GL_MOTION_OR_DETAIL),+ ("detail_drift", r"moved|resized|removed|added", DETAIL_DRIFT),+ ("render_console", r"frame rate|error", RUNTIME_SLOW),+ ("shader_preflight", r".", SHADER_COMPILE_OR_BINDING),+ ("lint", r"never imported", LINT_PART_NOT_IMPORTED),+ ("lint", r"never appears as a string", LINT_LINK_NAME),+ ("lint", r"unbound|uniform|ignores scene\.fog|shader (?:fail|error|compile)", SHADER_COMPILE_OR_BINDING),+ ("lint", r".", LINT_API_TRAP),+)+_COMPILED = tuple((gate, re.compile(pat, re.I), kind) for gate, pat, kind in _RULES)+++def finding_kind(gate: str, message: str, severity: str = "warn") -> str | None:+ """``(gate, message)`` → a stable defect slug, or ``None`` for census/INFO lines.++ ``severity`` is honoured, not guessed at: an INFO finding is the gate reporting what+ it saw ("all 7 parts are connected"), and routing a skill off it would attach the+ interpenetration sheet to a run with no interpenetration.+ """+ if str(severity).lower() == "info":+ return None+ g = (gate or "").strip().lower()+ text = message or ""+ for want, pattern, kind in _COMPILED:+ if (g == want or (want == "lint" and g.startswith("lint:"))) and pattern.search(text):+ return kind+ return None+++def finding_kinds(findings: object) -> list[str]:+ """Distinct kinds of an iterable of ``GateFinding`` (or of ``GateReport``s), in order."""+ out: list[str] = []+ for f in _iter_findings(findings):+ k = finding_kind(getattr(f, "gate", ""), getattr(f, "message", ""),+ str(getattr(f, "severity", "warn")))+ if k and k not in out:+ out.append(k)+ return out+++def _iter_findings(obj: object):+ for item in obj or (): # type: ignore[union-attr]+ inner = getattr(item, "findings", None)+ if inner is not None:+ yield from inner+ else:+ yield item+++# --------------------------------------------------------------------------- routes+OBJECT_TRACKS = ("static_object", "articulated_object")+BLENDER_LANGS = ("blender", "urdf_blender")+THREEJS_LANGS = ("scene_threejs", "threejs")+BUILD_KINDS = ("baseline", "part", "detail", "refine", "rebuild", "repair")+#: kinds that attach nothing on their own (design §5.2 law 4): short, narrow sessions the+#: corpus attaches no defect class to. A gate-fired row still reaches them.+QUIET_KINDS = ("asset", "asset_fix", "reference")+++@dataclass(frozen=True)+class Route:+ """One row of the table. Empty tuple == "any"; ``findings`` == "a gate fired"."""++ rule: str+ skill: str+ priority: int+ tracks: tuple[str, ...] = ()+ languages: tuple[str, ...] = ()+ kinds: tuple[str, ...] = ()+ requires_all: tuple[str, ...] = ()+ requires_any: tuple[str, ...] = ()+ findings: tuple[str, ...] = ()+ why: str = ""++ @property+ def gate_fired(self) -> bool:+ return bool(self.findings)++ def matches_finding(self, kinds: list[str]) -> str | None:+ """The first routed finding kind this row answers, or None."""+ for pat in self.findings:+ family = pat[:-1] if pat.endswith("*") else ""+ for k in kinds:+ if (family and k.startswith(family)) or k == pat:+ return k+ return None+++ROUTES: tuple[Route, ...] = (+ Route("R1", "cv3d-part-contact", 70, tracks=OBJECT_TRACKS, requires_all=("multi_part",),+ why="a multi-part object: contact, penetration and stray islands are the top defect class (50.5% of runs)"),+ Route("R2", "cv3d-part-contact", 95, kinds=("repair", "refine", "rebuild"),+ findings=("connectivity/*", "joint_sweep/*"),+ why="the previous round's connectivity/joint gate fired"),+ Route("R3", "cv3d-bbox-contract", 65, tracks=(*OBJECT_TRACKS, "scene"),+ kinds=("baseline", "part", "detail", "refine", "rebuild", "zone"),+ why="this session owns dimensions, and the plan's numbers are the contract"),+ Route("R4", "cv3d-bbox-contract", 95, kinds=("repair", "refine", "rebuild"), findings=("contract/*",),+ why="the previous round's contract gate fired"),+ Route("R5", "cv3d-form-manifest", 60, tracks=OBJECT_TRACKS, kinds=("baseline", "part", "detail", "rebuild"),+ why="a session that still decides WHAT shapes to build (a repair session is not re-planning)"),+ Route("R6", "cv3d-repeats-and-mirrors", 55, tracks=OBJECT_TRACKS,+ kinds=("baseline", "part", "detail", "refine", "rebuild"),+ requires_any=("has_instances", "has_symmetry"),+ why="the plan repeats or mirrors a part, and the contract gate measures each instance"),+ Route("R7", "cv3d-repeats-and-mirrors", 90, kinds=("repair", "refine"), findings=("contract/instance_bbox",),+ why="an instanced part's bbox drifted"),+ Route("R8", "cv3d-blender-forms", 75, languages=BLENDER_LANGS, kinds=BUILD_KINDS,+ why="blender authoring: the language of 47 of our graded runs"),+ Route("R9", "cv3d-blender-forms", 95, languages=BLENDER_LANGS, kinds=("repair",),+ findings=(LINT_PART_NOT_IMPORTED,),+ why="a part file was written but never imported, so its geometry does not exist"),+ Route("R10", "cv3d-cadquery-forms", 75, languages=("cadquery",), kinds=BUILD_KINDS,+ why="cadquery authoring (evidence: inherited-unverified — 0 graded runs, routed off by default)"),+ Route("R11", "cv3d-threejs-forms", 75, tracks=("static_object",), languages=("threejs",), kinds=BUILD_KINDS,+ why="three.js object authoring (evidence: inherited-unverified — 0 graded runs, routed off by default)"),+ Route("R12", "cv3d-urdf-joints", 80, tracks=("articulated_object",), languages=("urdf_blender",),+ kinds=("baseline", "refine", "rebuild", "repair"),+ why="joints, limits and axes: joint_sweep fires on 38% and motion_direction on 35% of urdf runs"),+ Route("R13", "cv3d-urdf-joints", 95, tracks=("articulated_object",), languages=("urdf_blender",),+ findings=("joint_sweep/*", "motion_direction/*"),+ why="a joint_sweep or motion_direction gate fired on the previous round"),+ Route("R14", "cv3d-scene-composition", 75, tracks=("scene",), languages=("scene_threejs",),+ kinds=("baseline", "env", "zone", "compose", "refine"),+ why="scene layout and camera framing"),+ Route("R15", "cv3d-scene-composition", 95, tracks=("scene",), languages=("scene_threejs",),+ findings=(SCENE_CAMERA_PLACEMENT,),+ why="the camera was below ground or inside geometry"),+ Route("R16", "cv3d-scene-lighting", 65, tracks=("scene",), languages=("scene_threejs",),+ kinds=("baseline", "env", "refine"),+ why="lighting and exposure decide whether the frame reads at all"),+ Route("R17", "cv3d-scene-lighting", 95, tracks=("scene",), languages=("scene_threejs",),+ findings=(SCENE_DARK_OR_FLAT,),+ why="the frame gate called the render dark or flat"),+ Route("R18", "cv3d-scene-motion", 70, tracks=("scene",), languages=("scene_threejs",),+ kinds=("baseline", "zone", "refine", "compose"),+ why="animation_life 0.431 is the lowest criterion in the whole corpus"),+ Route("R19", "cv3d-scene-motion", 90, tracks=("scene",), languages=("scene_threejs",),+ findings=(GL_MOTION_OR_DETAIL,),+ why="the frame-difference gate saw a flicker or a still image"),+ Route("R20", "cv3d-threejs-shader-traps", 60, tracks=("scene", "static_object"), languages=THREEJS_LANGS,+ requires_all=("has_custom_shader",),+ why="the plan names a custom shader/material effect"),+ Route("R21", "cv3d-threejs-shader-traps", 95, languages=THREEJS_LANGS, findings=(SHADER_COMPILE_OR_BINDING,),+ why="a shader failed to compile or a uniform was unbound"),+ Route("R22", "cv3d-glsl-craft", 80, tracks=("graphics",), languages=("glsl_shader",),+ kinds=("baseline", "refine", "repair", "rebuild"),+ why="fragment-shader craft: technical_cleanliness 0.597 is the lowest glsl criterion"),+ Route("R23", "cv3d-opengl-pipeline", 80, tracks=("graphics",), languages=("opengl_python",),+ kinds=("baseline", "refine", "repair", "rebuild"),+ why="pipeline setup and pass structure: originality 0.330 is the lowest criterion anywhere"),+ # R24 is one row per language: the design writes it as a single line, but a Route names+ # exactly one skill so telemetry can say which one the finding routed.+ Route("R24-glsl", "cv3d-glsl-craft", 90, tracks=("graphics",), languages=("glsl_shader",),+ findings=(GL_MOTION_OR_DETAIL,), why="the frame gate saw no motion or no detail"),+ Route("R24-opengl", "cv3d-opengl-pipeline", 90, tracks=("graphics",), languages=("opengl_python",),+ findings=(GL_MOTION_OR_DETAIL,), why="the frame gate saw no motion or no detail"),+)++#: every skill the table can attach — the Author phase's contract for which bundles must exist+ROUTED_SKILLS: tuple[str, ...] = tuple(dict.fromkeys(r.skill for r in ROUTES))+++__all__ = ["BLENDER_LANGS", "BUILD_KINDS", "OBJECT_TRACKS", "QUIET_KINDS", "ROUTED_SKILLS", "ROUTES",+ "THREEJS_LANGS", "Route", "finding_kind", "finding_kinds",+ "CONNECTIVITY_FLOATING_PART", "CONNECTIVITY_INTERPENETRATION", "CONNECTIVITY_NO_GEOMETRY",+ "CONNECTIVITY_NO_GROUND", "CONNECTIVITY_STRAY_ISLANDS", "CONTRACT_FOOTPRINT", "CONTRACT_GROUND_GAP",+ "CONTRACT_INSTANCE_BBOX", "CONTRACT_INSTANCE_COUNT", "CONTRACT_MISSING_PART", "CONTRACT_OVERALL_BBOX",+ "CONTRACT_PART_BBOX", "CONTRACT_SCENE_BOUNDS", "DETAIL_DRIFT", "GL_MOTION_OR_DETAIL",+ "JOINT_SWEEP_DISCONNECTED", "JOINT_SWEEP_LINK_OVERLAP", "LINT_API_TRAP", "LINT_LINK_NAME",+ "LINT_PART_NOT_IMPORTED", "MOTION_SKIPPED", "MOTION_WRONG_AXIS", "RUNTIME_SLOW",+ "SCENE_CAMERA_PLACEMENT", "SCENE_DARK_OR_FLAT", "SHADER_COMPILE_OR_BINDING"]diff --git a/harness/codeverse/skills/router.py b/harness/codeverse/skills/router.pynew file mode 100644index 00000000..79ed5dfa--- /dev/null+++ b/harness/codeverse/skills/router.py@@ -0,0 +1,151 @@+"""Derive the skill set from typed inputs — nobody writes ``skills: [...]`` by hand.++The reference library put a ``skills: list[str]`` field on each task and a human filled+it; that scales to one author and drifts the moment the failure modes change. Here the+set falls out of five inputs the harness already has (track, language, round kind, plan+signals, and the PREVIOUS round's gate findings), through the typed table in+``registry.py``. The last input is the one no CLI's own skill loader can see, and it is+why a repair round gets the sheet for what actually broke.++Everything in this module is pure: no environment, no filesystem beyond the library the+caller passes in. The switches are applied by the caller (``materialize.attach_skills``)+so a test can route without touching ``os.environ``.+"""++from __future__ import annotations++import logging+from typing import Any++from codeverse.skills.model import EVIDENCE_INHERITED, Selection, Skill+from codeverse.skills.registry import QUIET_KINDS, ROUTES, Route, finding_kinds++log = logging.getLogger(__name__)++#: plan-derived booleans/ints the table may test. Kept here (not on the Plan contracts)+#: because they are a routing concern: adding one must not migrate every stored plan.+SIGNAL_KEYS = ("n_parts", "multi_part", "has_instances", "has_symmetry", "has_assemblies",+ "has_joints", "joint_types", "has_custom_shader")++_SHADER_WORDS = ("shader", "glsl", "onbeforecompile", "shadermaterial", "custom material",+ "raymarch", "postprocess", "post-process")+++def plan_signals(plan: Any | None) -> dict[str, Any]:+ """Route-relevant facts about a plan. Tolerant by design: a missing/partial plan+ yields all-false signals rather than raising, because a planner failure must not+ also take out the round's skills."""+ parts = list(getattr(plan, "parts", None) or [])+ joints = list(getattr(plan, "joints", None) or [])+ effects = list(getattr(plan, "effects", None) or [])+ passes = list(getattr(plan, "passes", None) or [])+ text = " ".join(str(x) for x in (+ getattr(plan, "summary", ""), getattr(plan, "style_notes", ""), getattr(plan, "environment", ""),+ getattr(plan, "style", ""), getattr(plan, "motion", ""),+ *(f"{getattr(e, 'kind', '')} {getattr(e, 'description', '')}" for e in effects),+ *(f"{getattr(p, 'kind', '')} {getattr(p, 'description', '')}" for p in passes),+ )).lower()+ n_parts = len(parts)+ return {+ "n_parts": n_parts,+ "multi_part": n_parts >= 2,+ "has_instances": any(int(getattr(p, "instances", 1) or 1) > 1 for p in parts),+ "has_symmetry": any(str(getattr(p, "symmetry", "none") or "none") != "none" for p in parts),+ "has_assemblies": any(getattr(p, "children", None) for p in parts),+ "has_joints": bool(joints),+ "joint_types": sorted({str(getattr(j, "type", "")) for j in joints if getattr(j, "type", "")}),+ "has_custom_shader": bool(effects) or any(w in text for w in _SHADER_WORDS),+ }+++def _row_applies(row: Route, track: str, language: str, kind: str, signals: dict[str, Any]) -> bool:+ if row.tracks and track not in row.tracks:+ return False+ if row.languages and language not in row.languages:+ return False+ if row.kinds and kind not in row.kinds:+ return False+ if any(not signals.get(k) for k in row.requires_all):+ return False+ return not (row.requires_any and not any(signals.get(k) for k in row.requires_any))+++def select(+ track: str,+ language: str,+ kind: str,+ *,+ signals: dict[str, Any] | None = None,+ findings: Any = (),+ library: dict[str, Skill] | None = None,+ max_skills: int = 5,+ allow_unverified: bool = False,+) -> list[Selection]:+ """The routed bundles for one session, ranked, capped, each with its reason.++ ``findings`` may be ``GateFinding``s, ``GateReport``s, or already-classified kind+ strings — the caller usually has the previous ``RoundRecord.gates`` on hand.+ """+ from codeverse.skills import all_skills++ lib = library if library is not None else all_skills()+ sig = dict(signals or {})+ kinds = [f for f in findings if isinstance(f, str)] if findings else []+ if findings and not kinds:+ kinds = finding_kinds(findings)++ best: dict[str, Selection] = {}+ first_seen: dict[str, int] = {}+ for order, row in enumerate(ROUTES):+ hit = row.matches_finding(kinds) if row.gate_fired else None+ if row.gate_fired and hit is None:+ continue+ if not row.gate_fired and kind in QUIET_KINDS:+ # design §5.2 law 4: short, narrow sessions attach nothing on their own+ continue+ if not _row_applies(row, track, language, kind, sig):+ continue+ skill = lib.get(row.skill)+ if skill is None:+ # The Author phase ships bodies in its own commits; a table row without a+ # bundle must not crash a run — it is a missing skill, not a broken harness.+ log.debug("route %s names skill %r, which is not in the library", row.rule, row.skill)+ continue+ if skill.evidence == EVIDENCE_INHERITED and not allow_unverified:+ log.debug("skill %s is %s and CV3D_SKILLS_UNVERIFIED is off; not routed", skill.name, EVIDENCE_INHERITED)+ continue+ reason = f"{row.rule}: {row.why}" + (f" [{hit}]" if hit else "")+ first_seen.setdefault(row.skill, order)+ prev = best.get(row.skill)+ if prev is None:+ best[row.skill] = Selection(skill=skill, priority=row.priority, rules=(row.rule,), reason=reason)+ elif row.priority > prev.priority:+ # a gate-fired row overrides the standing one, and says so in the reason+ best[row.skill] = Selection(skill=skill, priority=row.priority, rules=(*prev.rules, row.rule), reason=reason)+ else:+ best[row.skill] = prev.model_copy(update={"rules": (*prev.rules, row.rule)})++ # priority first (law 2: gate-fired rows outrank standing ones), then table order —+ # a stable, testable ranking, so the cap always cuts the same tail.+ ranked = sorted(best.values(), key=lambda s: (-s.priority, first_seen[s.name]))+ return ranked[:max(0, max_skills)]+++def skills_for(+ track: str,+ language: str,+ kind: str,+ *,+ plan: Any | None = None,+ findings: Any = (),+ library: dict[str, Skill] | None = None,+ max_skills: int = 5,+ allow_unverified: bool = False,+) -> list[Skill]:+ """``select`` without the reasons — the shape most callers want."""+ sel = select(track, language, kind, signals=plan_signals(plan), findings=findings,+ library=library, max_skills=max_skills, allow_unverified=allow_unverified)+ return [s.skill for s in sel]+++__all__ = ["SIGNAL_KEYS", "plan_signals", "select", "skills_for"]diff --git a/harness/codeverse/skills/telemetry.py b/harness/codeverse/skills/telemetry.pynew file mode 100644index 00000000..15505616--- /dev/null+++ b/harness/codeverse/skills/telemetry.py@@ -0,0 +1,165 @@+"""Did anyone actually READ it? The measurement no CLI can do for us.++The fact this whole system has to answer: ``read_cookbook`` was called by **0 of 16**+zone sessions and 1 of 4 env sessions on ``scenes_v1_flash``, although the prompt named+five chapters by title. A tool that exists is not a tool that gets used, and shipping a+nicer file format without measuring reads would repeat that at a new price.++Three signals, cheapest first:++1. **atime probe** — the root filesystem is ext4 with ``relatime``, where the first read+ after a write bumps ``atime``. ``materialize_skills`` stamps ``atime == mtime`` on+ every file it writes, so ``atime > mtime`` afterwards means the file was opened. No+ parsing, and it works identically for all five backends.+2. **references/ depth probe** — signal 1 has one known false positive: a CLI's startup+ scan opens SKILL.md to read the frontmatter. Nothing scans ``references/*.md``, so an+ atime bump there means the agent read the body and followed it. Signal 1 = surfaced,+ signal 2 = went deep. (This is the spec's own progressive disclosure, so the probe is+ free — but a bundle that ships no ``references/`` cannot be probed for depth, and says+ so via ``deep_measurable`` instead of quietly scoring 0.)+3. **exact reads for api-agent** — our own tool loop owns ``read_file``, so it logs every+ read of a skill path with its turn into ``telemetry/skill_reads.jsonl``. api-agent is+ therefore the CALIBRATION arm: compare signals 1/2 against ground truth and report the+ probe's false-positive / false-negative rate rather than assuming it is exact.+"""++from __future__ import annotations++import json+import logging+from collections.abc import Sequence+from pathlib import Path+from typing import Any++from codeverse.skills.model import SkillRead, SkillsMaterialized, SkillsUsage+from codeverse.skills.prompting import AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT++log = logging.getLogger(__name__)++TELEMETRY_DIR = "telemetry"+READS_FILE = "skill_reads.jsonl" # signal 3, written during the session+SKILLS_FILE = "skills.jsonl" # the per-session roll-up, written after it+#: seconds of slack: some filesystems round atime/mtime differently on the two writes+ATIME_EPSILON_S = 1.0+++def is_skill_path(rel: str) -> str:+ """The skill name a workspace-relative path belongs to, or '' — the one place the+ two discovery roots are recognised, so signal 3 cannot drift from what we wrote."""+ p = str(rel).replace("\\", "/")+ while p.startswith("./"):+ p = p[2:]+ for root in (AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT):+ if p.startswith(root + "/"):+ rest = p[len(root) + 1:].split("/")+ return rest[0] if rest and rest[0] else ""+ return ""+++def record_exact_read(ws_root: Path, rel_path: str, *, turn: int, label: str = "") -> None:+ """Signal 3: log one api-agent read of a skill file. Never raises into the loop."""+ name = is_skill_path(rel_path)+ if not name:+ return+ try:+ d = Path(ws_root) / TELEMETRY_DIR+ d.mkdir(parents=True, exist_ok=True)+ with (d / READS_FILE).open("a") as fh:+ fh.write(json.dumps({"skill": name, "path": str(rel_path), "turn": int(turn), "label": label}) + "\n")+ except OSError as e: # telemetry must never cost a run+ log.debug("could not record a skill read: %s", e)+++def _exact_reads(ws_root: Path) -> dict[str, dict[str, Any]]:+ """name → {first_turn, deep} from ``skill_reads.jsonl`` (empty when absent)."""+ p = Path(ws_root) / TELEMETRY_DIR / READS_FILE+ if not p.is_file():+ return {}+ out: dict[str, dict[str, Any]] = {}+ for line in p.read_text().splitlines():+ try:+ row = json.loads(line)+ except json.JSONDecodeError:+ continue+ name = str(row.get("skill") or "")+ if not name:+ continue+ rec = out.setdefault(name, {"first_turn": None, "deep": False})+ turn = row.get("turn")+ if isinstance(turn, int) and (rec["first_turn"] is None or turn < rec["first_turn"]):+ rec["first_turn"] = turn+ if "/references/" in str(row.get("path", "")):+ rec["deep"] = True+ return out+++def _opened(path: Path) -> bool:+ try:+ st = path.stat()+ except OSError:+ return False+ return st.st_atime > st.st_mtime + ATIME_EPSILON_S+++def probe_reads(ws_root: Path, materialized: SkillsMaterialized) -> SkillsUsage:+ """What the session did with the bundles we attached, per skill."""+ root = Path(ws_root)+ exact = _exact_reads(root)+ reads: list[SkillRead] = []+ for sel in materialized.selections:+ name = sel.name+ bundles = [root / r / name for r in (AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT)]+ refs = [f for b in bundles for f in sorted((b / "references").glob("*.md"))]+ surfaced = any(_opened(b / "SKILL.md") for b in bundles)+ deep = any(_opened(f) for f in refs)+ got = exact.get(name)+ if got:+ surfaced = True+ deep = deep or bool(got["deep"])+ # reading a reference means the bundle was reached, whatever SKILL.md's atime says+ # (relatime can miss the second access within 24 h, and some CLIs stream the body+ # out of their own index rather than re-opening the file)+ surfaced = surfaced or deep+ reads.append(SkillRead(+ name=name, surfaced=surfaced, deep=deep, deep_measurable=bool(refs),+ body_tokens=sel.skill.body_tokens, reason=sel.reason,+ first_seen_turn=got["first_turn"] if got else None,+ ))+ return SkillsUsage(+ listed=list(materialized.listed), reads=reads, index_tokens=materialized.index_tokens,+ body_tokens_read=sum(r.body_tokens for r in reads if r.deep),+ inlined=materialized.inlined,+ )+++def append_usage(ws_root: Path, usage: SkillsUsage, **context: Any) -> Path | None:+ """One JSON line per (run, round, session) — the file ``3dcv skills report`` reads."""+ try:+ d = Path(ws_root) / TELEMETRY_DIR+ d.mkdir(parents=True, exist_ok=True)+ p = d / SKILLS_FILE+ with p.open("a") as fh:+ fh.write(json.dumps({**context, **usage.model_dump(mode="json")}) + "\n")+ return p+ except OSError as e:+ log.debug("could not append skills telemetry: %s", e)+ return None+++def deep_read_rate(usages: Sequence[SkillsUsage]) -> dict[str, tuple[int, int]]:+ """skill → (deep reads, times listed) across sessions — the metric with the teeth.++ Standing rule from the design: a skill under 20% over 20 sessions is merged or+ deleted. A library that only ever grows is how this ends as bloat."""+ out: dict[str, list[int]] = {}+ for u in usages:+ for name in u.listed:+ out.setdefault(name, [0, 0])[1] += 1+ for r in u.reads:+ if r.deep:+ out.setdefault(r.name, [0, 0])[0] += 1+ return {k: (v[0], v[1]) for k, v in sorted(out.items())}+++__all__ = ["ATIME_EPSILON_S", "READS_FILE", "SKILLS_FILE", "TELEMETRY_DIR", "append_usage",+ "deep_read_rate", "is_skill_path", "probe_reads", "record_exact_read"]diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.pyindex 1a5e1ed5..ee80a3cf 100644--- a/harness/codeverse/tracks/plan_features.py+++ b/harness/codeverse/tracks/plan_features.py@@ -48,6 +48,11 @@ LIVE_SWITCHES: dict[str, str] = {"CV3D_SCOPED_PARTS": "codeverse/tracks/depth.py","CV3D_DETAIL_ROUNDS": "codeverse/tracks/lifecycle.py","CV3D_REFERENCE_DIFF": "codeverse/judges/reference.py",+ # the skill system (design: scratchpad/skills/design/DESIGN.md §6.5). All three are+ # read at call time by one module, so an A/B arm that sets them really differs.+ "CV3D_SKILLS": "codeverse/skills/config.py",+ "CV3D_SKILLS_MAX": "codeverse/skills/config.py",+ "CV3D_SKILLS_UNVERIFIED": "codeverse/skills/config.py",}#: Switches that are DECLARED but read by no code path, with the reason. An A/B arm thatdiff --git a/harness/codeverse/tracks/repair.py b/harness/codeverse/tracks/repair.pyindex 11000120..242acea5 100644--- a/harness/codeverse/tracks/repair.py+++ b/harness/codeverse/tracks/repair.py@@ -19,6 +19,7 @@ from pydantic import BaseModel, Fieldfrom codeverse.contracts.artifacts import BuildResult, GateReportfrom codeverse.contracts.common import Usagefrom codeverse.prompts import render+from codeverse.tracks import skills_hookfrom codeverse.tracks.common import RunContextfrom codeverse.tracks.generation import GenerationResult, GenerationTask, generatefrom codeverse.tracks.prompting import base_prompt_context@@ -51,8 +52,12 @@ def error_signature(build: BuildResult, lint: GateReport) -> str:return "lint|" + "|".join(sorted(f"{f.target}:{f.message[:80]}" for f in lint.errors))-def format_error_report(build: BuildResult, lint: GateReport, cookbook: str = "") -> str:- """Compact, structured error report for the fixer (the ONLY thing it must fix)."""+def format_error_report(build: BuildResult, lint: GateReport, cookbook: str = "", skills: str = "") -> str:+ """Compact, structured error report for the fixer (the ONLY thing it must fix).++ ``skills`` is the gate→skill pointer block: the bundles already in the workspace that+ answer THESE findings, named beside them. Pointers, not text — the bodies are on+ disk, and the repair prompt is the volatile tail nobody caches."""lines: list[str] = []if not build.ok:loc = build.error_file + (f":{build.error_line}" if build.error_line else "") if build.error_file else "(unknown file)"@@ -68,6 +73,8 @@ def format_error_report(build: BuildResult, lint: GateReport, cookbook: str = ""if lint.errors:lines.append(f"LINT ERRORS ({lint.gate}):")lines.extend(f"- {f.as_line(with_target=True)}" for f in lint.errors)+ if skills.strip():+ lines.append("\n" + skills.strip())section = relevant_cookbook_section(cookbook, " ".join([build.error_type, build.error_message, build.stderr_tail[-2000:]]))if section:lines.append("\nRelevant cookbook section:\n" + section)@@ -180,7 +187,7 @@ def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hidef make_repair_task(ctx: RunContext, build: BuildResult, lint: GateReport, *, round_index: int, attempt: int,repeats: int, label: str, files_hint: list[str]) -> GenerationTask:"""Render prompts/tracks/repair.j2 for the current strategy."""- report = format_error_report(build, lint, ctx.cookbook_text)+ report = format_error_report(build, lint, ctx.cookbook_text, skills_hook.repair_pointers(ctx, lint))files = files_for_repair(ctx, build, lint, files_hint) if ctx.single_shot else {}prompt = render("tracks/repair.j2", **base_prompt_context(ctx, error_report=report, files=files, repeats=repeats, attempt=attempt,diff --git a/harness/codeverse/tracks/skills_hook.py b/harness/codeverse/tracks/skills_hook.pynew file mode 100644index 00000000..c23a9c12--- /dev/null+++ b/harness/codeverse/tracks/skills_hook.py@@ -0,0 +1,170 @@+"""Where the skill system meets a round: route before generating, measure after.++Kept out of ``codeverse/skills`` so that package stays pure (no ``RunContext``, no+workspace conventions, no environment) and testable without a run. Kept out of+``steps.py`` so a round's control flow does not grow a second subject.++Everything here is a no-op unless ``CV3D_SKILLS`` is on, and every function swallows its+own failures: a skill that cannot be routed, written or probed must cost that skill, not+the round. The switch is read at CALL time (see ``skills/config.py`` for why).+"""++from __future__ import annotations++import json+import logging+from collections.abc import Sequence+from pathlib import Path+from typing import Any++from pydantic import ValidationError++from codeverse.contracts.artifacts import GateReport+from codeverse.contracts.skills import SkillsUsage+from codeverse.tracks.common import RunContext++log = logging.getLogger(__name__)++CTX_KEY = "skills" # ctx.extra slot holding this round's SkillsMaterialized+++def _previous_findings(ctx: RunContext, index: int) -> list[GateReport]:+ """The gates of the last completed round — the input no CLI's own loader can see.++ Read straight off disk rather than through ``steps.load_round_records`` so the hook+ stays independent of the round loop (and so a half-written record from a killed run+ costs this round its gate routing, not the round itself)."""+ if index <= 0:+ return []+ d = Path(ctx.ws.root) / "rounds"+ if not d.is_dir():+ return []+ for p in sorted(d.glob("r*.json"), reverse=True):+ try:+ data = json.loads(p.read_text())+ except (OSError, json.JSONDecodeError) as e:+ log.debug("skills: unreadable round record %s: %s", p, e)+ continue+ if int(data.get("index", -1)) >= index:+ continue+ gates = data.get("gates") or []+ if gates:+ try:+ return [GateReport.model_validate(g) for g in gates]+ except ValidationError as e:+ log.debug("skills: round record %s has gates we cannot parse: %s", p, e)+ return []+ return []+++def attach_for_round(ctx: RunContext, *, index: int, kind: str) -> Any | None:+ """Route + materialise this round's skills. Returns the ``SkillsMaterialized``."""+ from codeverse.skills import attach_skills, skills_enabled++ # drop the previous round's set first: a failure below must not leave this round+ # probing — and crediting — bundles it never attached+ ctx.extra.pop(CTX_KEY, None)+ if not skills_enabled():+ return None+ try:+ got = attach_skills(+ ctx.ws.root,+ track=ctx.spec.track.value if hasattr(ctx.spec.track, "value") else str(ctx.spec.track),+ language=ctx.language.value,+ kind=kind,+ agent_kind=ctx.agent_id.split(":", 1)[0],+ plan=ctx.plan,+ findings=_previous_findings(ctx, index),+ single_shot=ctx.single_shot,+ )+ except Exception as e: # noqa: BLE001 — never let the skill system break a round+ log.warning("skills not attached for round %d (%s): %s", index, kind, e)+ return None+ ctx.extra[CTX_KEY] = got+ # the body a session actually saw is part of what decided the run: hash it beside the+ # prompt hashes so a later comparison of two runs can tell "same skill, new wording"+ # from "different skill"+ for sel in got.selections:+ ctx.record_prompt(f"skill:{sel.name}", sel.skill.body)+ ctx.events.emit("skills.attached", round=index, kind=kind, skills=got.listed,+ index_tokens=got.index_tokens, inlined=got.inlined or None, reasons=got.reasons)+ return got+++def with_inlined_skill(ctx: RunContext, tasks: Sequence[Any]) -> list[Any]:+ """Single-shot only: prepend the one routed body to each task prompt.++ A single-shot call has no read loop, so a pointer to a file it cannot open would be+ cost with no benefit — and, worse, would make the single-shot arm quietly+ incomparable with the agent arms. One body, capped, in the prompt.+ """+ got = ctx.extra.get(CTX_KEY)+ if not got or not getattr(got, "inlined", ""):+ return list(tasks)+ from codeverse.skills.prompting import inline_body++ _, text = inline_body(got.selections)+ if not text:+ return list(tasks)+ return [t.model_copy(update={"prompt": f"{text}\n---\n\n{t.prompt}"}) for t in tasks]+++def repair_pointers(ctx: RunContext, lint: GateReport | None) -> str:+ """Name the attached skills that answer the CURRENT lint/build failure.++ ``tracks/repair.py`` already picks a cookbook section by keyword; this is the same+ idea one level up, and it only names skills that are already in the workspace, so it+ adds pointers rather than text.+ """+ got = ctx.extra.get(CTX_KEY)+ if not got or not getattr(got, "selections", None):+ return ""+ from codeverse.skills.prompting import repair_pointers as _fmt+ from codeverse.skills.registry import finding_kinds++ kinds = set(finding_kinds([lint])) if lint is not None else set()+ answering = [s.name for s in got.selections if kinds & _matched(s, kinds)]+ return _fmt(got.selections, agent_kind=ctx.agent_id.split(":", 1)[0], answering=answering)+++def _matched(selection: Any, kinds: set[str]) -> set[str]:+ """The current finding kinds this attached skill's routes answer (families included)."""+ out: set[str] = set()+ for pat in _kinds_of(selection):+ family = pat[:-1] if pat.endswith("*") else ""+ out |= {k for k in kinds if (family and k.startswith(family)) or k == pat}+ return out+++def _kinds_of(selection: Any) -> tuple[str, ...]:+ """Every finding kind ANY route for this skill answers.++ Deliberately not just the rules that fired at attach time: the build/lint failure a+ repair session is looking at was discovered afterwards, and the sheet that answers it+ is already sitting in the workspace."""+ from codeverse.skills.registry import ROUTES++ return tuple(k for r in ROUTES if r.skill == selection.name for k in r.findings)+++def record_usage(ctx: RunContext, *, index: int, kind: str) -> SkillsUsage | None:+ """After the round's sessions: what was read. Also appends ``telemetry/skills.jsonl``."""+ got = ctx.extra.get(CTX_KEY)+ if not got:+ return None+ try:+ from codeverse.skills.telemetry import append_usage, probe_reads++ usage = probe_reads(ctx.ws.root, got)+ append_usage(ctx.ws.root, usage, round=index, kind=kind, agent=ctx.agent_id,+ track=ctx.spec.track.value if hasattr(ctx.spec.track, "value") else str(ctx.spec.track),+ language=ctx.language.value)+ except Exception as e: # noqa: BLE001 — telemetry never costs a round+ log.warning("skills telemetry failed for round %d: %s", index, e)+ return None+ ctx.events.emit("skills.read", round=index, listed=usage.listed, deep=usage.deep,+ surfaced=usage.surfaced, body_tokens_read=usage.body_tokens_read)+ return usage+++__all__ = ["CTX_KEY", "attach_for_round", "record_usage", "repair_pointers", "with_inlined_skill"]diff --git a/harness/codeverse/tracks/steps.py b/harness/codeverse/tracks/steps.pyindex 079566c2..b8846afa 100644--- a/harness/codeverse/tracks/steps.py+++ b/harness/codeverse/tracks/steps.py@@ -35,6 +35,7 @@ from codeverse.contracts.plan import AcceptanceItem, Planfrom codeverse.contracts.run import RoundRecordfrom codeverse.orchestrator.budget import usage_deltafrom codeverse.orchestrator.fanout import fan_out+from codeverse.tracks import skills_hookfrom codeverse.tracks.common import RunContextfrom codeverse.tracks.generation import GenerationResult, GenerationTask, generatefrom codeverse.tracks.repair import RepairOutcome, build_with_repair@@ -198,7 +199,8 @@ def _run_round(if extra_usage is not None and extra_usage.cost_usd:cost["candidates"] = round(extra_usage.cost_usd, 6)- gens = run_generation_tasks(ctx, tasks)+ skills_hook.attach_for_round(ctx, index=index, kind=kind)+ gens = run_generation_tasks(ctx, skills_hook.with_inlined_skill(ctx, tasks))turns = 0for g in gens:usage = usage + g.usage@@ -249,6 +251,7 @@ def _run_round(else:notes.append(f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:200]}")rec.gates = gates+ rec.skills = skills_hook.record_usage(ctx, index=index, kind=kind)_write_gate_reports(ctx, index, gates)rec.commit = ctx.ws.commit(f"r{index:02d} {kind}")diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex 91ed26c3..f05f6d85 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -77,7 +77,8 @@ codeverse/contracts/ pydantic: common (Track, Language, Usage, Budget, Backends, TRACK_INFO registry,ENTRY_FILE/code_file/LANGUAGE_LABEL tables), spec (+ RunOptions), plan, artifacts(GateFinding.as_line, RenderView.judge, RenderSet.out_dir), judgment, run, chat,- agent (typed AgentJob + ApiAgentOptions)+ agent (typed AgentJob + ApiAgentOptions), skills.py (SkillsUsage/SkillRead on+ RoundRecord: what was attached, what was read)workspace.py run-dir layout + git snapshots ; events.py JSONL event logproc.py stdlib-only subprocess + atomic-JSON primitives (run_subprocess w/ group kill +preexec_fn, kill_group, tail, write_json_atomic) — shared by languages/spatial/cli@@ -103,6 +104,16 @@ codeverse/complexity.py (objective complexity vector -> Measurement.extra, docs/COMPLEXITY.md),joints*.py + joints_collide.py (deterministic penetration), registry.py, tools*.py(tools_texture.py, tools_graphics.py), mcp_server.py (MCP name: 3dcv)+ skills/ THE skill library + its router (design: SKILL.md is an open standard, so+ claude-code / codex / gemini-cli / agy load our bundles natively):+ <name>/SKILL.md + <name>/references/*.md (the bundles, package data),+ loader.py (spec validation), model.py, registry.py (the R1-R24 route table ++ finding_kind(): the ONE place gate message text is matched), router.py+ (track/language/kind/plan/gate-findings -> a capped, ranked, reasoned set),+ materialize.py (writes into ws/.agents/skills AND ws/.claude/skills, real+ copies — codex refuses symlinks), prompting.py (per-backend index text),+ telemetry.py (the atime read probe: surfaced vs deep), claims.py (numbers+ pinned to live constants), config.py (CV3D_SKILLS, default OFF)cost/ types.py (CallCost/Stage/Role) ledger.py (append-only telemetry/cost.jsonl + price provenance)context.py (per-call > ambient attribution) instrument.py (MeteredChatModel /MeteredAgent — one row per ChatModel.generate; one session row only for a backend@@ -134,7 +145,9 @@ codeverse/plan_features.py (CV3D_PLAN_FEATURES: one switch per plan-loop change, so eachcan be A/B'd alone — docs/PLAN_LOOP.md),plan_examples.py (worked plans shown to the planner), depth.py + detailing.py- (per-part detail pass), envelope.py (bbox envelope), scene_asset_gen.py+ (per-part detail pass), envelope.py (bbox envelope), scene_asset_gen.py,+ skills_hook.py (the round's view of codeverse/skills: attach before generating,+ probe reads after — a no-op unless CV3D_SKILLS is on)flywheel/ record.py, export.py, pack.py, sample.py, pairs.py, migrate.py (schema moves),deliverable.py, telemetry.py, trajectories.py (repair-pairmining), captions.py, quality.py (tiers + dedupe), gallery.py (the shared@@ -150,6 +163,8 @@ codeverse/texturing/*.md, tracks/*.j2 (incl. plan/generate/refine_graphics.j2)cli/ main.py, tools_cmd.py, flywheel_cmd.py, gallery_cmd.py, bench_cmd.py,texture_cmd.py, cost_cmd.py (`3dcv cost`), layout_cmd.py, doctor.py+ (`--skills` checks the library + its discovery wiring),+ skills_cmd.py (`3dcv skills list|show|validate|report` — the read-rate report)bench/ run_bench.py, report.py (reuses flywheel gallery), compare_backends.py(preflights every model it needs; --wait-for-provider / --no-preflight),_infra.py (outage vs model failure: infra_failed / budget_exhausted, docs/EVAL.md §7),diff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.mdnew file mode 100644index 00000000..7b3fec47--- /dev/null+++ b/harness/docs/SKILLS.md@@ -0,0 +1,98 @@+# Skills — the authoring contract++A **skill** is a task-scoped rule sheet the harness attaches to a coding session+automatically, from the track, the language, the round kind, the plan, and **the previous+round's gate findings**. It is not a renamed cookbook chapter: the cookbook+(`codeverse/prompts/<lang>/cookbook.md`) stays the reference manual with the copyable+code; a skill states rules and numbers and names the cookbook section to fetch.++`SKILL.md` is an open standard (agentskills.io), which is why the format below is not+ours to bend: claude-code, codex, gemini-cli and agy discover these bundles themselves.+Only `api-agent` needs harness-side injection.++Everything is behind `CV3D_SKILLS` (default **off**). See `codeverse/skills/config.py`.++## 1. Layout++```+codeverse/skills/<name>/SKILL.md the bundle (package data — it ships in the wheel)+codeverse/skills/<name>/references/*.md depth: worked examples, long tables. ONE level.+codeverse/skills/_claims/<name>.toml numbers pinned to live constants (outside the bundle)+```++`references/` is not optional decoration. Nothing scans it, so an `atime` bump there is+the only honest evidence that an agent read the body rather than a discovery scan reading+the frontmatter. A bundle without it reports `deep_measurable: false` and can never score+on the read metric.++## 2. Frontmatter++```yaml+---+name: cv3d-part-contact # == the directory name, lowercase a-z0-9 and '-', <= 64+description: >- # 1-1024 chars, and it must say WHAT and WHEN+ ... the only text a CLI indexes ...+license: Apache-2.0+metadata: # string -> string only+ evidence: measured # measured | mixed | inherited-unverified+ verified: 2026-08-25 # ISO date the claims were last checked against this repo+ corpus: static_v2_flash n=47 # optional, when the body quotes corpus statistics+---+```++Hard rules the loader enforces (`codeverse/skills/loader.py`):++* `name` equals the parent directory name — every discovery implementation keys off it.+* **No `<` or `>` anywhere in the frontmatter.** The spec's prompt-injection rule.+* Only spec keys at the top level; our own fields live under `metadata`.+* Body <= **350 lines** and <= **2,500 estimated tokens** (half the spec's recommendation,+ because docs/COST.md §4 shows we pay for every prompt byte on every turn, not once).+* A bundle labelled `inherited-unverified` is **not routed** unless+ `CV3D_SKILLS_UNVERIFIED=on`. Today that is cadquery and threejs: zero graded runs each.++## 3. Body rules (enforced by `tests/skills/test_library.py`)++* No code fence longer than 20 lines — code belongs in the cookbook, one library of truth.+* Never restate a frame, unit or naming rule; `codeverse/conventions.py` is the only place+ those exist, and two truths are worse than one.+* Every number that came from a live constant gets a `_claims` row, so moving the constant+ breaks the test that ships the skill quoting it.+* Every corpus percentage carries its battery, its n and its date.+* Two skills that can be attached to the same session may not disagree about a claim key.++A claim row:++```toml+[[claim]]+key = "penetration_error_m"+text = "10 mm" # must appear in the body+python = "codeverse.spatial.connectivity:PENETRATION_ERROR_M"+scale = 1000+format = "{:.0f} mm"+```++## 4. Routing++Nobody writes `skills: [...]`. `codeverse/skills/registry.py` holds the typed route table+(R1-R24) and `finding_kind()`, the one place a gate message is pattern-matched.+`codeverse/skills/router.py` turns `(track, language, kind, plan signals, findings)` into a+ranked, capped set with a reason per selection. Gate-fired rows (priority >= 90) always+outrank standing rows, so a repair round spends its budget on what actually broke, and at+most `CV3D_SKILLS_MAX` (default 5) bundles are attached.++Adding a bundle means adding its rows to that table in the same commit — an unroutable+bundle pays the index and never helps, and a test fails on both halves of that.++## 5. Commands++```+3dcv skills list --routes+3dcv skills show cv3d-part-contact+3dcv skills validate+3dcv skills report bench/out/static_v2_flash+3dcv doctor --skills+```++`report` is the one that matters: deep-read rate per skill per backend. Targets are+>= 60% for CLI backends and >= 80% for api-agent, and a skill under 20% over 20 sessions+is merged or deleted. A library that only ever grows is how this ends as bloat.diff --git a/harness/pyproject.toml b/harness/pyproject.tomlindex 7ac8923d..90d28ff3 100644--- a/harness/pyproject.toml+++ b/harness/pyproject.toml@@ -64,8 +64,12 @@ include = ["codeverse*"]# scene starter tree were missing and `spatial/js/*` matched nothing at all (no such# directory), so a wheel install shipped no starter files: skeleton.write_example()# rglob'd an absent directory and wrote ZERO files while reporting success.+# `skills/**/*` carries the SKILL.md bundles + their references/: an installed wheel that+# ships none of them routes an empty set, and the failure is silent (the run still passes,+# the skill simply never appears). tests/skills/test_packaging.py builds a wheel and+# asserts the files are in it.codeverse = ["prompts/**/*", "judges/rubrics/*.yaml", "languages/**/wrappers/*",- "languages/**/*.md", "languages/**/starter/**/*"]+ "languages/**/*.md", "languages/**/starter/**/*", "skills/**/*"][tool.setuptools.exclude-package-data]codeverse = ["**/__pycache__/*"] # a wheel must not carry the build host's bytecode@@ -90,4 +94,5 @@ markers = ["live: needs network + API keys (deselect with -m 'not live')","blender: needs a Blender binary","node: needs node + runtime_js deps",+ "slow: recomputes something from bench/out (deselect with -m 'not slow')",]diff --git a/harness/tests/skills/__init__.py b/harness/tests/skills/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/harness/tests/skills/conftest.py b/harness/tests/skills/conftest.pynew file mode 100644index 00000000..b95286ba--- /dev/null+++ b/harness/tests/skills/conftest.py@@ -0,0 +1,59 @@+"""A synthetic skill library on disk — the machinery is tested without the real bodies.++The 14 real bundles are written by a different phase; the plumbing must be green before+they land, and must keep working when they change. So every unit test here builds the+library it needs.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from codeverse.skills.registry import ROUTED_SKILLS++FRONTMATTER = """---+name: {name}+description: {description}+license: Apache-2.0+metadata:+ evidence: {evidence}+ verified: 2026-08-25+---++# {name}++{body}+"""+++def write_bundle(root: Path, name: str, *, description: str = "", evidence: str = "measured",+ body: str = "Rule one: prove it with `measure`.", references: dict[str, str] | None = None) -> Path:+ d = root / name+ d.mkdir(parents=True, exist_ok=True)+ (d / "SKILL.md").write_text(FRONTMATTER.format(+ name=name, description=description or f"Rules for {name}. Use when the harness routes it.",+ evidence=evidence, body=body))+ refs = {"worked_example.md": "A worked example.\n"} if references is None else references+ for rel, text in refs.items():+ (d / "references").mkdir(exist_ok=True)+ (d / "references" / rel).write_text(text)+ return d+++def library_dir(tmp_path: Path) -> Path:+ """A library holding every skill the route table can name, all `measured`."""+ root = tmp_path / "library"+ root.mkdir()+ for name in ROUTED_SKILLS:+ write_bundle(root, name)+ return root+++def library(library_dir: Path) -> dict:+ from codeverse.skills import all_skills++ return all_skills(library_dir, strict=True)diff --git a/harness/tests/skills/data/gate_findings.json b/harness/tests/skills/data/gate_findings.jsonnew file mode 100644index 00000000..a2cd48a5--- /dev/null+++ b/harness/tests/skills/data/gate_findings.json@@ -0,0 +1,314 @@+{+ "source": "bench/out/**/artifacts/gates/**/*.json — 2,113 gate reports, mined 2026-08-25",+ "note": "Real WARN/ERROR gate messages, one row per distinct message shape (up to 6 per defect kind, including the shortest and longest shape seen). finding_kind() must classify every row: an `unknown` here means a gate reword has silently unrouted a repair skill. INFO findings are excluded on purpose — they are census, not defects.",+ "n_shapes_mined": 113,+ "findings": [+ {+ "gate": "connectivity",+ "severity": "error",+ "message": "part 'door_leaf' is floating: nearest supported part is 'frame' at 4.0 mm",+ "n": 262,+ "kind": "connectivity/floating_part"+ },+ {+ "gate": "connectivity",+ "severity": "warn",+ "message": "'Leg_2' and 'Seat' interpenetrate by ≈5.0 mm (3% of surface samples inside)",+ "n": 5406,+ "kind": "connectivity/interpenetration"+ },+ {+ "gate": "connectivity",+ "severity": "error",+ "message": "GLB has no mesh parts",+ "n": 0,+ "kind": "connectivity/no_geometry",+ "origin": "codeverse source (gate not yet represented in bench/out)"+ },+ {+ "gate": "connectivity",+ "severity": "warn",+ "message": "no part touches the ground (z=0)",+ "n": 0,+ "kind": "connectivity/no_ground_contact",+ "origin": "codeverse source (gate not yet represented in bench/out)"+ },+ {+ "gate": "connectivity",+ "severity": "warn",+ "message": "part 'frame' contains 8 tiny disconnected island(s) (< 5% of the part size) — stray geometry",+ "n": 2907,+ "kind": "connectivity/stray_islands"+ },+ {+ "gate": "contract",+ "severity": "warn",+ "message": "footprint centre is 4.6 cm off the up axis",+ "n": 233,+ "kind": "contract/footprint_offset"+ },+ {+ "gate": "contract",+ "severity": "error",+ "message": "object floats 130.0 mm above the ground",+ "n": 6,+ "kind": "contract/ground_gap"+ },+ {+ "gate": "contract",+ "severity": "warn",+ "message": "'BaseFootPlates' (all instances) bbox deviates from the plan (worst 1.1× tolerance)",+ "n": 94,+ "kind": "contract/instance_bbox"+ },+ {+ "gate": "contract",+ "severity": "error",+ "message": "'Leg' (each instance) bbox deviates from the plan (worst 3.4× tolerance)",+ "n": 224,+ "kind": "contract/instance_bbox"+ },+ {+ "gate": "contract",+ "severity": "warn",+ "message": "'ApexFinial': found 1 instance(s), plan asks for 2",+ "n": 12,+ "kind": "contract/instance_count"+ },+ {+ "gate": "contract",+ "severity": "error",+ "message": "plan part 'WoodenPlatform' is missing from the GLB",+ "n": 2,+ "kind": "contract/missing_part"+ },+ {+ "gate": "contract",+ "severity": "warn",+ "message": "overall bbox deviates from the plan (worst 1.1× tolerance)",+ "n": 348,+ "kind": "contract/overall_bbox"+ },+ {+ "gate": "contract",+ "severity": "warn",+ "message": "part 'ConicalShade' bbox deviates from the plan (worst 2.2× tolerance)",+ "n": 1386,+ "kind": "contract/part_bbox"+ },+ {+ "gate": "contract",+ "severity": "warn",+ "message": "scene geometry exceeds the planned bounds by x +2.1 m",+ "n": 0,+ "kind": "contract/scene_bounds",+ "origin": "codeverse source (gate not yet represented in bench/out)"+ },+ {+ "gate": "detail_drift",+ "severity": "error",+ "message": "part 'DraftingStoolLegs0' moved 8.9 mm / resized 16.9 mm during the detail round (tolerance 5 mm)",+ "n": 10,+ "kind": "detail_drift/part_moved"+ },+ {+ "gate": "gl_frames",+ "severity": "warn",+ "message": "very large frame-to-frame change (max |Δ| 0.392); flicker or hard cuts",+ "n": 6,+ "kind": "gl_frames/motion_or_detail"+ },+ {+ "gate": "gl_frames",+ "severity": "warn",+ "message": "very low visual detail (edge density 0.0000); the image is a near-flat gradient",+ "n": 2,+ "kind": "gl_frames/motion_or_detail"+ },+ {+ "gate": "joint_sweep",+ "severity": "error",+ "message": "link 'moving_jaw' slides in 'fixed_jaw_body' (prismatic joint) but the meshes are 42.5 mm apart at rest — nothing physically connects them",+ "n": 4,+ "kind": "joint_sweep/disconnected"+ },+ {+ "gate": "joint_sweep",+ "severity": "warn",+ "message": "link 'seat' hinges on 'main_frame' (revolute joint) but the meshes are 11.0 mm apart at rest — nothing physically connects them",+ "n": 2,+ "kind": "joint_sweep/disconnected"+ },+ {+ "gate": "joint_sweep",+ "severity": "warn",+ "message": "links 'door_leaf' and 'lever_handle' overlap by 3.0 mm at pose rest",+ "n": 51,+ "kind": "joint_sweep/link_overlap"+ },+ {+ "gate": "joint_sweep",+ "severity": "error",+ "message": "links 'shaft_and_handle' and 'rib_assembly1' overlap by 4.6 mm at pose crown_hinge1=-0.891,crown_hinge2=-1.17,crown_hinge3=-1.2,crown_hinge4=-0.228,crown_hinge5=-0.106,crown_hinge6=-0.48,runner_slide=0.191 (pose q={'runner_slide': 0.19108850619643628, 'crown_hinge1': -0.8908602092080782, 'crown_hinge2': -1.1700123007978425, 'crown_hinge3': -1.1998362846551944, 'crown_hinge4': -0.2278103081756676, 'crown_hinge5': -0.10643819572117952, 'crown_hinge6': -0.4799043535640406}) [approx: non-watertight mesh]",+ "n": 78,+ "kind": "joint_sweep/link_overlap"+ },+ {+ "gate": "joint_sweep",+ "severity": "error",+ "message": "links 'table_top' and 'left_leg_frame' overlap by 5.4 mm at pose left_brace_elbow_joint=0.0778,left_brace_upper_joint=0.424,left_leg_joint=0.968,right_brace_elbow_joint=1.73,right_brace_upper_joint=1.28,right_leg_joint=0.0251 (pose q={'left_leg_joint': 0.9681817647286105, 'left_brace_upper_joint': 0.4235651406092764, 'left_brace_elbow_joint': 0.07784969547876991, 'right_leg_joint': 0.025122006003364224, 'right_brace_upper_joint': 1.2768342755444277, 'right_brace_elbow_joint': 1.7342355968276713})",+ "n": 334,+ "kind": "joint_sweep/link_overlap"+ },+ {+ "gate": "joint_sweep",+ "severity": "error",+ "message": "links 'turret' and 'lower_arm' overlap by 2.9 mm at pose elbow_joint=-1.01,head_tilt_joint=-0.967,shoulder_joint=-0.241,swivel_joint=0.548 (pose q={'swivel_joint': 0.5478467492858172, 'shoulder_joint': -0.241079353346475, 'elbow_joint': -1.0098582473403717, 'head_tilt_joint': -0.9669447289429418})",+ "n": 48,+ "kind": "joint_sweep/link_overlap"+ },+ {+ "gate": "lint:blender",+ "severity": "warn",+ "message": "bpy.context.selected_objects is unreliable in background mode (often empty)",+ "n": 18,+ "kind": "lint/api_trap"+ },+ {+ "gate": "lint:blender",+ "severity": "warn",+ "message": "bpy.ops.object.join needs all parts selected + an active object; the result inherits the ACTIVE object's transform",+ "n": 231,+ "kind": "lint/api_trap"+ },+ {+ "gate": "lint:blender",+ "severity": "warn",+ "message": "bpy.ops.object.modifier_apply needs the object active+selected in OBJECT mode",+ "n": 94,+ "kind": "lint/api_trap"+ },+ {+ "gate": "lint:blender",+ "severity": "warn",+ "message": "no PascalCase object names found (e.g. obj.name = 'SeatCushion')",+ "n": 122,+ "kind": "lint/api_trap"+ },+ {+ "gate": "lint:blender",+ "severity": "warn",+ "message": "src/parts/backrest_assembly.py is never imported by src/model.py → its part is not built",+ "n": 144,+ "kind": "lint/part_not_imported"+ },+ {+ "gate": "lint:scene_threejs",+ "severity": "warn",+ "message": "GLSL declares/reads uTime but JS never binds it (uniforms: { uTime: { value: 0 } } and update .value in update(t))",+ "n": 0,+ "kind": "shader/compile_or_binding",+ "origin": "codeverse source (gate not yet represented in bench/out)"+ },+ {+ "gate": "lint:urdf",+ "severity": "warn",+ "message": "link 'rib_assembly1' never appears as a string in src/model.py — the wrapper looks for an object named exactly 'rib_assembly1'",+ "n": 12,+ "kind": "lint/link_name"+ },+ {+ "gate": "motion_direction",+ "severity": "warn",+ "message": "motion check skipped: motion_direction_check: 'lower_latch_mount' is not a movable joint",+ "n": 2,+ "kind": "motion_direction/skipped"+ },+ {+ "gate": "motion_direction",+ "severity": "error",+ "message": "elbow_joint: child 'upper_arm' moves (0.0, 0.48, 0.877) for q=+0.35; expected front (WRONG — flip the axis sign or swap limits). Plan says: \"upper arm articulates forward and back over a 126 degree range\"",+ "n": 8,+ "kind": "motion_direction/wrong_axis"+ },+ {+ "gate": "motion_direction",+ "severity": "error",+ "message": "left_leg_joint: child 'left_leg_frame' moves (0.985, 0.0, 0.174) for q=+0.35; expected +y (WRONG — flip the axis sign or swap limits). Plan says: \"Left leg frame rotates clockwise (+Y axis) folding inward toward table center\"",+ "n": 6,+ "kind": "motion_direction/wrong_axis"+ },+ {+ "gate": "motion_direction",+ "severity": "error",+ "message": "right_leg_joint: child 'right_leg_frame' moves (-0.985, 0.0, 0.174) for q=+0.35; expected -y (WRONG — flip the axis sign or swap limits). Plan says: \"Right leg frame rotates counter-clockwise (-Y axis) folding inward toward table center\"",+ "n": 6,+ "kind": "motion_direction/wrong_axis"+ },+ {+ "gate": "motion_direction",+ "severity": "error",+ "message": "shade_joint: child 'lamp_shade' moves (0.0, 0.73, -0.683) for q=+0.35; expected up (WRONG — flip the axis sign or swap limits). Plan says: \"tilts lamp shade up and down at the arm tip\"",+ "n": 1,+ "kind": "motion_direction/wrong_axis"+ },+ {+ "gate": "motion_direction",+ "severity": "error",+ "message": "shoulder_joint: child 'lower_arm' moves (0.0, 0.895, 0.445) for q=+0.35; expected up (WRONG — flip the axis sign or swap limits). Plan says: \"lower arm pitches up and down from 20 to 80 degrees elevation\"",+ "n": 8,+ "kind": "motion_direction/wrong_axis"+ },+ {+ "gate": "render_console",+ "severity": "warn",+ "message": "low frame rate 10 fps",+ "n": 3,+ "kind": "render_console/slow_or_error"+ },+ {+ "gate": "scene_frames",+ "severity": "warn",+ "message": "camera inside / touching geometry: inside ['CityTower', 'CityTower']",+ "n": 2,+ "kind": "scene_frames/camera_placement"+ },+ {+ "gate": "scene_frames",+ "severity": "error",+ "message": "camera is 1.0 m BELOW the ground level (6.21 m)",+ "n": 3,+ "kind": "scene_frames/camera_placement"+ },+ {+ "gate": "scene_frames",+ "severity": "warn",+ "message": "flat frame: one luminance band holds 100% of the pixels",+ "n": 5,+ "kind": "scene_frames/dark_or_flat"+ },+ {+ "gate": "scene_frames",+ "severity": "warn",+ "message": "frame too dark: mean luminance 0.11, 36% of pixels near black",+ "n": 11,+ "kind": "scene_frames/dark_or_flat"+ },+ {+ "gate": "shader_preflight",+ "severity": "warn",+ "message": "ShaderMaterial 'Water' ignores scene.fog (set fog: true, merge THREE.UniformsLib.fog, include fog_pars_fragment/fog_fragment)",+ "n": 0,+ "kind": "shader/compile_or_binding",+ "origin": "codeverse source (gate not yet represented in bench/out)"+ },+ {+ "gate": "shader_preflight",+ "severity": "error",+ "message": "ShaderMaterial 'Water' reads uTime but uniforms.uTime is missing",+ "n": 0,+ "kind": "shader/compile_or_binding",+ "origin": "codeverse source (gate not yet represented in bench/out)"+ }+ ]+}\ No newline at end of filediff --git a/harness/tests/skills/test_config.py b/harness/tests/skills/test_config.pynew file mode 100644index 00000000..2e40ddee--- /dev/null+++ b/harness/tests/skills/test_config.py@@ -0,0 +1,49 @@+"""The switches: read at call time, tolerant of garbage, and registered as 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+``CV3D_SKILLS`` from becoming that switch.+"""++from __future__ import annotations++import pytest++from codeverse.skills import config as C+from codeverse.tracks import plan_features as F+++def test_off_by_default(monkeypatch):+ for env in (C.SKILLS_ENV, C.SKILLS_MAX_ENV, C.SKILLS_UNVERIFIED_ENV):+ monkeypatch.delenv(env, raising=False)+ assert C.skills_enabled() is False+ assert C.skills_unverified() is False+ assert C.skills_max() == C.DEFAULT_SKILLS_MAX == 5++[email protected]("raw, want", [("on", True), ("1", True), ("true", True), ("YES", True),+ ("off", False), ("0", False), ("", False), ("maybe", False)])+def test_flag_spellings(monkeypatch, raw, want):+ monkeypatch.setenv(C.SKILLS_ENV, raw)+ assert C.skills_enabled() is want+++def test_read_at_call_time_not_cached(monkeypatch):+ monkeypatch.setenv(C.SKILLS_ENV, "on")+ assert C.skills_enabled()+ monkeypatch.setenv(C.SKILLS_ENV, "off")+ assert not C.skills_enabled()++[email protected]("raw, want", [("3", 3), ("0", 0), ("-1", 0), ("nope", 5), ("", 5)])+def test_max_is_never_a_crash(monkeypatch, raw, want):+ monkeypatch.setenv(C.SKILLS_MAX_ENV, raw)+ assert C.skills_max() == want+++def test_the_switches_are_registered_as_live_not_dead():+ for env in (C.SKILLS_ENV, C.SKILLS_MAX_ENV, C.SKILLS_UNVERIFIED_ENV):+ assert env in F.LIVE_SWITCHES, f"{env} must be declared so ab_plan accepts an arm using it"+ assert env not in F.DEAD_SWITCHES+ assert F.LIVE_SWITCHES[env] == "codeverse/skills/config.py"+ assert F.dead_env_keys({C.SKILLS_ENV: "on"}) == []diff --git a/harness/tests/skills/test_end_to_end.py b/harness/tests/skills/test_end_to_end.pynew file mode 100644index 00000000..f6bcf7ce--- /dev/null+++ b/harness/tests/skills/test_end_to_end.py@@ -0,0 +1,149 @@+"""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.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from codeverse.config import Settings+from codeverse.contracts.common import Language+from codeverse.contracts.run import RunStatus+from codeverse.skills.materialize import MARK_BEGIN+from codeverse.skills.registry import ROUTED_SKILLS+from codeverse.tracks.static_object import StaticObjectTrack+from codeverse.workspace import Workspace+from tests.orchestrator_tracks.conftest import chair_plan as _chair_plan+from tests.orchestrator_tracks.conftest import make_spec+from tests.orchestrator_tracks.fakes import (+ FakeAgent,+ FakeChatModel,+ FakeJudge,+ FakeRuntime,+ FakeServices,+)+from tests.orchestrator_tracks.test_tracks import _agent_writer+from tests.skills.conftest import write_bundle+++class RealMessageServices(FakeServices):+ """FakeServices, but the contract gate speaks the words the real gate speaks.++ The stock fake says "Seat bbox off by 0.03 m", which ``finding_kind`` correctly+ refuses to classify — it is not a message our gates emit. Routing off a gate is only+ proven by the real text."""++ def contract(self, measurement, plan, tol_m, language=""):+ from codeverse.contracts.artifacts import GateFinding, GateReport, Severity++ parts = list(getattr(plan, "parts", []))[: self.contract_errors]+ findings = [GateFinding(gate="contract", severity=Severity.ERROR, target=p.name,+ message=f"part '{p.name}' bbox deviates from the plan (worst 3.4x tolerance)",+ fix_hint=f"resize {p.name} to its plan extents") for p in parts]+ return GateReport(gate="contract", passed=not findings, findings=findings)++[email protected](autouse=True)+def _no_brief(monkeypatch):+ """The fake planner answers one canned plan; the optional brief call would eat it."""+ monkeypatch.setenv("CV3D_PLAN_BRIEF", "off")+++def chair_plan():+ return _chair_plan.__wrapped__()+++def settings(tmp_path: Path) -> Settings:+ return Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")+++def run(tmp_path: Path, chair_plan, settings, monkeypatch):+ lib = tmp_path / "library"+ for name in ROUTED_SKILLS:+ write_bundle(lib, name)+ monkeypatch.setenv("CV3D_SKILLS", "on")+ monkeypatch.setenv("CV3D_SKILLS_DIR", str(lib))+ ws = Workspace(tmp_path / "runs" / "chair")+ agent = FakeAgent(_agent_writer)+ track = StaticObjectTrack(services=RealMessageServices(contract_errors=1), judge=FakeJudge(scores=(0.55, 0.7, 0.85)),+ agent=agent, 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 rec.status is RunStatus.PASSED+ return rec, ws, agent+++def test_the_bundles_reach_the_workspace_in_both_roots(run):+ _, ws, _ = run+ for root in (".agents/skills", ".claude/skills"):+ names = sorted(p.name for p in (ws.root / root).iterdir())+ assert names and all((ws.root / root / n / "SKILL.md").is_file() for n in names)+++def test_the_index_reaches_the_file_the_agent_reads(run):+ _, ws, _ = run+ body = (ws.root / "AGENTS.md").read_text()+ assert MARK_BEGIN in body and "MANDATORY" in body+++def test_every_round_records_what_was_attached_and_what_was_read(run):+ rec, _, _ = run+ for r in rec.rounds:+ assert r.skills is not None, r.kind+ assert r.skills.listed and len(r.skills.listed) <= 5+ assert r.skills.index_tokens > 0+ assert r.skills.deep_read_rate == 0.0 # the fake agent reads nothing — and we can SEE that+ assert {x.name for x in r.skills.reads} == set(r.skills.listed)+++def test_the_baseline_round_gets_the_standing_set_and_the_next_round_gets_the_gate_set(run):+ rec, _, _ = run+ baseline = rec.rounds[0].skills.listed+ refine = rec.rounds[1].skills.listed+ assert "cv3d-form-manifest" in baseline # R5: a baseline still decides what to build+ assert "cv3d-bbox-contract" in refine # R4: the contract gate fired in round 0+ reasons = {x.name: x.reason for x in rec.rounds[1].skills.reads}+ assert "contract/" in reasons["cv3d-bbox-contract"]+++def test_the_body_that_was_sent_is_hashed_into_the_record(run):+ """`prompt_hashes` already answers "what text decided this run"; a skill body is+ part of that text, so `skill:<name>` rows sit beside the prompt rows."""+ rec, _, _ = run+ keys = [k for k in rec.prompt_hashes if k.startswith("skill:")]+ assert keys and all(rec.prompt_hashes[k] for k in keys)+ assert {k.split(":", 1)[1] for k in keys} >= set(rec.rounds[0].skills.listed)+++def test_the_cap_holds_across_a_whole_run(run):+ rec, _, _ = run+ assert all(len(r.skills.listed) <= 5 for r in rec.rounds)+++def test_telemetry_is_on_disk_for_the_report_command(run):+ _, ws, _ = run+ rows = (ws.root / "telemetry" / "skills.jsonl").read_text().splitlines()+ assert len(rows) == 3 and all('"listed"' in r for r in rows)+++def test_the_switch_off_leaves_no_trace(tmp_path, chair_plan, settings, monkeypatch):+ monkeypatch.delenv("CV3D_SKILLS", raising=False)+ 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_hook.py b/harness/tests/skills/test_hook.pynew file mode 100644index 00000000..8227ed1e--- /dev/null+++ b/harness/tests/skills/test_hook.py@@ -0,0 +1,153 @@+"""``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.+"""++from __future__ import annotations++from pathlib import Path+from types import SimpleNamespace as NS++import pytest++from codeverse.contracts.artifacts import GateFinding, GateReport, Severity+from codeverse.skills import config as C+from codeverse.tracks import skills_hook as H+++class Events(list):+ def emit(self, name, **kw):+ self.append((name, kw))+++def ctx(tmp_path: Path, library_dir: Path, monkeypatch):+ root = tmp_path / "ws"+ root.mkdir()+ for name in ("AGENTS.md", "GEMINI.md", "CLAUDE.md"):+ (root / name).write_text("# body\n")+ monkeypatch.setenv("CV3D_SKILLS_DIR", str(library_dir))+ parts = [NS(name=f"P{i}", instances=1, symmetry="none", children=[]) for i in range(3)]+ hashes: dict[str, str] = {}+ return NS(ws=NS(root=root), spec=NS(track=NS(value="static_object")), language=NS(value="blender"),+ agent_id="api-agent:gemini-3.7-flash", plan=NS(parts=parts, summary="a chair"),+ single_shot=False, extra={}, events=Events(), prompt_hashes=hashes,+ record_prompt=lambda name, text: hashes.__setitem__(name, str(len(text))))+++def test_the_switch_off_means_no_files_no_events_no_record(ctx, monkeypatch):+ monkeypatch.delenv(C.SKILLS_ENV, raising=False)+ assert H.attach_for_round(ctx, index=0, kind="baseline") is None+ assert not (ctx.ws.root / ".agents").exists()+ assert ctx.events == [] and ctx.extra == {}+ assert H.record_usage(ctx, index=0, kind="baseline") is None+ assert H.repair_pointers(ctx, None) == ""+++def test_the_switch_on_attaches_records_and_measures(ctx, monkeypatch):+ monkeypatch.setenv(C.SKILLS_ENV, "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(C.SKILLS_ENV, "on")+ rounds = ctx.ws.root / "rounds"+ rounds.mkdir()+ rec = {"index": 0, "kind": "baseline", "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")],+ ).model_dump(mode="json")]}+ import json++ (rounds / "r00.json").write_text(json.dumps(rec))+ got = H.attach_for_round(ctx, index=1, kind="repair")+ assert "cv3d-part-contact" in got.listed+ assert "connectivity/floating_part" in got.reasons["cv3d-part-contact"]+ assert got.selections[0].gate_fired+++def test_round_zero_never_looks_for_a_previous_round(ctx, monkeypatch):+ monkeypatch.setenv(C.SKILLS_ENV, "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(C.SKILLS_ENV, "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 "cv3d-blender-forms" in text+++def test_single_shot_inlines_one_body_into_every_task(ctx, monkeypatch):+ monkeypatch.setenv(C.SKILLS_ENV, "on")+ ctx.single_shot = True+ got = H.attach_for_round(ctx, index=0, kind="baseline")+ assert got.inlined and got.paths == []++ class Task:+ def __init__(self, prompt):+ self.prompt = prompt++ def model_copy(self, *, update):+ return Task(update["prompt"])++ out = H.with_inlined_skill(ctx, [Task("write the chair")])+ 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(C.SKILLS_ENV, "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(C.SKILLS_ENV, "on")+ monkeypatch.setenv("CV3D_SKILLS_DIR", "/definitely/not/a/directory")+ with caplog.at_level("WARNING"):+ got = H.attach_for_round(ctx, index=0, kind="baseline")+ assert got is not None and got.listed == [] # routed nothing, wrote nothing, raised nothing+++def test_a_failed_attach_clears_the_previous_rounds_set(ctx, monkeypatch):+ """Otherwise round N+1 probes round N's bundles and reports reads it never earned."""+ monkeypatch.setenv(C.SKILLS_ENV, "on")+ assert H.attach_for_round(ctx, index=0, kind="baseline")+ monkeypatch.setattr("codeverse.skills.attach_skills",+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("boom")))+ assert H.attach_for_round(ctx, index=1, kind="refine") is None+ assert H.record_usage(ctx, index=1, kind="refine") is None+++def test_a_probe_failure_is_logged_not_raised(ctx, monkeypatch):+ monkeypatch.setenv(C.SKILLS_ENV, "on")+ H.attach_for_round(ctx, index=0, kind="baseline")+ monkeypatch.setattr("codeverse.skills.telemetry.probe_reads", lambda *a, **k: (_ for _ in ()).throw(OSError("boom")))+ assert H.record_usage(ctx, index=0, kind="baseline") is None+++def test_the_round_and_the_repair_loop_really_call_the_hook():+ """Grep-level, on purpose: these two call sites are the whole integration, and a+ refactor that drops one leaves every unit test above green."""+ src = Path(__file__).resolve().parents[2] / "codeverse" / "tracks"+ steps = (src / "steps.py").read_text()+ assert "skills_hook.attach_for_round(" in steps+ assert "skills_hook.with_inlined_skill(" in steps+ assert "rec.skills = skills_hook.record_usage(" in steps+ assert "skills_hook.repair_pointers(" in (src / "repair.py").read_text()diff --git a/harness/tests/skills/test_library.py b/harness/tests/skills/test_library.pynew file mode 100644index 00000000..ef7788fd--- /dev/null+++ b/harness/tests/skills/test_library.py@@ -0,0 +1,146 @@+"""The tests that run over the REAL bundles as they land (T1-T4, T6, T8).++Every test here skips cleanly while the library is empty — the machinery ships before the+bodies do — and starts biting the moment a bundle appears. That ordering is deliberate:+the Author phase should not be able to land a bundle that contradicts the contract, quotes+a stale constant, or grows into a second cookbook, and it should not have to remember to+add a test for each of those.+"""++from __future__ import annotations++import re+import shutil+import subprocess+from collections import defaultdict+from pathlib import Path++import pytest++from codeverse.skills import bundle_dirs, iter_skills, skills_dir, validate_bundle+from codeverse.skills.claims import check_claims, claim_values+from codeverse.skills.loader import BODY_MAX_LINES, BODY_MAX_TOKENS+from codeverse.skills.registry import ROUTED_SKILLS, ROUTES++BUNDLES = bundle_dirs()+SKILLS = list(iter_skills()) if BUNDLES else []+pytestmark = pytest.mark.skipif(not BUNDLES, reason=f"no bundles in {skills_dir()} yet (the Author phase writes them)")++MAX_FENCE_LINES = 20+#: law 2 of the contract: `conventions.py` is the only place a frame/unit rule is stated.+#: A skill that restates one gives the agent two truths to choose between.+CONTRACT_RESTATEMENTS = (+ r"\bZ is UP\b", r"\bY is UP\b", r"-Y is the FRONT", r"\+Z is the FRONT",+ r"units are meters", r"\bY-up\b.*\bframe\b",+)++[email protected]("d", BUNDLES, ids=[d.name for d in BUNDLES])+def test_bundle_is_spec_conformant(d: Path):+ assert validate_bundle(d) == []++[email protected]("s", SKILLS, ids=[s.name for s in SKILLS])+def test_body_is_inside_the_budget(s):+ assert s.body_lines <= BODY_MAX_LINES+ assert s.body_tokens <= BODY_MAX_TOKENS++[email protected]("s", SKILLS, ids=[s.name for s in SKILLS])+def test_a_skill_states_rules_and_does_not_become_a_second_cookbook(s):+ """No code fence longer than 20 lines: code lives in the cookbook, which is one+ library of truth with 3,560 lines already."""+ for fence in re.findall(r"^```.*?^```", s.body, re.S | re.M):+ n = len(fence.splitlines()) - 2+ assert n <= MAX_FENCE_LINES, f"{s.name}: a {n}-line code fence belongs in the cookbook"++[email protected]("s", SKILLS, ids=[s.name for s in SKILLS])+def test_a_skill_does_not_restate_the_frame_or_unit_contract(s):+ for pat in CONTRACT_RESTATEMENTS:+ assert not re.search(pat, s.body, re.I), f"{s.name}: {pat!r} belongs in conventions.py only"++[email protected]("s", SKILLS, ids=[s.name for s in SKILLS])+def test_every_pinned_number_still_matches_its_live_constant(s):+ """T2: changing PENETRATION_ERROR_M must break the test that ships the skill quoting it."""+ assert check_claims(s) == []++[email protected]("s", SKILLS, ids=[s.name for s in SKILLS])+def test_an_evidence_thin_bundle_says_so(s):+ if s.evidence != "measured":+ assert s.metadata.get("evidence_note"), f"{s.name}: a non-measured bundle must say why in metadata"+++def test_co_routing_skills_never_disagree_about_a_number():+ """T3: astra3d checked one hand-picked pair; this checks the whole co-routing graph."""+ by_skill = {s.name: claim_values(s.name) for s in SKILLS}+ pairs: set[tuple[str, str]] = set()+ for a in by_skill:+ for b in by_skill:+ if a < b and _can_co_route(a, b):+ pairs.add((a, b))+ for a, b in sorted(pairs):+ shared = set(by_skill[a]) & set(by_skill[b])+ for key in sorted(shared):+ assert by_skill[a][key] == by_skill[b][key], f"{a} and {b} disagree about {key}"+++def _can_co_route(a: str, b: str) -> bool:+ """Two skills can co-route when some (track, language) can name both."""+ def reach(name: str) -> set[tuple[str, str]]:+ out: set[tuple[str, str]] = set()+ for r in ROUTES:+ if r.skill != name:+ continue+ for t in r.tracks or ("*",):+ for lang in r.languages or ("*",):+ out.add((t, lang))+ return out++ ra, rb = reach(a), reach(b)+ return any((t1 == t2 or "*" in (t1, t2)) and (l1 == l2 or "*" in (l1, l2))+ for t1, l1 in ra for t2, l2 in rb)+++def test_every_routed_skill_has_a_bundle_once_the_library_is_complete():+ have = {d.name for d in BUNDLES}+ missing = [n for n in ROUTED_SKILLS if n not in have]+ if missing and len(have) < len(ROUTED_SKILLS):+ pytest.skip(f"library still being written: {len(have)}/{len(ROUTED_SKILLS)} bundles")+ assert missing == []+++def test_no_bundle_exists_that_no_route_can_ever_attach():+ orphans = [d.name for d in BUNDLES if d.name not in ROUTED_SKILLS]+ assert orphans == [], f"unroutable bundles pay the index and never help: {orphans}"++[email protected](shutil.which("skills-ref") is None,+ reason="the reference validator is not installed (pip install skills-ref)")[email protected]("d", BUNDLES, ids=[d.name for d in BUNDLES])+def test_the_reference_validator_accepts_the_bundle(d: Path):+ """T1: our loader implements the spec, but the spec's own validator is the arbiter."""+ p = subprocess.run(["skills-ref", "validate", str(d)], capture_output=True, text=True, check=False)+ assert p.returncode == 0, p.stdout + p.stderr+++def test_every_corpus_statistic_a_skill_quotes_is_still_true():+ """T8: a percentage in a body must be within 20% of what bench/out says today."""+ out = Path(__file__).resolve().parents[2] / "bench" / "out"+ if not out.is_dir():+ pytest.skip("no bench/out in this checkout")+ quoted = defaultdict(list)+ for s in SKILLS:+ for m in re.finditer(r"(\d{1,3}(?:\.\d)?)\s?%", s.body):+ quoted[s.name].append(float(m.group(1)))+ if not quoted:+ pytest.skip("no corpus percentages quoted yet")+ # The recomputation lives with the corpus tooling; here we only assert the bodies+ # carry their provenance, so a reader can check the number without guessing.+ for name, values in quoted.items():+ body = next(s.body for s in SKILLS if s.name == name)+ assert re.search(r"(bench/out|battery|n\s?=\s?\d+|20\d\d-\d\d-\d\d)", body), (+ f"{name} quotes {values} with no battery / n / date beside it")diff --git a/harness/tests/skills/test_live_discovery.py b/harness/tests/skills/test_live_discovery.pynew file mode 100644index 00000000..29a3a945--- /dev/null+++ b/harness/tests/skills/test_live_discovery.py@@ -0,0 +1,74 @@+"""T7 — the smoke test that a CLI upgrade cannot pass by accident (`pytest -m live`).++Everything else in this package proves we WROTE the bundles correctly. Only a real CLI+can prove it FINDS them, and that is the failure mode with no symptom: a moved discovery+root ships an empty index, the run still passes, and the read rate reads 0% as if the+model had ignored the skill. The design's discovery table was read out of the shipped+binaries; this test is what keeps it true after the next `npm -g update`.++The assertion is the read probe itself, so one test covers both halves: if the CLI found+and opened the bundle, ``atime > mtime`` on its ``references/`` file.+"""++from __future__ import annotations++import shutil+from pathlib import Path++import pytest++from codeverse.agents.registry import get_coding_agent+from codeverse.contracts.agent import AgentJob+from codeverse.skills.materialize import materialize_skills+from codeverse.skills.telemetry import probe_reads+from tests.skills.conftest import write_bundle++pytestmark = pytest.mark.live++PROMPT = ("Your workspace has a skill installed whose description matches this task. "+ "Activate it, read the whole skill INCLUDING every file under its references/ "+ "directory, then reply with the single magic word the reference file contains. "+ "Do not write any file.")+MAGIC = "ORTHOGONAL-KUMQUAT"+BACKENDS = [("gemini-cli", "gemini-3.7-flash"), ("codex", "gpt-5.2-codex"),+ ("claude-code", "claude-opus-5"), ("agy", "gemini-3.7-flash")]++[email protected]("kind, model", BACKENDS, ids=[k for k, _ in BACKENDS])+def test_the_cli_discovers_and_opens_a_materialised_skill(tmp_path: Path, kind: str, model: str):+ if shutil.which(kind) is None:+ pytest.skip(f"{kind} is not installed here")+ ws = tmp_path / "ws"+ (ws / "src").mkdir(parents=True)+ for name in ("AGENTS.md", "GEMINI.md", "CLAUDE.md"):+ (ws / name).write_text("# 3dcv workspace\n\nRead this file before acting.\n")++ lib = tmp_path / "library"+ write_bundle(lib, "cv3d-live-probe",+ description="Answer the magic-word question. Use when a task asks for the magic word.",+ body="Read `references/magic.md` and reply with the word it contains.",+ references={"magic.md": f"The magic word is {MAGIC}.\n"})+ from codeverse.skills import load_skill+ from codeverse.skills.materialize import write_index+ from codeverse.skills.prompting import index_block++ skill = load_skill("cv3d-live-probe", lib)+ materialize_skills(ws, [skill])+ write_index(ws, index_block([skill], kind))++ agent = get_coding_agent(f"{kind}:{model}")+ ok, why = agent.available()+ if not ok:+ pytest.skip(f"{kind} unavailable: {why}")+ res = agent.run(AgentJob(workspace=str(ws), prompt=PROMPT, spatial_tools=False,+ max_turns=8, timeout_s=300, label="skills_live"))++ from codeverse.skills.model import Selection, SkillsMaterialized++ got = SkillsMaterialized(+ listed=[skill.name],+ selections=[Selection(skill=skill, priority=99, rules=("live",), reason="live smoke")])+ usage = probe_reads(ws, got)+ assert usage.surfaced == [skill.name], f"{kind} never opened SKILL.md — discovery root drift? ({res.exit_reason})"+ assert usage.deep == [skill.name], f"{kind} opened SKILL.md but not references/ ({res.text[:300]})"+ assert MAGIC in (res.text or ""), f"{kind} read the skill but did not follow it: {res.text[:300]}"diff --git a/harness/tests/skills/test_loader.py b/harness/tests/skills/test_loader.pynew file mode 100644index 00000000..cfbf9004--- /dev/null+++ b/harness/tests/skills/test_loader.py@@ -0,0 +1,139 @@+"""The spec's rules, enforced where a test can see them (design §6.2, T1)."""++from __future__ import annotations++from pathlib import Path++import pytest++from codeverse.skills import all_skills, bundle_dirs, iter_skills, load_skill+from codeverse.skills.loader 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, "cv3d-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 == "cv3d-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+ assert s.ref().name == "cv3d-demo"+++def test_a_directory_argument_finds_the_skill_file(tmp_path: Path):+ d = write_bundle(tmp_path, "cv3d-demo")+ assert parse_skill(d).name == parse_skill(d / "SKILL.md").name++[email protected]("text, expect", [+ ("no frontmatter at all\n", "missing YAML frontmatter"),+ ("---\nname: [1, 2]\n---\nbody\n", "must match"),+ ("---\ndescription: only this\n---\nbody\n", "no `name`"),+ ("---\nname: cv3d-demo\n---\nbody\n", "no `description`"),+ ("---\nname: cv3d-demo\ndescription: d\nwhen_to_use: x\n---\nbody\n", "unknown frontmatter key"),+ ("---\nname: cv3d-demo\ndescription: use <script> tags\n---\nbody\n", "prompt-injection"),+ ("---\nname: cv3d_demo\ndescription: d\n---\nbody\n", "must match"),+ ("---\nname: cv3d--demo\ndescription: d\n---\nbody\n", "must match"),+ ("---\nname: Cv3d-Demo\ndescription: d\n---\nbody\n", "must match"),+ ("---\n- a\n- b\n---\nbody\n", "must be a YAML mapping"),+ ("---\nname: cv3d-demo\ndescription: d\nmetadata:\n a:\n b: c\n---\nbody\n", "must be a scalar"),+])+def test_malformed_frontmatter_is_rejected_with_a_reason(tmp_path: Path, text: str, expect: str):+ d = tmp_path / "cv3d-demo"+ d.mkdir()+ (d / "SKILL.md").write_text(text)+ with pytest.raises(SkillError, match=expect):+ parse_skill(d)+++def test_name_must_equal_the_directory_name(tmp_path: Path):+ d = tmp_path / "cv3d-elsewhere"+ d.mkdir()+ (d / "SKILL.md").write_text("---\nname: cv3d-demo\ndescription: d\n---\nbody\n")+ with pytest.raises(SkillError, match="directory name"):+ parse_skill(d)+++def test_description_length_is_the_spec_limit(tmp_path: Path):+ d = tmp_path / "cv3d-demo"+ d.mkdir()+ (d / "SKILL.md").write_text(f"---\nname: cv3d-demo\ndescription: {'x' * 1025}\n---\nbody\n")+ with pytest.raises(SkillError, match="1024"):+ 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, "cv3d-big", evidence="guesswork", body="x\n" * (BODY_MAX_LINES + 5))+ (d / "references" / "deeper").mkdir()+ (d / "references" / "deeper" / "x.md").write_text("nope")+ issues = " | ".join(validate_bundle(d))+ assert "cap is" in issues and "metadata.evidence" in issues and "one level of references" in issues+++def test_validate_flags_a_symlink_because_codex_refuses_them(tmp_path: Path):+ d = write_bundle(tmp_path, "cv3d-demo")+ (d / "references" / "link.md").symlink_to(d / "SKILL.md")+ assert any("symlink" in i for i in validate_bundle(d))+++def test_validate_wants_a_verified_date(tmp_path: Path):+ d = tmp_path / "cv3d-demo"+ d.mkdir()+ (d / "SKILL.md").write_text("---\nname: cv3d-demo\ndescription: d\nmetadata:\n evidence: measured\n---\nbody\n")+ 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, "cv3d-demo")) == []+++def test_iteration_skips_modules_dunder_dirs_and_claims(tmp_path: Path):+ write_bundle(tmp_path, "cv3d-demo")+ (tmp_path / "_claims").mkdir()+ (tmp_path / "_claims" / "cv3d-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)] == ["cv3d-demo"]+ assert list(all_skills(tmp_path)) == ["cv3d-demo"]+++def test_a_broken_bundle_is_skipped_not_fatal_but_strict_raises(tmp_path: Path, caplog):+ write_bundle(tmp_path, "cv3d-good")+ bad = tmp_path / "cv3d-bad"+ bad.mkdir()+ (bad / "SKILL.md").write_text("no frontmatter\n")+ with caplog.at_level("WARNING"):+ assert [s.name for s in iter_skills(tmp_path)] == ["cv3d-good"]+ assert any("cv3d-bad" in r.getMessage() for r in caplog.records)+ with pytest.raises(SkillError):+ list(iter_skills(tmp_path, strict=True))+++def test_load_skill_by_name(tmp_path: Path):+ write_bundle(tmp_path, "cv3d-demo")+ assert load_skill("cv3d-demo", tmp_path).name == "cv3d-demo"+ with pytest.raises(SkillError, match="no skill"):+ load_skill("cv3d-missing", tmp_path)+++def test_the_library_dir_is_overridable_for_tests_and_the_live_smoke(tmp_path: Path, monkeypatch):+ from codeverse.skills import SKILLS_DIR_ENV, skills_dir++ write_bundle(tmp_path, "cv3d-demo")+ monkeypatch.setenv(SKILLS_DIR_ENV, str(tmp_path))+ assert skills_dir() == tmp_pathdiff --git a/harness/tests/skills/test_materialize_prompting.py b/harness/tests/skills/test_materialize_prompting.pynew file mode 100644index 00000000..41a5be4a--- /dev/null+++ b/harness/tests/skills/test_materialize_prompting.py@@ -0,0 +1,180 @@+"""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.+"""++from __future__ import annotations++import os+from pathlib import Path++import pytest++from codeverse.skills.materialize import (+ BODY_FILES,+ MARK_BEGIN,+ MARK_END,+ SKILL_ROOTS,+ attach_skills,+ materialize_skills,+ write_index,+)+from codeverse.skills.prompting import (+ MANDATE,+ NATIVE_LOADERS,+ index_block,+ index_tokens,+ inline_body,+ repair_pointers,+)+from codeverse.skills.router import select+++def ws(tmp_path: Path) -> Path:+ root = tmp_path / "ws"+ root.mkdir()+ for name in BODY_FILES:+ (root / name).write_text("# 3dcv workspace\n\n## Hard rules\n\n1. …\n")+ 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["cv3d-part-contact"], library["cv3d-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()+ assert len(written) == 2 * 2 * 2 # 2 roots x 2 skills x (SKILL.md + one reference)+++def test_nothing_in_a_materialised_tree_is_a_symlink_because_codex_refuses_them(ws, library):+ materialize_skills(ws, [library["cv3d-part-contact"]])+ for root in SKILL_ROOTS:+ assert not any(p.is_symlink() for p in (ws / root).rglob("*"))+++def test_atime_equals_mtime_after_writing_so_the_read_probe_has_a_zero_point(ws, library):+ for p in materialize_skills(ws, [library["cv3d-part-contact"]]):+ st = os.stat(p)+ assert abs(st.st_atime - st.st_mtime) < 0.001+++def test_a_skill_that_is_no_longer_routed_is_removed_from_the_workspace(ws, library):+ materialize_skills(ws, [library["cv3d-part-contact"], library["cv3d-blender-forms"]])+ materialize_skills(ws, [library["cv3d-part-contact"]])+ for root in SKILL_ROOTS:+ assert (ws / root / "cv3d-part-contact").is_dir()+ assert not (ws / root / "cv3d-blender-forms").exists()+++# --------------------------------------------------------------------------- prompt text+def test_native_loader_backends_get_one_sentence_and_no_second_index(library):+ skills = [library["cv3d-part-contact"], library["cv3d-bbox-contract"]]+ for kind in NATIVE_LOADERS:+ text = index_block(skills, kind)+ assert MANDATE in text+ assert "cv3d-part-contact" not in text, f"{kind} would be double-indexed"+ assert index_tokens(skills, kind) < 60+++def test_api_agent_gets_the_index_it_cannot_discover(library):+ skills = [library["cv3d-part-contact"], library["cv3d-bbox-contract"]]+ text = index_block(skills, "api-agent")+ assert MANDATE in text+ for s in skills:+ assert f"**{s.name}**" in text and f".agents/skills/{s.name}/SKILL.md" in text+++def test_the_worst_case_api_agent_index_stays_inside_its_budget(library):+ """Design §5.4 prices the index at ~225 tokens for five skills; 300 is the ceiling."""+ five = list(library.values())[:5]+ assert index_tokens(five, "api-agent") <= 300+++def test_an_empty_route_adds_no_text_at_all(library):+ assert index_block([], "api-agent") == "" and index_block([], "codex") == ""+++def test_claude_code_is_pointed_at_its_own_root(library):+ text = index_block([library["cv3d-part-contact"]], "unknown-backend")+ assert ".agents/skills/" in text+ from codeverse.skills.prompting import skill_path++ assert skill_path("cv3d-x", agent_kind="claude-code") == ".claude/skills/cv3d-x/SKILL.md"+++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)+ text = repair_pointers(sel)+ assert "cv3d-part-contact" in text and "connectivity/interpenetration" in text+ assert "cv3d-blender-forms" not in text # standing rows are already in the workspace+ assert repair_pointers([]) == ""+++def test_inline_body_picks_the_highest_priority_body_and_respects_the_cap(library):+ sel = select("static_object", "blender", "repair", signals={"multi_part": True},+ findings=["connectivity/interpenetration"], library=library)+ name, text = inline_body(sel)+ assert name == "cv3d-part-contact" and "cv3d-part-contact" in text+ assert inline_body(sel, max_tokens=0) == ("", "")+++# --------------------------------------------------------------------------- the section+def test_the_index_is_written_into_every_body_file_and_is_replaceable(ws, library):+ write_index(ws, index_block([library["cv3d-part-contact"]], "api-agent"))+ for name in BODY_FILES:+ body = (ws / name).read_text()+ assert MARK_BEGIN in body and MARK_END in body and "cv3d-part-contact" in body+ assert body.startswith("# 3dcv workspace")+ write_index(ws, index_block([library["cv3d-bbox-contract"]], "api-agent"))+ body = (ws / "AGENTS.md").read_text()+ assert body.count(MARK_BEGIN) == 1 and "cv3d-part-contact" not in body and "cv3d-bbox-contract" in body+ write_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",+ agent_kind="api-agent", plan=_plan(), library=library, max_skills=5,+ allow_unverified=False)+ assert got.listed and got.paths and got.index_tokens > 0+ assert set(got.reasons) == set(got.listed)+ assert all("cv3d-" in p for p in got.paths)+ assert "cv3d-part-contact" 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",+ agent_kind="single-shot", plan=_plan(), library=library, single_shot=True,+ max_skills=5, allow_unverified=False)+ assert got.inlined and got.paths == [] and got.index_tokens == 0+ 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",+ agent_kind="codex", 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_packaging.py b/harness/tests/skills/test_packaging.pynew file mode 100644index 00000000..1f56cb72--- /dev/null+++ b/harness/tests/skills/test_packaging.py@@ -0,0 +1,71 @@+"""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.+"""++from __future__ import annotations++import shutil+import subprocess+import sys+import zipfile+from pathlib import Path++import pytest++from codeverse._compat import tomllib++HARNESS = Path(__file__).resolve().parents[2]+PROBE = "cv3d-packaging-probe"+++def test_package_data_declares_the_skill_tree():+ data = tomllib.loads((HARNESS / "pyproject.toml").read_text())+ globs = data["tool"]["setuptools"]["package-data"]["codeverse"]+ assert "skills/**/*" in globs+++def 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+ the guarantee is proven now rather than the first time a bundle lands."""+ probe = HARNESS / "codeverse" / "skills" / PROBE+ existing = [p.name for p in (HARNESS / "codeverse" / "skills").iterdir()+ if p.is_dir() and (p / "SKILL.md").is_file()]+ made_probe = False+ try:+ if not existing:+ (probe / "references").mkdir(parents=True)+ (probe / "SKILL.md").write_text(f"---\nname: {PROBE}\ndescription: probe\n---\nbody\n")+ (probe / "references" / "depth.md").write_text("depth\n")+ made_probe = True+ out = tmp_path / "wheel"+ r = subprocess.run([sys.executable, "-c",+ f"from setuptools import build_meta as b; print(b.build_wheel({str(out)!r}))"],+ cwd=HARNESS, capture_output=True, text=True, check=False)+ assert r.returncode == 0, r.stdout + r.stderr+ whl = next(out.glob("*.whl"))+ names = set(zipfile.ZipFile(whl).namelist())+ want = PROBE if made_probe else existing[0]+ assert f"codeverse/skills/{want}/SKILL.md" in names, sorted(n for n in names if "skills" in n)[:20]+ refs = [n for n in names if n.startswith(f"codeverse/skills/{want}/references/")]+ assert refs, "references/ must ship too — it is the depth probe"+ assert not any(n.endswith(".pyc") for n in names if "skills" in n)+ finally:+ if made_probe:+ shutil.rmtree(probe, ignore_errors=True)+ shutil.rmtree(HARNESS / "build", ignore_errors=True)+++def test_the_library_resolves_through_importlib_resources_not_just___file__():+ """An installed wheel has no source tree; ``skills_dir`` must still find the bundles."""+ from importlib.resources import files++ from codeverse.skills import skills_dir++ assert Path(str(files("codeverse.skills"))) == skills_dir()diff --git a/harness/tests/skills/test_registry.py b/harness/tests/skills/test_registry.pynew file mode 100644index 00000000..b439bf01--- /dev/null+++ b/harness/tests/skills/test_registry.py@@ -0,0 +1,107 @@+"""finding_kind() against real gate text, and the shape of the route table (T5).++The golden list in ``data/gate_findings.json`` was mined from 2,113 gate reports under+``bench/out``. It is the guard against the failure mode this classifier invites: a gate+message gets reworded, ``finding_kind`` quietly returns None, and repair rounds stop+getting the skill that answers them — with nothing failing anywhere.+"""++from __future__ import annotations++import json+from pathlib import Path++import pytest++from codeverse.skills.registry import ROUTED_SKILLS, ROUTES, Route, finding_kind, finding_kinds++DATA = Path(__file__).parent / "data" / "gate_findings.json"+GOLDEN = json.loads(DATA.read_text())["findings"]+++def test_the_golden_list_is_real_and_not_tiny():+ assert len(GOLDEN) >= 30+ assert {r["severity"] for r in GOLDEN} == {"warn", "error"}++[email protected]("row", GOLDEN, ids=[f"{r['gate']}:{r['kind']}:{i}" for i, r in enumerate(GOLDEN)])+def test_every_recorded_finding_classifies_to_its_expected_kind(row: dict):+ got = finding_kind(row["gate"], row["message"], row["severity"])+ assert got is not None, f"unknown: {row['gate']} / {row['message'][:90]}"+ assert got == row["kind"]+++def test_no_recorded_finding_is_unknown():+ unknown = [r for r in GOLDEN if finding_kind(r["gate"], r["message"], r["severity"]) is None]+ assert unknown == []+++def test_info_findings_are_census_not_defects():+ # "all 7 parts are connected" must not attach the interpenetration sheet+ assert finding_kind("connectivity", "all 7 parts are connected (9 contacts, gap <= 2 mm)", "info") is None+ assert finding_kind("contract", "all plan parts present and within tolerance", "info") is None+ 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"):+ self.gate, self.message, self.severity = gate, message, severity++ class R:+ def __init__(self, findings):+ self.findings = findings++ a = F("connectivity", "'A' and 'B' interpenetrate by 5.0 mm (3% of surface samples inside)")+ b = F("contract", "part 'Leg' bbox deviates from the plan (worst 2.2x tolerance)")+ assert finding_kinds([a, b]) == ["connectivity/interpenetration", "contract/part_bbox"]+ assert finding_kinds([R([a]), R([b])]) == ["connectivity/interpenetration", "contract/part_bbox"]+ assert finding_kinds([a, a]) == ["connectivity/interpenetration"] # distinct, in order+ assert finding_kinds([]) == [] and finding_kinds(None) == []+++# --------------------------------------------------------------------------- the table+def test_rule_ids_are_unique_and_the_design_numbers_are_all_present():+ ids = [r.rule for r in ROUTES]+ assert len(ids) == len(set(ids))+ for n in range(1, 24):+ assert any(r.rule == f"R{n}" for r in ROUTES), f"R{n} is missing from the table"+ assert [r for r in ROUTES if r.rule.startswith("R24")], "R24 (the graphics gate row) is missing"+++def test_gate_fired_rows_always_outrank_standing_rows():+ """Law 2: a repair round must spend its budget on what actually broke."""+ fired = [r for r in ROUTES if r.gate_fired]+ standing = [r for r in ROUTES if not r.gate_fired]+ assert min(r.priority for r in fired) > max(r.priority for r in standing)+ 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 in ROUTED_SKILLS+ assert r.skill.startswith("cv3d-")+++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))}+ families |= {"shader"} # shader_preflight rows exist in the fixture as source-derived+ for r in ROUTES:+ for pat in r.findings:+ assert pat.split("/", 1)[0] in families, f"{r.rule} routes on unknown family {pat!r}"+++def test_matches_finding_supports_exact_and_family_patterns():+ row = Route("X", "cv3d-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"+ assert row.matches_finding(["joint_sweep/disconnected"]) is None+ assert row.matches_finding([]) is Nonediff --git a/harness/tests/skills/test_router.py b/harness/tests/skills/test_router.pynew file mode 100644index 00000000..e7b92064--- /dev/null+++ b/harness/tests/skills/test_router.py@@ -0,0 +1,181 @@+"""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.+"""++from __future__ import annotations++from types import SimpleNamespace as NS++import pytest++from codeverse.conventions import LANGUAGE_FRAME+from codeverse.skills.model import EVIDENCE_INHERITED+from codeverse.skills.registry import QUIET_KINDS+from codeverse.skills.router import plan_signals, select, skills_for+from tests.skills.conftest import write_bundle++TRACK_OF = {+ "blender": "static_object", "cadquery": "static_object", "threejs": "static_object",+ "urdf_blender": "articulated_object", "scene_threejs": "scene",+ "glsl_shader": "graphics", "opengl_python": "graphics",+}+++def part(name="Leg", instances=1, symmetry="none", children=()):+ return NS(name=name, instances=instances, symmetry=symmetry, children=list(children))+++def static_plan(n=3, **kw):+ return NS(parts=[part(f"P{i}", **kw) for i in range(n)], summary="a chair", style_notes="")+++# --------------------------------------------------------------------------- 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"]+ assert not plan_signals(NS(summary="a wooden chair", parts=[part()]))["has_custom_shader"]+++# --------------------------------------------------------------------------- the laws+def test_every_track_language_pair_routes_at_least_one_skill_at_baseline(library):+ """Coverage is a test, not a hope (design §5.2 law 6)."""+ for language in LANGUAGE_FRAME:+ track = TRACK_OF[language]+ got = skills_for(track, language, "baseline", plan=static_plan(), library=library, allow_unverified=True)+ assert got, f"{track}/{language} routes nothing at baseline"+++def test_no_input_combination_exceeds_the_cap(library):+ every_finding = ["connectivity/interpenetration", "contract/part_bbox", "contract/instance_bbox",+ "joint_sweep/link_overlap", "motion_direction/wrong_axis", "scene_frames/dark_or_flat",+ "scene_frames/camera_placement", "gl_frames/motion_or_detail", "lint/part_not_imported",+ "shader/compile_or_binding"]+ kinds = ("baseline", "part", "detail", "refine", "repair", "rebuild", "rewrite", "env", "zone",+ "asset", "asset_fix", "compose", "reference")+ for language, track in TRACK_OF.items():+ for kind in kinds:+ for findings in ((), every_finding):+ got = select(track, language, kind, signals=plan_signals(static_plan(instances=2, symmetry="mirror_x")),+ findings=findings, library=library, max_skills=5, allow_unverified=True)+ assert len(got) <= 5, (track, language, kind, [s.name for s in got])+++def test_a_repair_round_spends_its_budget_on_what_broke(library):+ got = select("static_object", "blender", "repair",+ signals=plan_signals(static_plan()),+ findings=["connectivity/interpenetration", "contract/part_bbox"],+ library=library, max_skills=2)+ assert [s.name for s in got] == ["cv3d-part-contact", "cv3d-bbox-contract"]+ assert all(s.gate_fired for s in got)+ 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."""+ 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()),+ findings=["scene_frames/dark_or_flat"], library=library)+ assert [s.name for s in fired] == ["cv3d-scene-lighting"]+ # R2 is scoped to repair/refine/rebuild, so a connectivity finding does NOT+ # reopen an asset session+ assert select("static_object", "blender", kind, signals=plan_signals(static_plan()),+ findings=["connectivity/floating_part"], library=library) == []+++def test_inherited_unverified_bundles_are_off_until_the_switch_says_otherwise(library_dir):+ from codeverse.skills import all_skills++ write_bundle(library_dir, "cv3d-cadquery-forms", evidence=EVIDENCE_INHERITED)+ lib = all_skills(library_dir, strict=True)+ off = skills_for("static_object", "cadquery", "baseline", plan=static_plan(), library=lib)+ on = skills_for("static_object", "cadquery", "baseline", plan=static_plan(), library=lib, allow_unverified=True)+ assert "cv3d-cadquery-forms" not in [s.name for s in off]+ assert "cv3d-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 "cv3d-part-contact" not in [s.name for s in one]+ assert "cv3d-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 "cv3d-repeats-and-mirrors" not in [s.name for s in plain]+ assert "cv3d-repeats-and-mirrors" in [s.name for s in mirrored]+++def test_language_rows_do_not_leak_across_languages(library):+ blender = [s.name for s in skills_for("static_object", "blender", "baseline", plan=static_plan(), library=library)]+ assert "cv3d-blender-forms" in blender and "cv3d-cadquery-forms" not in blender+ graphics = [s.name for s in skills_for("graphics", "glsl_shader", "baseline", library=library)]+ assert graphics == ["cv3d-glsl-craft"]+++def test_scene_gate_findings_route_the_matching_scene_skill(library):+ for finding, want in (("scene_frames/dark_or_flat", "cv3d-scene-lighting"),+ ("scene_frames/camera_placement", "cv3d-scene-composition"),+ ("gl_frames/motion_or_detail", "cv3d-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_routing_is_deterministic_and_ordered_by_priority(library):+ args = dict(signals=plan_signals(static_plan(instances=2)), findings=["contract/instance_bbox"], library=library)+ runs = [[(s.name, s.priority) for s in select("static_object", "blender", "refine", **args)] for _ in range(5)]+ assert all(r == runs[0] for r in runs)+ assert [p for _, p in runs[0]] == sorted((p for _, p in runs[0]), reverse=True)+++def test_a_route_row_without_a_bundle_is_skipped_not_a_crash(library_dir):+ from codeverse.skills import all_skills++ (library_dir / "cv3d-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 "cv3d-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["cv3d-part-contact"].rules == ("R1",)+ assert by_name["cv3d-part-contact"].reason.startswith("R1: ")+ assert not by_name["cv3d-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_telemetry.py b/harness/tests/skills/test_telemetry.pynew file mode 100644index 00000000..f05e30f8--- /dev/null+++ b/harness/tests/skills/test_telemetry.py@@ -0,0 +1,151 @@+"""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, a bundle with no references cannot+be probed for depth and says so, and api-agent's exact log wins over the probe.+"""++from __future__ import annotations++import json+import os+from pathlib import Path++import pytest++from codeverse.skills.materialize import attach_skills+from codeverse.skills.telemetry import (+ READS_FILE,+ SKILLS_FILE,+ TELEMETRY_DIR,+ append_usage,+ deep_read_rate,+ is_skill_path,+ probe_reads,+ record_exact_read,+)+from tests.skills.conftest import write_bundle+++def ws(tmp_path: Path) -> Path:+ root = tmp_path / "ws"+ root.mkdir()+ (root / "AGENTS.md").write_text("# body\n")+ 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",+ agent_kind="api-agent", plan=_plan(), library=library,+ max_skills=5, allow_unverified=False, **kw)+++def _touch_read(path: Path) -> None:+ """Simulate a reader on a filesystem whose atime we cannot rely on in a test."""+ st = os.stat(path)+ 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):+ got = _attach(ws, library)+ name = got.listed[0]+ _touch_read(ws / ".agents" / "skills" / name / "references" / "worked_example.md")+ usage = 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]+++def test_a_bundle_with_no_references_says_depth_is_unmeasurable(tmp_path, ws):+ from codeverse.skills import all_skills++ lib_dir = tmp_path / "lib"+ write_bundle(lib_dir, "cv3d-part-contact", references={})+ got = _attach(ws, all_skills(lib_dir, strict=True))+ read = probe_reads(ws, got).reads[0]+ assert read.deep_measurable is False and read.deep is False+++def test_api_agent_exact_reads_override_the_probe_and_carry_the_turn(ws, library):+ got = _attach(ws, library)+ name = got.listed[0]+ record_exact_read(ws, f".agents/skills/{name}/SKILL.md", turn=3, label="baseline")+ record_exact_read(ws, f".agents/skills/{name}/references/worked_example.md", turn=5, label="baseline")+ record_exact_read(ws, "src/model.py", turn=1) # not a skill: ignored+ usage = probe_reads(ws, got)+ row = next(r for r in usage.reads if r.name == name)+ assert row.surfaced and row.deep and row.first_seen_turn == 3+ lines = (ws / TELEMETRY_DIR / READS_FILE).read_text().splitlines()+ assert len(lines) == 2 and json.loads(lines[0])["skill"] == name+++def test_is_skill_path_recognises_both_roots_and_nothing_else():+ assert is_skill_path(".agents/skills/cv3d-x/SKILL.md") == "cv3d-x"+ assert is_skill_path(".claude/skills/cv3d-x/references/a.md") == "cv3d-x"+ assert is_skill_path("./.agents/skills/cv3d-x/SKILL.md") == "cv3d-x"+ assert is_skill_path("src/model.py") == ""+ assert is_skill_path(".agents/settings.json") == ""+++def test_a_damaged_reads_file_does_not_break_the_probe(ws, library):+ got = _attach(ws, library)+ (ws / TELEMETRY_DIR).mkdir(exist_ok=True)+ (ws / TELEMETRY_DIR / READS_FILE).write_text("not json\n{}\n")+ assert probe_reads(ws, got).surfaced == []+++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="api-agent:gemini-3.7-flash")+ append_usage(ws, usage, round=1, kind="refine", agent="api-agent:gemini-3.7-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_deep_read_rate_aggregates_across_sessions(ws, library):+ got = _attach(ws, library)+ a = probe_reads(ws, got)+ _touch_read(ws / ".agents" / "skills" / got.listed[0] / "references" / "worked_example.md")+ b = probe_reads(ws, got)+ rates = deep_read_rate([a, b])+ assert rates[got.listed[0]] == (1, 2)+ assert rates[got.listed[1]] == (0, 2)+++def test_telemetry_never_raises_into_a_run(tmp_path):+ from codeverse.skills.model import SkillsMaterialized++ record_exact_read(tmp_path / "does" / "not" / "exist", ".agents/skills/x/SKILL.md", turn=1)+ assert append_usage(tmp_path / "nope" / "nope", probe_reads(tmp_path, SkillsMaterialized())) is None or True