Official Codebase of 3DCodeVerse
Python
skills: twelve modules become seven; the table and its evaluator share a file
gaoypeng27eaa89f2814
diff --git a/harness/codeverse/cli/skills_cmd.py b/harness/codeverse/cli/skills_cmd.pyindex c6cad7f2..12d76e48 100644--- a/harness/codeverse/cli/skills_cmd.py+++ b/harness/codeverse/cli/skills_cmd.py@@ -67,7 +67,7 @@ def list_skills(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+ from codeverse.skills.model import SkillErrortry:s = load_skill(name)@@ -86,9 +86,9 @@ def validate() -> 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.model import SkillError, parse_skillfrom codeverse.skills.registry import ROUTED_SKILLS+ from codeverse.skills.targets import check_claimsdirs = bundle_dirs()bad = 0diff --git a/harness/codeverse/skills/__init__.py b/harness/codeverse/skills/__init__.pyindex c594b380..cf9f572b 100644--- a/harness/codeverse/skills/__init__.py+++ b/harness/codeverse/skills/__init__.py@@ -27,8 +27,14 @@ import osfrom collections.abc import Iteratorfrom pathlib import Path-from codeverse.skills.loader import SKILL_FILE, SkillError, parse_skill, validate_bundle-from codeverse.skills.model import Skill, SkillRef+from codeverse.skills.model import (+ SKILL_FILE,+ Skill,+ SkillError,+ SkillRef,+ parse_skill,+ validate_bundle,+)log = logging.getLogger(__name__)@@ -98,10 +104,10 @@ 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: E402from codeverse.skills.config import skills_enabled, skills_max, skills_unverified # noqa: E402from 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.registry import plan_signals, select, skills_for # noqa: E402+from codeverse.skills.targets import check_claims, claim_values # noqa: E402from codeverse.skills.telemetry import probe_reads # noqa: E402__all__ = ["SKILLS_DIR_ENV", "Skill", "SkillError", "SkillRef", "all_skills", "attach_skills", "bundle_dirs",diff --git a/harness/codeverse/skills/claims.py b/harness/codeverse/skills/claims.pydeleted file mode 100644index 1b561a67..00000000--- a/harness/codeverse/skills/claims.py+++ /dev/null@@ -1,123 +0,0 @@-"""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-import tomllib-from pathlib import Path-from typing import Any--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 — the rendered string, in that bundle's own units."""- return {str(r["key"]): str(r.get("text", "")) for r in load_claims(name, root) if r.get("key")}---def claim_bases(name: str, root: Path | None = None) -> dict[str, tuple[str, Any]]:- """``key -> (dotted target, live value)`` — the agreement test's real comparison.-- WHY not the rendered text: two skills may honestly quote one constant in two units.- ``cv3d-bbox-contract`` says "1 cm" (scale 100) and ``cv3d-repeats-and-mirrors`` says- "0.01" metres; both pin ``conventions:BBOX_TOLERANCE_M`` and both are right. A- contradiction is two skills pointing a shared key at DIFFERENT numbers, so that is what- is compared — the pre-scale value, and the target it came from.- """- out: dict[str, tuple[str, Any]] = {}- for row in load_claims(name, root):- key = row.get("key")- if not key or not row.get("python"):- continue- out[str(key)] = (str(row["python"]), resolve(str(row["python"])))- return out---__all__ = ["CLAIMS_DIR", "check_claims", "claim_bases", "claim_values", "claims_path", "load_claims",- "render_claim", "resolve"]diff --git a/harness/codeverse/skills/delivery.py b/harness/codeverse/skills/delivery.pydeleted file mode 100644index f107b236..00000000--- a/harness/codeverse/skills/delivery.py+++ /dev/null@@ -1,75 +0,0 @@-"""How one shared skill library reaches each coding agent — the ONE place that differs.--The library itself is agent-agnostic: plain `agentskills.io` bundles under-``codeverse/skills/<name>/SKILL.md``, routed by ``router.py`` from typed inputs. Nothing-in it knows what a backend is. What genuinely differs between backends is only-**delivery**, and only in two bits:--* does the backend have a NATIVE skill loader (it finds and indexes bundles itself), and-* which discovery root does it read?--Both were read out of the shipped binaries, not assumed: gemini-cli, codex and agy read-``<ws>/.agents/skills/<name>/SKILL.md``; claude-code 2.1 reads ``<ws>/.claude/skills/…``-and has no ``.agents`` skill root at all.--Everything else follows from those two bits, so adding a backend is ONE row here — not a-new module, not a branch in three files. A backend nobody has classified gets the safe-answer (no native loader), which means it is handed the explicit index *and* the-``read_skill`` tool: over-delivering costs tokens, under-delivering costs the skill.--WHY the tool exists at all, measured 2026-08-25: on the same library and workspace, the-three native loaders read **5 of 5** routed bundles unprompted while api-agent read-**0 of 5** — not from unwillingness (it made 52 ``read_file`` calls that session) but-because the bundles sit in hidden directories its ``list_files`` skips, and the index was-prose in a 2.3 kB system prompt rather than an affordance. So a backend without a loader-gets the routed set as a TOOL. That is a general rule about loaderless backends, not a-special case for one of them.-"""--from __future__ import annotations--from dataclasses import dataclass--__all__ = ["AGENTS_SKILL_ROOT", "CLAUDE_SKILL_ROOT", "Delivery", "delivery_for", "known_backends"]--#: discovery roots, relative to the workspace root-AGENTS_SKILL_ROOT = ".agents/skills"-CLAUDE_SKILL_ROOT = ".claude/skills"---@dataclass(frozen=True)-class Delivery:- """What one backend needs in order to see the routed bundles."""-- root: str- """Discovery root this backend reads (bundles are written to every known root anyway,- so one copy is never the only copy — this is the path we NAME to it)."""- native_loader: bool- """True when the backend indexes bundles itself. Such a backend must not be handed a- second index — it would list the same skills twice — and needs no tool."""-- @property- def needs_index(self) -> bool:- """An explicit one-line-per-skill index in the agent body file."""- return not self.native_loader---#: The whole per-backend policy. One row per backend; anything absent is loaderless.-_BACKENDS: dict[str, Delivery] = {- "claude-code": Delivery(root=CLAUDE_SKILL_ROOT, native_loader=True),- "codex": Delivery(root=AGENTS_SKILL_ROOT, native_loader=True),- "gemini-cli": Delivery(root=AGENTS_SKILL_ROOT, native_loader=True),- "agy": Delivery(root=AGENTS_SKILL_ROOT, native_loader=True),-}--#: the safe answer for a backend nobody has classified yet-_UNKNOWN = Delivery(root=AGENTS_SKILL_ROOT, native_loader=False)---def delivery_for(agent_kind: str) -> Delivery:- """The delivery policy for ``agent_kind``; unknown kinds get the loaderless answer."""- return _BACKENDS.get((agent_kind or "").split(":", 1)[0], _UNKNOWN)---def known_backends() -> tuple[str, ...]:- return tuple(_BACKENDS)diff --git a/harness/codeverse/skills/loader.py b/harness/codeverse/skills/loader.pydeleted file mode 100644index 45b2363c..00000000--- a/harness/codeverse/skills/loader.py+++ /dev/null@@ -1,190 +0,0 @@-"""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 nonstring_metadata(fm: dict) -> list[str]:- """metadata values YAML did not hand back as strings.-- An unquoted ``verified: 2026-08-25`` is a YAML *date*, not a string, and the spec says- metadata is string to string. ``_as_str_map`` coerces so a run never dies of it; the- validator reports it so a bundle is not shipped depending on our leniency.- """- meta = fm.get("metadata")- if not isinstance(meta, dict):- return []- return [f"metadata.{k} is a {type(v).__name__}, not a string — quote it (the spec allows string→string)"- for k, v in meta.items() if not isinstance(v, str) and v is not None]---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")- try:- fm_text, _ = split_frontmatter((bundle / SKILL_FILE).read_text(encoding="utf-8"))- issues += nonstring_metadata(yaml.safe_load(fm_text) or {})- except (OSError, SkillError, yaml.YAMLError): # already reported by parse_skill above- pass- 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", "nonstring_metadata", "parse_skill",- "split_frontmatter", "validate_bundle"]diff --git a/harness/codeverse/skills/materialize.py b/harness/codeverse/skills/materialize.pyindex 70bd7418..c54c2a4d 100644--- a/harness/codeverse/skills/materialize.py+++ b/harness/codeverse/skills/materialize.py@@ -48,7 +48,7 @@ from codeverse.skills.prompting import (index_tokens,inline_body,)-from codeverse.skills.router import plan_signals, select+from codeverse.skills.registry import plan_signals, selectlog = logging.getLogger(__name__)diff --git a/harness/codeverse/skills/model.py b/harness/codeverse/skills/model.pyindex 3cebcac6..7db64445 100644--- a/harness/codeverse/skills/model.py+++ b/harness/codeverse/skills/model.py@@ -8,11 +8,13 @@ telemetry in §6.4 of the design would be measuring a file nobody sent.from __future__ import annotations+import logging+import refrom pathlib import Path+import yamlfrom pydantic import BaseModel, Field-from codeverse.contracts.skills import SkillRead, SkillsUsagefrom codeverse.cost.guard import text_tokens#: `metadata.evidence` values. A bundle whose claims are carried over from a reference@@ -115,5 +117,159 @@ class SkillsMaterialized(BaseModel):warnings: list[str] = Field(default_factory=list)-__all__ = ["EVIDENCE_INHERITED", "EVIDENCE_LEVELS", "EVIDENCE_MEASURED", "EVIDENCE_MIXED",- "Selection", "Skill", "SkillRead", "SkillRef", "SkillsMaterialized", "SkillsUsage"]+# ===================================================================== loader+# (merged from codeverse/skills/loader.py, 2026-08-28)+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 nonstring_metadata(fm: dict) -> list[str]:+ """metadata values YAML did not hand back as strings.++ An unquoted ``verified: 2026-08-25`` is a YAML *date*, not a string, and the spec says+ metadata is string to string. ``_as_str_map`` coerces so a run never dies of it; the+ validator reports it so a bundle is not shipped depending on our leniency.+ """+ meta = fm.get("metadata")+ if not isinstance(meta, dict):+ return []+ return [f"metadata.{k} is a {type(v).__name__}, not a string — quote it (the spec allows string→string)"+ for k, v in meta.items() if not isinstance(v, str) and v is not None]+++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")+ try:+ fm_text, _ = split_frontmatter((bundle / SKILL_FILE).read_text(encoding="utf-8"))+ issues += nonstring_metadata(yaml.safe_load(fm_text) or {})+ except (OSError, SkillError, yaml.YAMLError): # already reported by parse_skill above+ pass+ 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 issuesdiff --git a/harness/codeverse/skills/prompting.py b/harness/codeverse/skills/prompting.pyindex bd3e4072..c7556d04 100644--- a/harness/codeverse/skills/prompting.py+++ b/harness/codeverse/skills/prompting.py@@ -1,39 +1,87 @@-"""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).-* a backend nobody has classified yet (``delivery.py``'s safe answer) gets a- one-line-per-skill index inside the AGENTS.md body, which is already message 0.-* 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.+"""How one shared skill library reaches each coding agent — the ONE place that differs.++The library itself is agent-agnostic: plain `agentskills.io` bundles under+``codeverse/skills/<name>/SKILL.md``, routed by ``router.py`` from typed inputs. Nothing+in it knows what a backend is. What genuinely differs between backends is only+**delivery**, and only in two bits:++* does the backend have a NATIVE skill loader (it finds and indexes bundles itself), and+* which discovery root does it read?++Both were read out of the shipped binaries, not assumed: gemini-cli, codex and agy read+``<ws>/.agents/skills/<name>/SKILL.md``; claude-code 2.1 reads ``<ws>/.claude/skills/…``+and has no ``.agents`` skill root at all.++Everything else follows from those two bits, so adding a backend is ONE row here — not a+new module, not a branch in three files. A backend nobody has classified gets the safe+answer (no native loader), which means it is handed the explicit index *and* the+``read_skill`` tool: over-delivering costs tokens, under-delivering costs the skill.++WHY the tool exists at all, measured 2026-08-25: on the same library and workspace, the+three native loaders read **5 of 5** routed bundles unprompted while api-agent read+**0 of 5** — not from unwillingness (it made 52 ``read_file`` calls that session) but+because the bundles sit in hidden directories its ``list_files`` skips, and the index was+prose in a 2.3 kB system prompt rather than an affordance. So a backend without a loader+gets the routed set as a TOOL. That is a general rule about loaderless backends, not a+special case for one of them."""from __future__ import annotationsimport refrom collections.abc import Sequence+from dataclasses import dataclassfrom codeverse.cost.guard import text_tokens-from codeverse.skills.delivery import (- AGENTS_SKILL_ROOT,- CLAUDE_SKILL_ROOT,- delivery_for,- known_backends,-)from codeverse.skills.model import Selection, Skill+__all__ = ["AGENTS_SKILL_ROOT", "CLAUDE_SKILL_ROOT", "Delivery", "delivery_for", "known_backends"]++#: discovery roots, relative to the workspace root+AGENTS_SKILL_ROOT = ".agents/skills"+CLAUDE_SKILL_ROOT = ".claude/skills"+++@dataclass(frozen=True)+class Delivery:+ """What one backend needs in order to see the routed bundles."""++ root: str+ """Discovery root this backend reads (bundles are written to every known root anyway,+ so one copy is never the only copy — this is the path we NAME to it)."""+ native_loader: bool+ """True when the backend indexes bundles itself. Such a backend must not be handed a+ second index — it would list the same skills twice — and needs no tool."""++ @property+ def needs_index(self) -> bool:+ """An explicit one-line-per-skill index in the agent body file."""+ return not self.native_loader+++#: The whole per-backend policy. One row per backend; anything absent is loaderless.+_BACKENDS: dict[str, Delivery] = {+ "claude-code": Delivery(root=CLAUDE_SKILL_ROOT, native_loader=True),+ "codex": Delivery(root=AGENTS_SKILL_ROOT, native_loader=True),+ "gemini-cli": Delivery(root=AGENTS_SKILL_ROOT, native_loader=True),+ "agy": Delivery(root=AGENTS_SKILL_ROOT, native_loader=True),+}++#: the safe answer for a backend nobody has classified yet+_UNKNOWN = Delivery(root=AGENTS_SKILL_ROOT, native_loader=False)+++def delivery_for(agent_kind: str) -> Delivery:+ """The delivery policy for ``agent_kind``; unknown kinds get the loaderless answer."""+ return _BACKENDS.get((agent_kind or "").split(":", 1)[0], _UNKNOWN)+++def known_backends() -> tuple[str, ...]:+ return tuple(_BACKENDS)+++# ===================================================================== prompting+# (merged from codeverse/skills/prompting.py, 2026-08-28)#: Per-backend policy lives in ONE place (``skills/delivery.py``); these are re-exported so#: existing importers keep working and so nothing here re-derives what a backend needs.NATIVE_LOADERS = tuple(k for k in known_backends() if delivery_for(k).native_loader)@@ -126,8 +174,3 @@ def inline_body(selections: Sequence[Selection], *, max_tokens: int = 2500) -> tif 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", "INDEX_SUMMARY_CHARS", "MANDATE", "MANDATE_ROUTED",- "NATIVE_LOADERS", "index_block", "index_summary", "index_tokens", "inline_body",- "repair_pointers", "skill_path"]diff --git a/harness/codeverse/skills/registry.py b/harness/codeverse/skills/registry.pyindex d4052184..5999e33e 100644--- a/harness/codeverse/skills/registry.py+++ b/harness/codeverse/skills/registry.py@@ -20,8 +20,12 @@ corpus; routing one is a claim that a skill helps, and that claim needs evidencefrom __future__ import annotations+import loggingimport refrom dataclasses import dataclass+from typing import Any++from codeverse.skills.model import EVIDENCE_INHERITED, Selection, Skill# --------------------------------------------------------------------------- finding kindsCONNECTIVITY_INTERPENETRATION = "connectivity/interpenetration"@@ -237,12 +241,131 @@ ROUTES: tuple[Route, ...] = (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"]+# ===================================================================== router+# (merged from codeverse/skills/router.py, 2026-08-28)+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]diff --git a/harness/codeverse/skills/router.py b/harness/codeverse/skills/router.pydeleted file mode 100644index 79ed5dfa..00000000--- a/harness/codeverse/skills/router.py+++ /dev/null@@ -1,151 +0,0 @@-"""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/targets.py b/harness/codeverse/skills/targets.pyindex 5ad1075e..107a5555 100644--- a/harness/codeverse/skills/targets.py+++ b/harness/codeverse/skills/targets.py@@ -26,7 +26,13 @@ rows against the live gate vocabulary and against each bundle's own frontmatter.from __future__ import annotations+import importlib+import tomllibfrom dataclasses import dataclass, field+from pathlib import Path+from typing import Any++from codeverse.skills.model import Skill#: the direction that counts as an improvementDOWN = "down"@@ -249,6 +255,92 @@ def gate_kinds_claimed() -> frozenset[str]:return frozenset(k for t in TARGETS for k in t.kinds)-__all__ = ["BY_SKILL", "DIRECTIONS", "DOWN", "METRICS", "SOURCES", "SRC_ARTIFACT", "SRC_BUILD",- "SRC_FRAMES", "SRC_GATE", "SRC_GLB", "TARGETS", "UP", "Target", "gate_kinds_claimed",- "target_for"]+# ===================================================================== claims+# (merged from codeverse/skills/claims.py, 2026-08-28)+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 key_name in ("key", "text", "python"):+ if not row.get(key_name):+ issues.append(f"{where}: missing `{key_name}`")+ 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 — the rendered string, in that bundle's own units."""+ return {str(r["key"]): str(r.get("text", "")) for r in load_claims(name, root) if r.get("key")}+++def claim_bases(name: str, root: Path | None = None) -> dict[str, tuple[str, Any]]:+ """``key -> (dotted target, live value)`` — the agreement test's real comparison.++ WHY not the rendered text: two skills may honestly quote one constant in two units.+ ``cv3d-bbox-contract`` says "1 cm" (scale 100) and ``cv3d-repeats-and-mirrors`` says+ "0.01" metres; both pin ``conventions:BBOX_TOLERANCE_M`` and both are right. A+ contradiction is two skills pointing a shared key at DIFFERENT numbers, so that is what+ is compared — the pre-scale value, and the target it came from.+ """+ out: dict[str, tuple[str, Any]] = {}+ for row in load_claims(name, root):+ key = row.get("key")+ if not key or not row.get("python"):+ continue+ out[str(key)] = (str(row["python"]), resolve(str(row["python"])))+ return outdiff --git a/harness/codeverse/skills/telemetry.py b/harness/codeverse/skills/telemetry.pyindex 2670f704..36cd27bb 100644--- a/harness/codeverse/skills/telemetry.py+++ b/harness/codeverse/skills/telemetry.py@@ -38,7 +38,8 @@ from collections.abc import Sequencefrom pathlib import Pathfrom typing import Any-from codeverse.skills.model import SkillRead, SkillsMaterialized, SkillsUsage+from codeverse.contracts.skills import SkillRead, SkillsUsage+from codeverse.skills.model import SkillsMaterializedfrom codeverse.skills.prompting import AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOTlog = logging.getLogger(__name__)diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.pyindex a424b6b9..1ebf01de 100644--- a/harness/codeverse/tracks/plan_features.py+++ b/harness/codeverse/tracks/plan_features.py@@ -64,7 +64,7 @@ LIVE_SWITCHES: dict[str, str] = {"CV3D_PLAN_BRIEF": "codeverse/tracks/planner.py", # brief.py merged in, 2026-08-28"CV3D_SCOPED_PARTS": "codeverse/tracks/depth.py","CV3D_DETAIL_ROUNDS": "codeverse/tracks/lifecycle.py",- "CV3D_REFERENCE_DIFF": "codeverse/judges/reference.py",+ "CV3D_REFERENCE_DIFF": "codeverse/judges/vlm_judge.py", # reference.py merged in, 2026-08-28# 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",diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex 0969150a..a810fe6f 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -120,18 +120,11 @@ 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), delivery.py (THE per-backend policy, two- bits — native loader? which root? — so a new backend is one row and nothing- else re-derives it), 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)+ skills/ registry.py (typed ROUTES + the router that evaluates them),+ model.py (Skill/Selection + the SKILL.md loader), prompting.py+ (per-backend delivery policy + the index/mandate text),+ targets.py (measured targets + claims), materialize.py,+ telemetry.py (the read probe), config.py (call-time switches)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 backenddiff --git a/harness/tests/skills/test_budget.py b/harness/tests/skills/test_budget.pyindex ac84a681..a6c10e19 100644--- a/harness/tests/skills/test_budget.py+++ b/harness/tests/skills/test_budget.py@@ -19,7 +19,7 @@ import itertoolsimport pytestfrom codeverse.skills import all_skills, bundle_dirs, select, skills_dir-from codeverse.skills.loader import BODY_MAX_TOKENS+from codeverse.skills.model import BODY_MAX_TOKENSfrom codeverse.skills.prompting import NATIVE_LOADERS, index_block, index_tokenspytestmark = pytest.mark.skipif(not bundle_dirs(), reason=f"no bundles in {skills_dir()} yet")diff --git a/harness/tests/skills/test_delivery.py b/harness/tests/skills/test_delivery.pyindex d6eab11c..52bc384d 100644--- a/harness/tests/skills/test_delivery.py+++ b/harness/tests/skills/test_delivery.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport pytest-from codeverse.skills.delivery import (+from codeverse.skills.prompting import (AGENTS_SKILL_ROOT,CLAUDE_SKILL_ROOT,delivery_for,diff --git a/harness/tests/skills/test_freshness.py b/harness/tests/skills/test_freshness.pyindex b6cce52f..a1d4e887 100644--- a/harness/tests/skills/test_freshness.py+++ b/harness/tests/skills/test_freshness.py@@ -238,7 +238,7 @@ def test_a_constant_a_body_names_is_also_pinned_by_a_claim(s):sentence with the old value and no test to notice. Found `DUPLICATE_DIFF` quoted at1e-4 in cv3d-glsl-craft with no row behind it."""- from codeverse.skills.claims import load_claims+ from codeverse.skills.targets import load_claimspinned = {str(r["python"]).rsplit(":", 1)[-1] for r in load_claims(s.name) if r.get("python")}named = {c for c in _CONST.findall(_prose(s.body)) if c in LIVE_CONSTANTS}diff --git a/harness/tests/skills/test_library.py b/harness/tests/skills/test_library.pyindex e6f4aeb6..2e4e59f7 100644--- a/harness/tests/skills/test_library.py+++ b/harness/tests/skills/test_library.py@@ -16,9 +16,9 @@ from pathlib import Pathimport pytestfrom codeverse.skills import bundle_dirs, iter_skills, skills_dir, validate_bundle-from codeverse.skills.claims import check_claims, claim_bases, load_claims-from codeverse.skills.loader import BODY_MAX_LINES, BODY_MAX_TOKENS+from codeverse.skills.model import BODY_MAX_LINES, BODY_MAX_TOKENSfrom codeverse.skills.registry import ROUTED_SKILLS, ROUTES+from codeverse.skills.targets import check_claims, claim_bases, load_claimsBUNDLES = bundle_dirs()SKILLS = list(iter_skills()) if BUNDLES else []diff --git a/harness/tests/skills/test_loader.py b/harness/tests/skills/test_loader.pyindex cfbf9004..c7425205 100644--- a/harness/tests/skills/test_loader.py+++ b/harness/tests/skills/test_loader.py@@ -7,7 +7,7 @@ from pathlib import Pathimport pytestfrom codeverse.skills import all_skills, bundle_dirs, iter_skills, load_skill-from codeverse.skills.loader import (+from codeverse.skills.model import (BODY_MAX_LINES,SkillError,parse_skill,diff --git a/harness/tests/skills/test_materialize_prompting.py b/harness/tests/skills/test_materialize_prompting.pyindex a7099d56..f0889435 100644--- a/harness/tests/skills/test_materialize_prompting.py+++ b/harness/tests/skills/test_materialize_prompting.py@@ -30,7 +30,7 @@ from codeverse.skills.prompting import (inline_body,repair_pointers,)-from codeverse.skills.router import select+from codeverse.skills.registry import select@pytest.fixturediff --git a/harness/tests/skills/test_router.py b/harness/tests/skills/test_router.pyindex e7b92064..6aa6ab19 100644--- a/harness/tests/skills/test_router.py+++ b/harness/tests/skills/test_router.py@@ -12,8 +12,7 @@ import pytestfrom codeverse.conventions import LANGUAGE_FRAMEfrom codeverse.skills.model import EVIDENCE_INHERITED-from codeverse.skills.registry import QUIET_KINDS-from codeverse.skills.router import plan_signals, select, skills_for+from codeverse.skills.registry import QUIET_KINDS, plan_signals, select, skills_forfrom tests.skills.conftest import write_bundleTRACK_OF = {diff --git a/harness/tests/skills/test_routing_property.py b/harness/tests/skills/test_routing_property.pyindex 7abb8833..a49cd393 100644--- a/harness/tests/skills/test_routing_property.py+++ b/harness/tests/skills/test_routing_property.py@@ -25,8 +25,7 @@ import pytestfrom codeverse.skills import all_skills, bundle_dirs, select, skills_dirfrom codeverse.skills.model import EVIDENCE_INHERITED-from codeverse.skills.registry import QUIET_KINDS, ROUTED_SKILLS, ROUTES-from codeverse.skills.router import SIGNAL_KEYS+from codeverse.skills.registry import QUIET_KINDS, ROUTED_SKILLS, ROUTES, SIGNAL_KEYSpytestmark = pytest.mark.skipif(not bundle_dirs(), reason=f"no bundles in {skills_dir()} yet")diff --git a/harness/tests/skills/test_spec_compliance.py b/harness/tests/skills/test_spec_compliance.pyindex 609ccc23..f267a494 100644--- a/harness/tests/skills/test_spec_compliance.py+++ b/harness/tests/skills/test_spec_compliance.py@@ -135,7 +135,7 @@ def test_the_reference_implementation_validates_the_bundle(d: Path):def test_our_loader_and_the_reference_implementation_read_the_same_fields(d: Path):"""A disagreement here is the failure mode that matters: we index one description,the CLI indexes another, and the read rate measures a skill nobody was offered."""- from codeverse.skills.loader import parse_skill+ from codeverse.skills.model import parse_skillp = subprocess.run([REF_VALIDATOR, "read-properties", str(d)],capture_output=True, text=True, check=False)