Skip to content

Official Codebase of 3DCodeVerse

Python

gates: every finding the skills route on carries its kind — R9 answers a part never imported, R13 a joint moving against the plan

gaoypeng8be58663c636
diff --git a/harness/codeverse3d/addons/skill_targets.py b/harness/codeverse3d/addons/skill_targets.py
index 682bcd4a..ad6387c9 100644
--- a/harness/codeverse3d/addons/skill_targets.py
+++ b/harness/codeverse3d/addons/skill_targets.py
@@ -117,7 +117,7 @@ TARGETS: tuple[Target, ...] = (
direction=DOWN,
unit="findings per run",
source=SRC_GATE,
- kinds=("lint/untyped",),
+ kinds=("lint/*",),
languages=("blender", "urdf_blender"),
why="the bundle is written around the five bpy traps the static lint already counts",
),
diff --git a/harness/codeverse3d/contracts/artifacts.py b/harness/codeverse3d/contracts/artifacts.py
index 8bc1dc72..59119c24 100644
--- a/harness/codeverse3d/contracts/artifacts.py
+++ b/harness/codeverse3d/contracts/artifacts.py
@@ -18,6 +18,31 @@ class Severity(StrEnum):
INFO = "info"
+class LintKind(StrEnum):
+ """``data.kind`` of a ``lint:<language>`` finding — what routes a skill (``skills.registry``)
+ and what a cap rule's ``kinds`` are matched against. One vocabulary for every lint."""
+
+ SYNTAX = "syntax" # the file does not parse
+ MISSING_FILE = "missing_file" # an entry / planned part file is absent
+ FORBIDDEN_IMPORT = "forbidden_import" # an import the sandbox forbids
+ BAD_IMPORT = "bad_import" # an import that cannot resolve here (package, URL, escape, missing)
+ SANDBOX = "sandbox" # file IO, network, subprocess, DOM, eval, exiting the process
+ HARNESS_OWNED = "harness_owned" # camera, light, world, renderer, render loop, export
+ API_TRAP = "api_trap" # a removed / renamed / context-dependent API
+ UNDEFINED_NAME = "undefined_name" # a name used and never imported
+ NAMING = "naming" # object / link / file naming
+ LAYOUT = "layout" # module exports and the multi-file layout
+ PART_NOT_IMPORTED = "part_not_imported" # a part file nothing imports, so its part is never built
+ LINK_NAME = "link_name" # a URDF link no object in model.py is named after
+ URDF_STRUCTURE = "urdf_structure" # the XML, the root, the link/joint tree
+ URDF_LINK = "urdf_link" # a link's visual / collision / mesh
+ URDF_JOINT = "urdf_joint" # a joint's type, parent/child, axis, limits
+ MIMIC = "mimic" # a <mimic> coupling
+ HANG_RISK = "hang_risk" # a loop / call that can stall a headless build
+ NONDETERMINISM = "nondeterminism" # an unseeded random source
+ CENSUS = "census" # INFO: what the lint saw
+
+
class GateFinding(BaseModel):
gate: str
severity: Severity
diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.py
index e3a5e31a..0b3ae162 100644
--- a/harness/codeverse3d/languages/blender/__init__.py
+++ b/harness/codeverse3d/languages/blender/__init__.py
@@ -9,7 +9,7 @@ import time
from pathlib import Path
from codeverse3d.config import Settings, get_settings
-from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, LintKind, Severity
from codeverse3d.contracts.common import ENTRY_FILE, Language
from codeverse3d.contracts.plan import BBox, PartPlan, Plan, StaticPlan
from codeverse3d.conventions import GROUND_TOL_M, PASCAL_RE, fmt3, to_pascal, to_snake
@@ -53,15 +53,15 @@ FORBIDDEN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
("urllib.", "no network"), ("requests.", "no network"),
("shutil.", "no file IO"),
)
-WARN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
- ("bpy.data.cameras.new", "the harness owns cameras; remove camera creation"),
- ("bpy.ops.object.camera_add", "the harness owns cameras; remove camera creation"),
- ("bpy.data.lights.new", "the harness owns lighting; remove light creation"),
- ("bpy.ops.object.light_add", "the harness owns lighting; remove light creation"),
- ("bpy.data.worlds.new", "the harness owns the world/background; remove world code"),
- ("bpy.ops.view3d.", "view3d operators fail in background mode (no 3D viewport)"),
- ("bpy.ops.screen.", "screen operators fail in background mode"),
- ("sys.exit", "do not exit; let the script fall off the end"),
+WARN_CALL_PREFIXES: tuple[tuple[str, str, LintKind], ...] = (
+ ("bpy.data.cameras.new", "the harness owns cameras; remove camera creation", LintKind.HARNESS_OWNED),
+ ("bpy.ops.object.camera_add", "the harness owns cameras; remove camera creation", LintKind.HARNESS_OWNED),
+ ("bpy.data.lights.new", "the harness owns lighting; remove light creation", LintKind.HARNESS_OWNED),
+ ("bpy.ops.object.light_add", "the harness owns lighting; remove light creation", LintKind.HARNESS_OWNED),
+ ("bpy.data.worlds.new", "the harness owns the world/background; remove world code", LintKind.HARNESS_OWNED),
+ ("bpy.ops.view3d.", "view3d operators fail in background mode (no 3D viewport)", LintKind.API_TRAP),
+ ("bpy.ops.screen.", "screen operators fail in background mode", LintKind.API_TRAP),
+ ("sys.exit", "do not exit; let the script fall off the end", LintKind.SANDBOX),
)
# Principled BSDF inputs that raise KeyError in Blender 4.x/5.x → their replacement.
# Verified against Blender 5.0.1: 'Anisotropic' and 'Specular Tint' STILL EXIST (do not list them).
@@ -199,8 +199,11 @@ class _Collector(ast.NodeVisitor):
self.constants.append((node.value, node.lineno))
-def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target: str = "src/model.py") -> GateFinding:
- data = {"line": line} if line else {}
+def _f(kind: LintKind, sev: Severity, msg: str, line: int | None = None, hint: str = "",
+ target: str = "src/model.py") -> GateFinding:
+ data: dict[str, object] = {"kind": kind.value}
+ if line:
+ data["line"] = line
return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=data)
@@ -208,89 +211,89 @@ def _rules(c: _Collector, source: str, *, target: str, expect_names: bool, expec
out: list[GateFinding] = []
E, W, I = Severity.ERROR, Severity.WARN, Severity.INFO # noqa: E741
if expect_bpy and "bpy" not in c.imports:
- out.append(_f(E, f"{target} never imports bpy", 1, "start the file with `import bpy`"))
+ out.append(_f(LintKind.UNDEFINED_NAME, E, f"{target} never imports bpy", 1, "start the file with `import bpy`"))
def _import_finding(kind: str, mod: str, line: int) -> GateFinding:
if kind == "forbidden":
- return _f(E, f"forbidden import `{mod}`", line, "only bpy/bmesh/mathutils/math/random/numpy (+stdlib data helpers) are allowed")
- return _f(W, f"unexpected import `{mod}` (not available / not allowed in the build sandbox)", line, "use only bpy, bmesh, mathutils, math, random, numpy")
+ return _f(LintKind.FORBIDDEN_IMPORT, E, f"forbidden import `{mod}`", line, "only bpy/bmesh/mathutils/math/random/numpy (+stdlib data helpers) are allowed")
+ return _f(LintKind.BAD_IMPORT, W, f"unexpected import `{mod}` (not available / not allowed in the build sandbox)", line, "use only bpy, bmesh, mathutils, math, random, numpy")
out.extend(check_imports(c.imports, forbidden=FORBIDDEN_IMPORTS, allowed=ALLOWED_IMPORTS, make_finding=_import_finding))
for name, call in c.calls:
for prefix, hint in FORBIDDEN_CALL_PREFIXES:
if name.startswith(prefix):
- out.append(_f(E, f"forbidden call `{name}`", call.lineno, hint))
- for prefix, hint in WARN_CALL_PREFIXES:
+ out.append(_f(LintKind.SANDBOX, E, f"forbidden call `{name}`", call.lineno, hint))
+ for prefix, hint, kind in WARN_CALL_PREFIXES:
if name.startswith(prefix):
- out.append(_f(W, f"`{name}` — {hint}", call.lineno, hint))
+ out.append(_f(kind, W, f"`{name}` — {hint}", call.lineno, hint))
if name == "open":
- out.append(_f(E, "file IO via open() is forbidden", call.lineno, "no file reads/writes; the harness exports for you"))
+ out.append(_f(LintKind.SANDBOX, E, "file IO via open() is forbidden", call.lineno, "no file reads/writes; the harness exports for you"))
if name.startswith("bpy.ops.") and call.args and isinstance(call.args[0], ast.Dict):
- out.append(_f(E, f"`{name}({{...}})` context-dict override was removed in Blender 4.0", call.lineno,
+ out.append(_f(LintKind.API_TRAP, E, f"`{name}({{...}})` context-dict override was removed in Blender 4.0", call.lineno,
"use `with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj]): bpy.ops....()`"))
if name.endswith("primitive_cube_add"):
kws = {k.arg for k in call.keywords}
if "scale" in kws and "size" not in kws:
- out.append(_f(W, "primitive_cube_add(scale=...) without size=1 makes a 2 m cube × scale (extents doubled)", call.lineno,
+ out.append(_f(LintKind.API_TRAP, W, "primitive_cube_add(scale=...) without size=1 makes a 2 m cube × scale (extents doubled)", call.lineno,
"pass `size=1, scale=(sx, sy, sz)` then `bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)`"))
if name.endswith("transform_apply"):
kws = {k.arg for k in call.keywords}
if kws and not {"location", "rotation", "scale"} <= kws:
- out.append(_f(W, "transform_apply with partial kwargs: unspecified ones default to True (bakes location into mesh data)", call.lineno,
+ out.append(_f(LintKind.API_TRAP, W, "transform_apply with partial kwargs: unspecified ones default to True (bakes location into mesh data)", call.lineno,
"always pass all three: transform_apply(location=False, rotation=False, scale=True)"))
if name.endswith("modifier_apply") and not c.has_temp_override:
- out.append(_f(W, "bpy.ops.object.modifier_apply needs the object active+selected in OBJECT mode", call.lineno,
+ out.append(_f(LintKind.API_TRAP, W, "bpy.ops.object.modifier_apply needs the object active+selected in OBJECT mode", call.lineno,
"either leave modifiers unapplied (the exporter applies them) or wrap: `with bpy.context.temp_override(object=obj): bpy.ops.object.modifier_apply(modifier=mod.name)`"))
# the rule's own precondition: a script that sets the active object before joining (the urdf
# cookbook's `join_as`, one joined object per link) has done what the warning asks
if (name.endswith("bpy.ops.object.join") or name == "bpy.ops.object.join") and not any(
t.endswith("view_layer.objects.active") for t, _ in c.attr_stores):
- out.append(_f(W, "bpy.ops.object.join needs all parts selected + an active object; the result inherits the ACTIVE object's transform", call.lineno,
+ out.append(_f(LintKind.API_TRAP, W, "bpy.ops.object.join needs all parts selected + an active object; the result inherits the ACTIVE object's transform", call.lineno,
"select all, set `bpy.context.view_layer.objects.active = main_obj` (identity transform) before join — or keep parts separate (preferred: named parts)"))
if name.endswith("shade_smooth") and any(k.arg == "use_auto_smooth" for k in call.keywords):
- out.append(_f(E, "shade_smooth(use_auto_smooth=...) was removed in 4.1", call.lineno, "use `bpy.ops.object.shade_smooth_by_angle(angle=0.523599)` or `bpy.ops.object.shade_auto_smooth()`"))
+ out.append(_f(LintKind.API_TRAP, E, "shade_smooth(use_auto_smooth=...) was removed in 4.1", call.lineno, "use `bpy.ops.object.shade_smooth_by_angle(angle=0.523599)` or `bpy.ops.object.shade_auto_smooth()`"))
if name.endswith(".calc_normals"):
- out.append(_f(E, "Mesh.calc_normals() was removed in 4.0 (normals are computed automatically)", call.lineno, "delete the call (use me.update() if needed)"))
+ out.append(_f(LintKind.API_TRAP, E, "Mesh.calc_normals() was removed in 4.0 (normals are computed automatically)", call.lineno, "delete the call (use me.update() if needed)"))
for target, line in c.attr_stores:
if target.endswith(".use_auto_smooth") or target.endswith(".auto_smooth_angle"):
- out.append(_f(E, f"`{target}` was removed in Blender 4.1", line, "use bpy.ops.object.shade_smooth_by_angle(angle=...) or mark sharp edges; or just shade_smooth()"))
+ out.append(_f(LintKind.API_TRAP, E, f"`{target}` was removed in Blender 4.1", line, "use bpy.ops.object.shade_smooth_by_angle(angle=...) or mark sharp edges; or just shade_smooth()"))
if ".render." in target or target.endswith(".render"):
- out.append(_f(W, f"render settings touched: `{target}`", line, "the harness owns rendering; delete render/engine/resolution code"))
+ out.append(_f(LintKind.HARNESS_OWNED, W, f"render settings touched: `{target}`", line, "the harness owns rendering; delete render/engine/resolution code"))
if target.endswith("scene.camera") or target.endswith(".world"):
- out.append(_f(W, f"`{target}` assignment — cameras/world are owned by the harness", line, "remove camera/world code"))
+ out.append(_f(LintKind.HARNESS_OWNED, W, f"`{target}` assignment — cameras/world are owned by the harness", line, "remove camera/world code"))
if target.endswith(".use_nodes"):
- out.append(_f(I, "`use_nodes = True` is a no-op in Blender 5.x (materials always have a node tree); harmless", line, ""))
+ out.append(_f(LintKind.API_TRAP, I, "`use_nodes = True` is a no-op in Blender 5.x (materials always have a node tree); harmless", line, ""))
for key, line, guarded in c.bsdf_inputs:
if key in REMOVED_BSDF_INPUTS and not guarded: # `elif 'Specular' in bsdf.inputs:` is version-proof
- out.append(_f(E, f"Principled BSDF input '{key}' does not exist in Blender 4.x/5.x (KeyError at runtime)", line,
+ out.append(_f(LintKind.API_TRAP, E, f"Principled BSDF input '{key}' does not exist in Blender 4.x/5.x (KeyError at runtime)", line,
f"use inputs['{REMOVED_BSDF_INPUTS[key]}']"))
elif key == "Specular Tint":
- out.append(_f(I, "'Specular Tint' is an RGBA colour in Blender 4.x/5.x (a float raises TypeError)", line,
+ out.append(_f(LintKind.API_TRAP, I, "'Specular Tint' is an RGBA colour in Blender 4.x/5.x (a float raises TypeError)", line,
'assign a 4-tuple: inputs["Specular Tint"].default_value = (r, g, b, 1.0)'))
has_lookup = any(n.endswith("ensure_lookup_table") for n, _ in c.calls)
# only subscripts on a BMESH object need ensure_lookup_table (BMElemSeq); e.verts[0]
# (BMEdge/BMFace tuples) and me.edges[i] (Mesh collections) are always fine.
bm_subs = [line for base, line in c.bm_subscripts if base in c.bm_names or base == "bm"]
if "bmesh" in c.imports and bm_subs and not has_lookup:
- out.append(_f(E, "bmesh verts/edges/faces indexed with [] but ensure_lookup_table() is never called → IndexError", bm_subs[0],
+ out.append(_f(LintKind.API_TRAP, E, "bmesh verts/edges/faces indexed with [] but ensure_lookup_table() is never called → IndexError", bm_subs[0],
"after bm.from_mesh()/any topology change call `bm.verts.ensure_lookup_table(); bm.edges.ensure_lookup_table(); bm.faces.ensure_lookup_table()` before indexing"))
for name, line in c.name_loads:
if name in KNOWN_BINDINGS and name not in c.bound:
hint = {"Vector": "from mathutils import Vector", "Matrix": "from mathutils import Matrix", "Euler": "from mathutils import Euler",
"Quaternion": "from mathutils import Quaternion", "np": "import numpy as np", "numpy": "import numpy"}.get(name, f"import {name}")
- out.append(_f(E, f"`{name}` is used but never imported (NameError at runtime)", line, hint))
+ out.append(_f(LintKind.UNDEFINED_NAME, E, f"`{name}` is used but never imported (NameError at runtime)", line, hint))
break
if "bpy.context.selected_objects" in source:
- out.append(_f(W, "bpy.context.selected_objects is unreliable in background mode (often empty)", None,
+ out.append(_f(LintKind.API_TRAP, W, "bpy.context.selected_objects is unreliable in background mode (often empty)", None,
"keep references to the objects you create (`obj = bpy.context.object` right after primitive_*_add) instead of re-reading the selection"))
for const, line in c.constants:
if const == "BLENDER_EEVEE_NEXT":
- out.append(_f(W, "'BLENDER_EEVEE_NEXT' is not a valid engine id in Blender 5.0", line, "render settings are owned by the harness; delete the line"))
+ out.append(_f(LintKind.HARNESS_OWNED, W, "'BLENDER_EEVEE_NEXT' is not a valid engine id in Blender 5.0", line, "render settings are owned by the harness; delete the line"))
pascal = [n for n in c.names_assigned if PASCAL_RE.match(n) and n not in ("Cube", "Cylinder", "Sphere", "Plane")]
if pascal:
- out.append(_f(I, f"named objects: {sorted(set(pascal))[:12]}", None, ""))
+ out.append(_f(LintKind.CENSUS, I, f"named objects: {sorted(set(pascal))[:12]}", None, ""))
elif expect_names:
- out.append(_f(W, "no PascalCase object names found (e.g. obj.name = 'SeatCushion')", None,
+ out.append(_f(LintKind.NAMING, W, "no PascalCase object names found (e.g. obj.name = 'SeatCushion')", None,
"name every visible mesh after its part: `obj.name = 'SeatCushion'`; instances `Leg_0..Leg_3`"))
return out
@@ -310,7 +313,7 @@ def lint_blender_source(
tree, exc = safe_parse(source, target)
if tree is None:
msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
- findings.append(_f(Severity.ERROR, msg, line, hint, target))
+ findings.append(_f(LintKind.SYNTAX, Severity.ERROR, msg, line, hint, target))
return GateReport.of(GATE, findings, duration_ms=int((time.monotonic() - t0) * 1000))
c = _Collector()
c.visit(tree)
@@ -382,7 +385,7 @@ def _layout_rules(ws: Workspace, parts: list[Path], entry_tree: ast.Module | Non
target = ws_rel(ws, p)
stem = p.stem
if stem != to_snake(stem):
- out.append(_f(E, f"part file name '{p.name}' is not snake_case", target=target,
+ out.append(_f(LintKind.NAMING, E, f"part file name '{p.name}' is not snake_case", target=target,
hint=f"rename to src/{PARTS_DIR}/{to_snake(stem)}.py (the harness maps plan part "
f"'{stem}' → that file) and fix the import in model.py"))
continue
@@ -391,18 +394,18 @@ def _layout_rules(ws: Workspace, parts: list[Path], entry_tree: ast.Module | Non
continue # reported by the per-file lint
fn = f"build_{stem}"
if fn not in _exported_functions(tree):
- out.append(_f(E, f"{target} does not define `def {fn}()`", target=target,
+ out.append(_f(LintKind.LAYOUT, E, f"{target} does not define `def {fn}()`", target=target,
hint=f"every part file exports `def {fn}() -> bpy.types.Object` returning the named object "
f"at its world pose; model.py calls it (`from {PARTS_DIR}.{stem} import {fn}`)"))
for node in tree.body:
if isinstance(node, ast.Expr) and isinstance(node.value, ast.Call):
name = getattr(node.value.func, "id", "")
if name.startswith("build_") or name == "main":
- out.append(_f(W, f"{target} calls `{name}()` at import time", node.lineno, target=target,
+ out.append(_f(LintKind.LAYOUT, W, f"{target} calls `{name}()` at import time", node.lineno, target=target,
hint="part files only DEFINE builders; model.py calls them once (a module-level "
"call here builds the part twice → auto-suffixed 'Name.001')"))
if entry_tree is not None and stem not in imported:
- out.append(_f(W, f"{target} is never imported by src/model.py → its part is not built", target=target,
+ out.append(_f(LintKind.PART_NOT_IMPORTED, W, f"{target} is never imported by src/model.py → its part is not built", target=target,
hint=f"add `from {PARTS_DIR}.{stem} import {fn}` to model.py and call `{fn}()` in main()"))
return out
@@ -413,7 +416,7 @@ def lint_workspace(ws: Workspace) -> GateReport:
entry = ws.root / ENTRY_REL
if not entry.is_file():
return GateReport.of(GATE, [_f(
- Severity.ERROR, f"{ENTRY_REL} is missing", target=ENTRY_REL,
+ LintKind.MISSING_FILE, Severity.ERROR, f"{ENTRY_REL} is missing", target=ENTRY_REL,
hint="create src/model.py (entry: imports src/parts/<snake>.py builders and calls them; see the skeleton)")])
parts = part_files(ws)
findings: list[GateFinding] = []
diff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.py
index d34dc4fb..aa967d4d 100644
--- a/harness/codeverse3d/languages/scene_threejs/__init__.py
+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py
@@ -13,6 +13,7 @@ from codeverse3d.contracts.artifacts import (
BuildResult,
GateFinding,
GateReport,
+ LintKind,
RenderSet,
Severity,
)
@@ -39,25 +40,25 @@ _CREATE_SCENE_RE = re.compile(r"export\s+(?:async\s+)?function\s+createScene\b|e
_BUILD_RE = re.compile(r"export\s+(?:async\s+)?function\s+build\b|export\s+(?:const|let)\s+build\b|export\s*\{[^}]*\bbuild\b[^}]*\}")
_BUILD_ANY_RE = re.compile(r"export\s+(?:async\s+)?function\s+build[A-Za-z0-9_]*\b|export\s+(?:const|let)\s+build[A-Za-z0-9_]*\b")
-#: (regex, severity, message, hint)
-_PATTERNS: list[tuple[re.Pattern[str], Severity, str, str]] = [
- (re.compile(r"\brequestAnimationFrame\s*\("), Severity.ERROR, "requestAnimationFrame: the host drives update(t, dt)", "delete your render loop; animate inside update(t, dt)"),
- (re.compile(r"\bsetAnimationLoop\s*\("), Severity.ERROR, "renderer.setAnimationLoop: the host drives rendering", "remove it; animate inside update(t, dt)"),
- (re.compile(r"new\s+THREE\.WebGLRenderer\b|new\s+WebGLRenderer\b|new\s+THREE\.WebGPURenderer\b"), Severity.ERROR, "creating a renderer: the host owns the WebGLRenderer", "use the `renderer` passed to createScene only for capability checks"),
- (re.compile(r"\brenderer\.render\s*\("), Severity.ERROR, "renderer.render(): the host renders", "remove; return {scene, cameras, update} and let the host render"),
- (re.compile(r"\bfetch\s*\(\s*['\"]https?://|XMLHttpRequest|new\s+WebSocket\b|['\"]https?://[^'\"]+\.(?:js|mjs|glb|gltf|png|jpg|hdr)['\"]"), Severity.ERROR, "network / CDN access", "no network: import 'three' / 'three/addons/*' and load assets from '/assets/<name>.glb'"),
- (re.compile(r"\bdocument\.(?:body|getElementById|querySelector|querySelectorAll|head)\b|\bwindow\.addEventListener\b|\.innerHTML\b|\blocalStorage\b"), Severity.ERROR, "DOM/page access outside the host contract", "the host owns the page; only document.createElement('canvas') for procedural textures is allowed"),
- (re.compile(r"\bTHREE\.Geometry\b|\bFace3\b|\bexamples/js/"), Severity.ERROR, "removed three.js API (Geometry/Face3/examples/js)", "use BufferGeometry and 'three/addons/...' imports"),
- (re.compile(r"\b(?:Box|Plane|Sphere|Cylinder|Cone|Torus|Circle|Ring|Shape|Extrude|Lathe|Tube|Icosahedron|Dodecahedron|Octahedron|Tetrahedron|Polyhedron|Edges|Wireframe)BufferGeometry\b"), Severity.ERROR, "*BufferGeometry aliases were removed (r144)", "drop the 'Buffer' infix: THREE.BoxGeometry"),
- (re.compile(r"\.outputEncoding\b|\bsRGBEncoding\b|\bLinearEncoding\b|\.encoding\s*="), Severity.ERROR, "texture/renderer .encoding was removed (r152)", "use texture.colorSpace = THREE.SRGBColorSpace (colour maps only)"),
- (re.compile(r"\bMath\.random\s*\("), Severity.WARN, "Math.random makes renders non-reproducible", "use a seeded PRNG (e.g. mulberry32) so rounds can be compared"),
- (re.compile(r"\brequire\s*\(|\bprocess\.env\b|\bmodule\.exports\b"), Severity.ERROR, "CommonJS / node globals in browser ESM", "use ESM import/export only"),
- (re.compile(r"\bTHREE\.ImageUtils\b|\bTHREE\.SceneUtils\b|\bMeshFaceMaterial\b|\bMultiMaterial\b"), Severity.ERROR, "removed three.js helper", "use TextureLoader / material arrays"),
+#: (regex, severity, message, hint, kind)
+_PATTERNS: list[tuple[re.Pattern[str], Severity, str, str, LintKind]] = [
+ (re.compile(r"\brequestAnimationFrame\s*\("), Severity.ERROR, "requestAnimationFrame: the host drives update(t, dt)", "delete your render loop; animate inside update(t, dt)", LintKind.HARNESS_OWNED),
+ (re.compile(r"\bsetAnimationLoop\s*\("), Severity.ERROR, "renderer.setAnimationLoop: the host drives rendering", "remove it; animate inside update(t, dt)", LintKind.HARNESS_OWNED),
+ (re.compile(r"new\s+THREE\.WebGLRenderer\b|new\s+WebGLRenderer\b|new\s+THREE\.WebGPURenderer\b"), Severity.ERROR, "creating a renderer: the host owns the WebGLRenderer", "use the `renderer` passed to createScene only for capability checks", LintKind.HARNESS_OWNED),
+ (re.compile(r"\brenderer\.render\s*\("), Severity.ERROR, "renderer.render(): the host renders", "remove; return {scene, cameras, update} and let the host render", LintKind.HARNESS_OWNED),
+ (re.compile(r"\bfetch\s*\(\s*['\"]https?://|XMLHttpRequest|new\s+WebSocket\b|['\"]https?://[^'\"]+\.(?:js|mjs|glb|gltf|png|jpg|hdr)['\"]"), Severity.ERROR, "network / CDN access", "no network: import 'three' / 'three/addons/*' and load assets from '/assets/<name>.glb'", LintKind.SANDBOX),
+ (re.compile(r"\bdocument\.(?:body|getElementById|querySelector|querySelectorAll|head)\b|\bwindow\.addEventListener\b|\.innerHTML\b|\blocalStorage\b"), Severity.ERROR, "DOM/page access outside the host contract", "the host owns the page; only document.createElement('canvas') for procedural textures is allowed", LintKind.SANDBOX),
+ (re.compile(r"\bTHREE\.Geometry\b|\bFace3\b|\bexamples/js/"), Severity.ERROR, "removed three.js API (Geometry/Face3/examples/js)", "use BufferGeometry and 'three/addons/...' imports", LintKind.API_TRAP),
+ (re.compile(r"\b(?:Box|Plane|Sphere|Cylinder|Cone|Torus|Circle|Ring|Shape|Extrude|Lathe|Tube|Icosahedron|Dodecahedron|Octahedron|Tetrahedron|Polyhedron|Edges|Wireframe)BufferGeometry\b"), Severity.ERROR, "*BufferGeometry aliases were removed (r144)", "drop the 'Buffer' infix: THREE.BoxGeometry", LintKind.API_TRAP),
+ (re.compile(r"\.outputEncoding\b|\bsRGBEncoding\b|\bLinearEncoding\b|\.encoding\s*="), Severity.ERROR, "texture/renderer .encoding was removed (r152)", "use texture.colorSpace = THREE.SRGBColorSpace (colour maps only)", LintKind.API_TRAP),
+ (re.compile(r"\bMath\.random\s*\("), Severity.WARN, "Math.random makes renders non-reproducible", "use a seeded PRNG (e.g. mulberry32) so rounds can be compared", LintKind.NONDETERMINISM),
+ (re.compile(r"\brequire\s*\(|\bprocess\.env\b|\bmodule\.exports\b"), Severity.ERROR, "CommonJS / node globals in browser ESM", "use ESM import/export only", LintKind.SANDBOX),
+ (re.compile(r"\bTHREE\.ImageUtils\b|\bTHREE\.SceneUtils\b|\bMeshFaceMaterial\b|\bMultiMaterial\b"), Severity.ERROR, "removed three.js helper", "use TextureLoader / material arrays", LintKind.API_TRAP),
]
-def _f(sev: Severity, msg: str, *, target: str, hint: str = "", **data: object) -> GateFinding:
- return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=dict(data))
+def _f(kind: LintKind, sev: Severity, msg: str, *, target: str, hint: str = "", **data: object) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data={"kind": kind.value, **data})
def _is_lib(path: Path, ws: Workspace) -> bool:
@@ -76,7 +77,7 @@ def _is_lib(path: Path, ws: Workspace) -> bool:
def _syntax_finding(p: SyntaxProblem, rel: str) -> GateFinding:
- return _f(Severity.ERROR, f"syntax: {p.message}", target=f"{rel}:{p.line}" if p.line else rel,
+ return _f(LintKind.SYNTAX, Severity.ERROR, f"syntax: {p.message}", target=f"{rel}:{p.line}" if p.line else rel,
hint="fix the syntax error at the quoted line (node --check)", line=p.line, detail=p.stderr_tail)
@@ -84,13 +85,13 @@ def _check_imports(rel: str, text: str, ws: Workspace, path: Path) -> list[GateF
def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
tgt = f"{rel}:{line}"
if v.kind is ImportKind.ESCAPES:
- return _f(Severity.ERROR, f"import '{spec}' escapes src/", target=tgt, hint="keep all code under src/")
+ return _f(LintKind.BAD_IMPORT, Severity.ERROR, f"import '{spec}' escapes src/", target=tgt, hint="keep all code under src/")
if v.kind is ImportKind.MISSING:
- return _f(Severity.ERROR, f"import of missing file '{spec}'", target=tgt,
+ return _f(LintKind.BAD_IMPORT, Severity.ERROR, f"import of missing file '{spec}'", target=tgt,
hint="create the file or fix the path (relative imports need the .js extension)")
if v.kind is ImportKind.ABSOLUTE:
- return _f(Severity.ERROR, f"absolute import '{spec}'", target=tgt, hint="use relative imports ('./x.js')")
- return _f(Severity.ERROR, f"import '{spec}' is not allowed (only 'three', 'three/addons/*', relative files)", target=tgt,
+ return _f(LintKind.BAD_IMPORT, Severity.ERROR, f"absolute import '{spec}'", target=tgt, hint="use relative imports ('./x.js')")
+ return _f(LintKind.BAD_IMPORT, Severity.ERROR, f"import '{spec}' is not allowed (only 'three', 'three/addons/*', relative files)", target=tgt,
hint="no CDN / npm packages; write the helper yourself in src/")
return check_imports(text, path, ws.src, make_finding=make_finding)[0]
@@ -103,7 +104,7 @@ def lint(ws: Workspace) -> GateReport:
files = js_sources(ws.src, dotfiles=True, mjs=True)
scene = ws.src / "scene.js"
if not scene.is_file():
- findings.append(_f(Severity.ERROR, "src/scene.js is missing", target="src/scene.js",
+ findings.append(_f(LintKind.MISSING_FILE, Severity.ERROR, "src/scene.js is missing", target="src/scene.js",
hint="create src/scene.js exporting createScene({THREE, renderer, loaders})"))
big: list[str] = []
syntax = node_check_syntax(files)
@@ -117,25 +118,25 @@ def lint(ws: Workspace) -> GateReport:
continue
findings.extend(_check_imports(rel, text, ws, path))
code = strip_js(text, strings=False) # a comment quoting the contract is not a call
- for pat, sev, msg, hint in _PATTERNS:
+ for pat, sev, msg, hint, kind in _PATTERNS:
m = pat.search(code)
if m:
line = line_of(code, m.start())
- findings.append(_f(sev, msg, target=f"{rel}:{line}", hint=hint))
+ findings.append(_f(kind, sev, msg, target=f"{rel}:{line}", hint=hint))
n_lines = text.count("\n") + 1
if n_lines > MAX_LINES:
big.append(f"{rel} ({n_lines} lines)")
if path == scene and not _CREATE_SCENE_RE.search(text):
- findings.append(_f(Severity.ERROR, "src/scene.js does not export createScene", target=rel,
+ findings.append(_f(LintKind.LAYOUT, Severity.ERROR, "src/scene.js does not export createScene", target=rel,
hint="export function createScene({ THREE, renderer, loaders }) { ... return { scene, cameras, update } }"))
if path.parent == ws.src / "zones" and not _BUILD_RE.search(text):
- findings.append(_f(Severity.ERROR, "zone module does not export build(ctx)", target=rel,
+ findings.append(_f(LintKind.LAYOUT, Severity.ERROR, "zone module does not export build(ctx)", target=rel,
hint="export function build(ctx) { const g = new THREE.Group(); g.name = 'ZoneName'; ...; return g; }"))
if path.parent == ws.src / "assets" and not _BUILD_ANY_RE.search(text):
- findings.append(_f(Severity.WARN, "asset module exports no build<Pascal>(THREE) factory", target=rel,
+ findings.append(_f(LintKind.LAYOUT, Severity.WARN, "asset module exports no build<Pascal>(THREE) factory", target=rel,
hint="export function buildLamp(THREE) { ... return group; }"))
for b in big:
- findings.append(_f(Severity.WARN, f"large file {b} > {MAX_LINES} lines", target=b.split(" ")[0],
+ findings.append(_f(LintKind.LAYOUT, Severity.WARN, f"large file {b} > {MAX_LINES} lines", target=b.split(" ")[0],
hint="split into zones/assets/shaders modules"))
return GateReport.of(GATE, findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse3d/languages/threejs/__init__.py b/harness/codeverse3d/languages/threejs/__init__.py
index f5ab0e70..38d2677c 100644
--- a/harness/codeverse3d/languages/threejs/__init__.py
+++ b/harness/codeverse3d/languages/threejs/__init__.py
@@ -8,7 +8,7 @@ import time
from pathlib import Path
from codeverse3d.config import get_settings
-from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, LintKind, Severity
from codeverse3d.contracts.common import ENTRY_FILE, Language
from codeverse3d.contracts.plan import Plan, StaticPlan
from codeverse3d.conventions import to_pascal, to_snake
@@ -99,44 +99,46 @@ GATE = "lint:threejs"
_EXPORT_BUILD_RE = re.compile(r"\bexport\s+(?:async\s+)?function\s+(build[A-Za-z0-9_]*)\s*\(")
_EXPORT_CONST_BUILD_RE = re.compile(r"\bexport\s+(?:const|let|var)\s+(build[A-Za-z0-9_]*)\s*=")
_EXPORT_LIST_RE = re.compile(r"\bexport\s*\{([^}]*)\}")
-# token -> (severity, message, fix hint)
-_FORBIDDEN: dict[str, tuple[Severity, str, str]] = {
- r"\bfetch\s*\(": (Severity.ERROR, "network access (fetch) is not allowed in object code", "build geometry procedurally; no downloads"),
- r"\bXMLHttpRequest\b": (Severity.ERROR, "network access (XMLHttpRequest) is not allowed", "remove it"),
- r"\bWebSocket\b": (Severity.ERROR, "network access (WebSocket) is not allowed", "remove it"),
- r"\bdocument\b": (Severity.ERROR, "DOM access (document) is not available: code runs in node", "remove DOM/canvas usage; no textures"),
- r"\bwindow\b": (Severity.ERROR, "DOM access (window) is not available: code runs in node", "remove it"),
- r"\bnavigator\b": (Severity.ERROR, "navigator is not available in node", "remove it"),
- r"\blocalStorage\b": (Severity.ERROR, "localStorage is not available", "remove it"),
- r"\brequire\s*\(": (Severity.ERROR, "CommonJS require() is not allowed; use ESM imports of 'three' only", "import * as THREE from 'three'"),
- r"\bprocess\.": (Severity.ERROR, "node process access is not allowed in object code", "remove it"),
- r"\beval\s*\(": (Severity.ERROR, "eval is not allowed", "remove it"),
- r"\bWebGLRenderer\b": (Severity.ERROR, "do not create renderers: the harness renders", "return the Group from build(THREE); delete renderer code"),
- r"\brequestAnimationFrame\b": (Severity.ERROR, "no render loops: put idle motion in root.userData.tick = (t, dt) => {}", "move per-frame logic into userData.tick"),
- r"\bTextureLoader\b|\bImageLoader\b|\bFileLoader\b": (Severity.ERROR, "loaders/textures cannot be exported from node", "use MeshStandardMaterial colour/roughness/metalness instead"),
- r"\bnew\s+THREE\.(?:Perspective|Orthographic)Camera\b": (Severity.WARN, "cameras in object code are ignored (harness owns the camera)", "delete it"),
- r"\bnew\s+THREE\.[A-Za-z]*Light\s*\(": (Severity.WARN, "lights in object code are exported as extras and ignored by the harness lighting", "delete them"),
- r"\bnew\s+THREE\.Scene\s*\(": (Severity.WARN, "do not build a Scene; return a Group", "replace Scene with Group"),
+# token -> (severity, message, fix hint, kind)
+_FORBIDDEN: dict[str, tuple[Severity, str, str, LintKind]] = {
+ r"\bfetch\s*\(": (Severity.ERROR, "network access (fetch) is not allowed in object code", "build geometry procedurally; no downloads", LintKind.SANDBOX),
+ r"\bXMLHttpRequest\b": (Severity.ERROR, "network access (XMLHttpRequest) is not allowed", "remove it", LintKind.SANDBOX),
+ r"\bWebSocket\b": (Severity.ERROR, "network access (WebSocket) is not allowed", "remove it", LintKind.SANDBOX),
+ r"\bdocument\b": (Severity.ERROR, "DOM access (document) is not available: code runs in node", "remove DOM/canvas usage; no textures", LintKind.SANDBOX),
+ r"\bwindow\b": (Severity.ERROR, "DOM access (window) is not available: code runs in node", "remove it", LintKind.SANDBOX),
+ r"\bnavigator\b": (Severity.ERROR, "navigator is not available in node", "remove it", LintKind.SANDBOX),
+ r"\blocalStorage\b": (Severity.ERROR, "localStorage is not available", "remove it", LintKind.SANDBOX),
+ r"\brequire\s*\(": (Severity.ERROR, "CommonJS require() is not allowed; use ESM imports of 'three' only", "import * as THREE from 'three'", LintKind.SANDBOX),
+ r"\bprocess\.": (Severity.ERROR, "node process access is not allowed in object code", "remove it", LintKind.SANDBOX),
+ r"\beval\s*\(": (Severity.ERROR, "eval is not allowed", "remove it", LintKind.SANDBOX),
+ r"\bWebGLRenderer\b": (Severity.ERROR, "do not create renderers: the harness renders", "return the Group from build(THREE); delete renderer code", LintKind.HARNESS_OWNED),
+ r"\brequestAnimationFrame\b": (Severity.ERROR, "no render loops: put idle motion in root.userData.tick = (t, dt) => {}", "move per-frame logic into userData.tick", LintKind.HARNESS_OWNED),
+ r"\bTextureLoader\b|\bImageLoader\b|\bFileLoader\b": (Severity.ERROR, "loaders/textures cannot be exported from node", "use MeshStandardMaterial colour/roughness/metalness instead", LintKind.SANDBOX),
+ r"\bnew\s+THREE\.(?:Perspective|Orthographic)Camera\b": (Severity.WARN, "cameras in object code are ignored (harness owns the camera)", "delete it", LintKind.HARNESS_OWNED),
+ r"\bnew\s+THREE\.[A-Za-z]*Light\s*\(": (Severity.WARN, "lights in object code are exported as extras and ignored by the harness lighting", "delete them", LintKind.HARNESS_OWNED),
+ r"\bnew\s+THREE\.Scene\s*\(": (Severity.WARN, "do not build a Scene; return a Group", "replace Scene with Group", LintKind.HARNESS_OWNED),
}
+def _f(kind: LintKind, sev: Severity, target: str, message: str, hint: str) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=message, fix_hint=hint, data={"kind": kind.value})
+
+
def _lint_imports(ws: Workspace, path: Path, src: str, findings: list[GateFinding]) -> set[Path]:
"""Validate import specifiers; return the set of resolved relative targets."""
rel = ws_rel(ws, path)
def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
if v.kind is ImportKind.ESCAPES:
- return GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message=f"{rel}:{line}: import '{spec}' escapes src/", fix_hint="keep all files under src/")
+ return _f(LintKind.BAD_IMPORT, Severity.ERROR, rel, f"{rel}:{line}: import '{spec}' escapes src/",
+ "keep all files under src/")
if v.kind is ImportKind.MISSING:
assert v.target is not None
- return GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message=f"{rel}:{line}: imported file does not exist: '{spec}'",
- fix_hint=f"create {ws_rel(ws, v.target)} or fix the path (extension '.js' is required)")
+ return _f(LintKind.BAD_IMPORT, Severity.ERROR, rel, f"{rel}:{line}: imported file does not exist: '{spec}'",
+ f"create {ws_rel(ws, v.target)} or fix the path (extension '.js' is required)")
kind = "URL" if v.kind is ImportKind.URL else "package"
- return GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message=f"{rel}:{line}: import of {kind} '{spec}' is not allowed",
- fix_hint="only 'three', 'three/addons/...' and relative './' imports are available")
+ return _f(LintKind.BAD_IMPORT, Severity.ERROR, rel, f"{rel}:{line}: import of {kind} '{spec}' is not allowed",
+ "only 'three', 'three/addons/...' and relative './' imports are available")
new, targets = check_imports(src, path, ws.src, make_finding=make_finding)
findings.extend(new)
@@ -146,11 +148,10 @@ def _lint_imports(ws: Workspace, path: Path, src: str, findings: list[GateFindin
def _lint_forbidden(ws: Workspace, path: Path, src: str, findings: list[GateFinding]) -> None:
stripped = strip_js(src)
rel = ws_rel(ws, path)
- for pattern, (sev, msg, hint) in _FORBIDDEN.items():
+ for pattern, (sev, msg, hint, kind) in _FORBIDDEN.items():
m = re.search(pattern, stripped)
if m:
- findings.append(GateFinding(gate=GATE, severity=sev, target=rel,
- message=f"{rel}:{line_of(stripped, m.start())}: {msg}", fix_hint=hint))
+ findings.append(_f(kind, sev, rel, f"{rel}:{line_of(stripped, m.start())}: {msg}", hint))
def _exports(src: str) -> set[str]:
@@ -176,8 +177,8 @@ def lint_workspace(ws: Workspace) -> GateReport:
syntax = check_syntax(sources)
if not entry.is_file():
- findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target="src/object.js",
- message="src/object.js is missing", fix_hint="create src/object.js with `export function build(THREE) { ... return root; }`"))
+ findings.append(_f(LintKind.MISSING_FILE, Severity.ERROR, "src/object.js",
+ "src/object.js is missing", "create src/object.js with `export function build(THREE) { ... return root; }`"))
imported: set[Path] = set()
for path in sources:
@@ -185,16 +186,16 @@ def lint_workspace(ws: Workspace) -> GateReport:
rel = ws_rel(ws, path)
syn = syntax.get(path)
if syn is not None:
- findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message=f"{rel}:{syn.line or '?'}: {syn.message}", fix_hint="fix the syntax error at that line"))
+ findings.append(_f(LintKind.SYNTAX, Severity.ERROR, rel, f"{rel}:{syn.line or '?'}: {syn.message}",
+ "fix the syntax error at that line"))
continue # other checks are noise on a file that does not parse
imported |= _lint_imports(ws, path, src, findings)
_lint_forbidden(ws, path, src, findings)
exports = _exports(src)
if path == entry:
if "build" not in exports:
- findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
- message="src/object.js must `export function build(THREE)`", fix_hint="add `export function build(THREE) { const root = new THREE.Group(); ...; return root; }`"))
+ findings.append(_f(LintKind.LAYOUT, Severity.ERROR, rel,
+ "src/object.js must `export function build(THREE)`", "add `export function build(THREE) { const root = new THREE.Group(); ...; return root; }`"))
elif path.parent == ws.src / "parts":
# matched by snake: the plan's `TVStand` lives in tv_stand.js and exports buildTVStand
expected = "build" + to_pascal(path.stem)
@@ -202,28 +203,28 @@ def lint_workspace(ws: Workspace) -> GateReport:
e.startswith("build") and len(e) > 5 and to_snake(e[5:]) == path.stem for e in exports):
named = sorted(e for e in exports if e != "build")
sev = Severity.WARN if any(e != "build" for e in exports) else Severity.ERROR
- findings.append(GateFinding(gate=GATE, severity=sev, target=rel,
- message=f"{rel}: expected `export function {expected}(THREE)` (found {sorted(exports) or 'no build export'})",
- fix_hint=f"rename the export to {expected} or the file to parts/{to_snake(named[0][5:]) if named else path.stem}.js"))
+ findings.append(_f(LintKind.LAYOUT, sev, rel,
+ f"{rel}: expected `export function {expected}(THREE)` (found {sorted(exports) or 'no build export'})",
+ f"rename the export to {expected} or the file to parts/{to_snake(named[0][5:]) if named else path.stem}.js"))
part_files = [p for p in sources if p.parent == ws.src / "parts"]
for p in part_files:
if p not in imported:
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=ws_rel(ws, p),
- message=f"{ws_rel(ws, p)} is not imported by any module (dead part file?)", fix_hint="import and add it in src/object.js or delete it"))
+ findings.append(_f(LintKind.PART_NOT_IMPORTED, Severity.WARN, ws_rel(ws, p),
+ f"{ws_rel(ws, p)} is not imported by any module (dead part file?)", "import and add it in src/object.js or delete it"))
plan = plan_or_none(ws.plan_path)
if type(plan) is StaticPlan: # an articulated plan's parts are not threejs part files
for part in plan.parts:
pf = ws.src / "parts" / f"{to_snake(part.name)}.js"
if not pf.is_file():
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=part.name,
- message=f"planned part {part.name} has no file src/parts/{to_snake(part.name)}.js",
- fix_hint=f"create it with `export function build{to_pascal(part.name)}(THREE)`"))
+ findings.append(_f(LintKind.MISSING_FILE, Severity.WARN, part.name,
+ f"planned part {part.name} has no file src/parts/{to_snake(part.name)}.js",
+ f"create it with `export function build{to_pascal(part.name)}(THREE)`"))
elif pf not in imported and entry.is_file():
- findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=part.name,
- message=f"planned part {part.name} is not assembled by src/object.js",
- fix_hint=f"import {{ build{to_pascal(part.name)} }} from './parts/{to_snake(part.name)}.js' and root.add(...)"))
+ findings.append(_f(LintKind.PART_NOT_IMPORTED, Severity.WARN, part.name,
+ f"planned part {part.name} is not assembled by src/object.js",
+ f"import {{ build{to_pascal(part.name)} }} from './parts/{to_snake(part.name)}.js' and root.add(...)"))
return GateReport.of(GATE, findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse3d/languages/urdf/__init__.py b/harness/codeverse3d/languages/urdf/__init__.py
index de164e07..8165b43a 100644
--- a/harness/codeverse3d/languages/urdf/__init__.py
+++ b/harness/codeverse3d/languages/urdf/__init__.py
@@ -17,7 +17,7 @@ from typing import Any
import numpy as np
from codeverse3d.config import Settings, get_settings
-from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, LintKind, Severity
from codeverse3d.contracts.common import ENTRY_FILE, Language, MimicSpec, mimic_issues
from codeverse3d.contracts.plan import ArticulatedPlan, JointPlan, PartPlan, Plan
from codeverse3d.conventions import LINK_NAME_RE, to_snake
@@ -106,16 +106,16 @@ _STATE_WORDS = ("open", "closed", "opened", "extended", "retracted", "raised", "
#: by that language's rules (``lint_blender_source``: imports, harness-owned and removed bpy APIs,
#: file IO); these are the few a link script adds on top. Until 2026-09-24 this module kept its
#: own looser lists: one source gave 7 ERRORs as blender and 2 WARNs as urdf.
-LINK_SCRIPT_CALLS: dict[str, tuple[Severity, str]] = {
- "exit": (Severity.ERROR, "exits Blender before the links are exported"),
- "quit": (Severity.ERROR, "exits Blender before the links are exported"),
- "input": (Severity.ERROR, "blocks headless Blender forever"),
- "time.sleep": (Severity.WARN, "pointless in a build script"),
+LINK_SCRIPT_CALLS: dict[str, tuple[Severity, str, LintKind]] = {
+ "exit": (Severity.ERROR, "exits Blender before the links are exported", LintKind.SANDBOX),
+ "quit": (Severity.ERROR, "exits Blender before the links are exported", LintKind.SANDBOX),
+ "input": (Severity.ERROR, "blocks headless Blender forever", LintKind.HANG_RISK),
+ "time.sleep": (Severity.WARN, "pointless in a build script", LintKind.HANG_RISK),
}
-def _f(sev: Severity, msg: str, *, target: str | None = None, fix: str = "", **data) -> GateFinding:
- return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=fix, data=data)
+def _f(kind: LintKind, sev: Severity, msg: str, *, target: str | None = None, fix: str = "", **data) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=fix, data={"kind": kind.value, **data})
def _floats(text: str | None) -> list[float] | None:
@@ -133,15 +133,15 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
root = ET.fromstring(text)
except ET.ParseError as e:
line = getattr(e, "position", (None, None))[0]
- out.append(_f(Severity.ERROR, f"{label} is not well-formed XML: {e}", target=label,
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.ERROR, f"{label} is not well-formed XML: {e}", target=label,
fix="Fix the XML (every <tag> closed, attributes quoted, one <robot> root element).", line=line))
return out, []
if root.tag != "robot":
- out.append(_f(Severity.ERROR, f"root element must be <robot>, got <{root.tag}>", target=label,
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.ERROR, f"root element must be <robot>, got <{root.tag}>", target=label,
fix='Wrap everything in <robot name="..."> ... </robot>.'))
return out, []
if not root.get("name"):
- out.append(_f(Severity.WARN, "<robot> has no name attribute", target=label, fix='<robot name="my_object">'))
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.WARN, "<robot> has no name attribute", target=label, fix='<robot name="my_object">'))
links = root.findall("link")
joints = root.findall("joint")
@@ -149,14 +149,14 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
for el in links:
name = el.get("name", "")
if not name:
- out.append(_f(Severity.ERROR, "<link> without name", target=label, fix='<link name="base">'))
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.ERROR, "<link> without name", target=label, fix='<link name="base">'))
continue
if name in link_names:
- out.append(_f(Severity.ERROR, f"duplicate link name '{name}'", target=name, fix="Link names must be unique."))
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.ERROR, f"duplicate link name '{name}'", target=name, fix="Link names must be unique."))
link_names.append(name)
_lint_link(el, name, out)
if not link_names:
- out.append(_f(Severity.ERROR, "URDF has no <link> elements", target=label, fix="Add one <link> per mesh object in model.py."))
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.ERROR, "URDF has no <link> elements", target=label, fix="Add one <link> per mesh object in model.py."))
return out, []
joint_names: list[str] = []
@@ -164,10 +164,10 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
for el in joints:
jname = el.get("name", "")
if not jname:
- out.append(_f(Severity.ERROR, "<joint> without name", target=label, fix='<joint name="hinge" type="revolute">'))
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.ERROR, "<joint> without name", target=label, fix='<joint name="hinge" type="revolute">'))
continue
if jname in joint_names:
- out.append(_f(Severity.ERROR, f"duplicate joint name '{jname}'", target=jname, fix="Joint names must be unique."))
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.ERROR, f"duplicate joint name '{jname}'", target=jname, fix="Joint names must be unique."))
joint_names.append(jname)
_lint_joint(el, jname, link_names, parent_of, out)
@@ -177,7 +177,7 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
children = set(parent_of)
roots = [n for n in link_names if n not in children]
if len(roots) != 1:
- out.append(_f(Severity.ERROR, f"expected exactly one root link (no parent joint), found {roots}", target=label,
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.ERROR, f"expected exactly one root link (no parent joint), found {roots}", target=label,
fix="Every link except the root must be the <child> of exactly one joint; connect extra roots with a fixed joint."))
else:
for link in link_names:
@@ -186,7 +186,7 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
seen.add(cur)
cur = parent_of[cur]
if cur != roots[0]:
- out.append(_f(Severity.ERROR, f"link '{link}' does not reach the root '{roots[0]}' (cycle or detached)", target=link,
+ out.append(_f(LintKind.URDF_STRUCTURE, Severity.ERROR, f"link '{link}' does not reach the root '{roots[0]}' (cycle or detached)", target=link,
fix="Joints must form a single tree rooted at the base link."))
return out, link_names
@@ -229,76 +229,76 @@ def _lint_mimics(joints: list[ET.Element], out: list[GateFinding]) -> None:
for i in mimic_issues(specs):
j, t = i.joint, i.target
if i.kind == "immobile":
- out.append(_f(Severity.ERROR, f"joint '{j}': a fixed joint has nothing to mimic", target=j,
+ out.append(_f(LintKind.MIMIC, Severity.ERROR, f"joint '{j}': a fixed joint has nothing to mimic", target=j,
fix="give it a type and a limit, or drop the <mimic>"))
elif i.kind == "zero_multiplier":
- out.append(_f(Severity.ERROR, f"joint '{j}': <mimic multiplier=\"0\"> — the joint cannot move",
+ out.append(_f(LintKind.MIMIC, Severity.ERROR, f"joint '{j}': <mimic multiplier=\"0\"> — the joint cannot move",
target=j, fix="use type=fixed, or a non-zero multiplier"))
elif i.kind == "self":
- out.append(_f(Severity.ERROR, f"joint '{j}': <mimic> names itself", target=j))
+ out.append(_f(LintKind.MIMIC, Severity.ERROR, f"joint '{j}': <mimic> names itself", target=j))
elif i.kind == "unknown_target":
- out.append(_f(Severity.ERROR, f"joint '{j}': <mimic joint=\"{t}\"> names no joint in this file",
+ out.append(_f(LintKind.MIMIC, Severity.ERROR, f"joint '{j}': <mimic joint=\"{t}\"> names no joint in this file",
target=j, fix=f"one of: {', '.join(known)}"))
elif i.kind == "immobile_target":
- out.append(_f(Severity.ERROR, f"joint '{j}': mimics '{t}', which is fixed and never moves", target=j,
+ out.append(_f(LintKind.MIMIC, Severity.ERROR, f"joint '{j}': mimics '{t}', which is fixed and never moves", target=j,
fix="mimic a joint that moves, or give that joint a type and a limit"))
elif i.kind == "out_of_range":
- out.append(_f(Severity.WARN, f"joint '{j}': following '{t}' drives it over {i.detail}, "
+ out.append(_f(LintKind.MIMIC, Severity.WARN, f"joint '{j}': following '{t}' drives it over {i.detail}, "
"outside its own <limit>", target=j,
fix="Make the limits and the multiplier agree: multiplier * driver range "
"+ offset is the range this joint really has."))
else:
- out.append(_f(Severity.ERROR, f"joint '{j}': <mimic> chain is a cycle through '{i.detail or j}'",
+ out.append(_f(LintKind.MIMIC, Severity.ERROR, f"joint '{j}': <mimic> chain is a cycle through '{i.detail or j}'",
target=j, fix="one joint drives the chain; the rest follow it, directly or in a line"))
def _lint_link(el: ET.Element, name: str, out: list[GateFinding]) -> None:
if name in RESERVED_LINK_NAMES:
- out.append(_f(Severity.ERROR, f"link name '{name}' is reserved by the GLB scene graph (glTF readers use it as the base frame)",
+ out.append(_f(LintKind.NAMING, Severity.ERROR, f"link name '{name}' is reserved by the GLB scene graph (glTF readers use it as the base frame)",
target=name, fix="Rename the link (e.g. 'base' or the part's name) in BOTH robot.urdf and model.py."))
if not LINK_NAME_RE.match(name):
- out.append(_f(Severity.WARN, f"link name '{name}' is not a plain identifier (letters/digits/underscore)", target=name,
+ out.append(_f(LintKind.NAMING, Severity.WARN, f"link name '{name}' is not a plain identifier (letters/digits/underscore)", target=name,
fix=f"Rename to '{to_snake(name)}' in BOTH robot.urdf and model.py (object names are case-sensitive; "
"Blender's auto-suffix '.001' means two objects shared a name)."))
if any(w in to_snake(name).split("_") for w in _STATE_WORDS):
- out.append(_f(Severity.WARN, f"link name '{name}' contains a state word — links are parts, states come from joints", target=name,
+ out.append(_f(LintKind.NAMING, Severity.WARN, f"link name '{name}' contains a state word — links are parts, states come from joints", target=name,
fix="Name the part (door, drawer, lid), not its state."))
visuals = el.findall("visual")
expected = f"meshes/{name}.glb"
if len(visuals) != 1:
- out.append(_f(Severity.ERROR, f"link '{name}' has {len(visuals)} <visual> elements; exactly one is required", target=name,
+ out.append(_f(LintKind.URDF_LINK, Severity.ERROR, f"link '{name}' has {len(visuals)} <visual> elements; exactly one is required", target=name,
fix=f'<visual><origin xyz="..." rpy="0 0 0"/><geometry><mesh filename="{expected}"/></geometry></visual>'))
for vis in visuals:
geom = vis.find("geometry")
mesh = geom.find("mesh") if geom is not None else None
if geom is None or mesh is None:
kinds = [c.tag for c in geom] if geom is not None else []
- out.append(_f(Severity.ERROR, f"link '{name}': visual geometry must be a <mesh> (found {kinds or 'nothing'})", target=name,
+ out.append(_f(LintKind.URDF_LINK, Severity.ERROR, f"link '{name}': visual geometry must be a <mesh> (found {kinds or 'nothing'})", target=name,
fix=f'Build the shape in model.py and reference <mesh filename="{expected}"/>.'))
else:
fn = mesh.get("filename", "")
if fn != expected:
- out.append(_f(Severity.ERROR, f"link '{name}': mesh filename '{fn}' must be '{expected}'", target=name,
+ out.append(_f(LintKind.URDF_LINK, Severity.ERROR, f"link '{name}': mesh filename '{fn}' must be '{expected}'", target=name,
fix=f'<mesh filename="{expected}"/>'))
try:
sc = parse_floats(mesh.get("scale"), 3, f"link {name} mesh scale") if mesh.get("scale") else None
except UrdfError as e:
- out.append(_f(Severity.ERROR, str(e), target=name, fix="Drop the scale attribute and size the geometry in model.py."))
+ out.append(_f(LintKind.URDF_LINK, Severity.ERROR, str(e), target=name, fix="Drop the scale attribute and size the geometry in model.py."))
sc = None
if sc is not None and any(abs(s - 1) > 1e-9 for s in sc):
- out.append(_f(Severity.WARN, f"link '{name}': mesh scale {list(sc)} — model in meters in model.py instead", target=name,
+ out.append(_f(LintKind.URDF_LINK, Severity.WARN, f"link '{name}': mesh scale {list(sc)} — model in meters in model.py instead", target=name,
fix="Drop the scale attribute and size the geometry in model.py."))
try:
parse_origin(vis, f"link {name} visual")
except UrdfError as e:
- out.append(_f(Severity.ERROR, str(e), target=name, fix='<origin xyz="0 0 0" rpy="0 0 0"/>'))
+ out.append(_f(LintKind.URDF_LINK, Severity.ERROR, str(e), target=name, fix='<origin xyz="0 0 0" rpy="0 0 0"/>'))
col = el.find("collision")
if col is None:
- out.append(_f(Severity.WARN, f"link '{name}' has no <collision> twin of its visual", target=name,
+ out.append(_f(LintKind.URDF_LINK, Severity.WARN, f"link '{name}' has no <collision> twin of its visual", target=name,
fix="Copy the <visual> block as <collision> (same origin + geometry)."))
else:
if _sig(col.find("geometry")) != _sig(geom) or _origin_sig(col.find("origin")) != _origin_sig(vis.find("origin")):
- out.append(_f(Severity.WARN, f"link '{name}': <collision> differs from <visual>; the harness collides the VISUAL mesh", target=name,
+ out.append(_f(LintKind.URDF_LINK, Severity.WARN, f"link '{name}': <collision> differs from <visual>; the harness collides the VISUAL mesh", target=name,
fix="Make <collision> an identical copy of <visual>."))
@@ -316,7 +316,7 @@ def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: di
out: list[GateFinding]) -> None:
jtype = el.get("type", "")
if jtype not in JOINT_TYPES:
- out.append(_f(Severity.ERROR, f"joint '{jname}': type '{jtype}' must be one of {JOINT_TYPES}", target=jname,
+ out.append(_f(LintKind.URDF_JOINT, Severity.ERROR, f"joint '{jname}': type '{jtype}' must be one of {JOINT_TYPES}", target=jname,
fix='type="revolute" (hinge) | "prismatic" (slide) | "continuous" (wheel) | "fixed"'))
p = el.find("parent")
c = el.find("child")
@@ -324,15 +324,15 @@ def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: di
child = c.get("link", "") if c is not None else ""
for role, lk in (("parent", parent), ("child", child)):
if not lk:
- out.append(_f(Severity.ERROR, f"joint '{jname}': missing <{role} link=...>", target=jname, fix=f'<{role} link="base"/>'))
+ out.append(_f(LintKind.URDF_JOINT, Severity.ERROR, f"joint '{jname}': missing <{role} link=...>", target=jname, fix=f'<{role} link="base"/>'))
elif lk not in link_names:
- out.append(_f(Severity.ERROR, f"joint '{jname}': {role} link '{lk}' does not exist (links: {link_names})", target=jname,
+ out.append(_f(LintKind.URDF_JOINT, Severity.ERROR, f"joint '{jname}': {role} link '{lk}' does not exist (links: {link_names})", target=jname,
fix="Reference an existing <link name>."))
if parent and child and parent == child:
- out.append(_f(Severity.ERROR, f"joint '{jname}': parent == child", target=jname, fix="A joint connects two different links."))
+ out.append(_f(LintKind.URDF_JOINT, Severity.ERROR, f"joint '{jname}': parent == child", target=jname, fix="A joint connects two different links."))
if child:
if child in parent_of:
- out.append(_f(Severity.ERROR, f"link '{child}' is the child of two joints ('{jname}' and another)", target=jname,
+ out.append(_f(LintKind.URDF_JOINT, Severity.ERROR, f"link '{child}' is the child of two joints ('{jname}' and another)", target=jname,
fix="Each link has exactly one parent joint (tree)."))
parent_of[child] = parent
if jtype not in JOINT_TYPES or not parent or not child:
@@ -342,33 +342,33 @@ def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: di
try:
j = parse_joint(el)
except UrdfError as e:
- out.append(_f(Severity.ERROR, str(e), target=jname))
+ out.append(_f(LintKind.URDF_JOINT, Severity.ERROR, str(e), target=jname))
return
rpy = matrix_to_rpy(j.origin[:3, :3])
if any(abs(v) > 1e-9 for v in rpy):
- out.append(_f(Severity.INFO, f"joint '{jname}' uses a rotated origin (rpy); allowed, but point the <axis> instead where possible", target=jname))
+ out.append(_f(LintKind.URDF_JOINT, Severity.INFO, f"joint '{jname}' uses a rotated origin (rpy); allowed, but point the <axis> instead where possible", target=jname))
ax = el.find("axis")
if jtype in MOVABLE_TYPES:
if ax is None or ax.get("xyz") is None:
- out.append(_f(Severity.WARN, f"joint '{jname}': no <axis>; URDF defaults to '1 0 0'", target=jname, fix='<axis xyz="0 0 1"/>'))
+ out.append(_f(LintKind.URDF_JOINT, Severity.WARN, f"joint '{jname}': no <axis>; URDF defaults to '1 0 0'", target=jname, fix='<axis xyz="0 0 1"/>'))
else:
n = math.sqrt(sum(v * v for v in parse_floats(ax.get("xyz"), 3, "axis")))
if abs(n - 1) > 1e-3:
unit = " ".join(f"{v:.6g}" for v in j.axis)
- out.append(_f(Severity.WARN, f"joint '{jname}': axis not unit length (|a|={n:.4g}); auto-normalised", target=jname,
+ out.append(_f(LintKind.URDF_JOINT, Severity.WARN, f"joint '{jname}': axis not unit length (|a|={n:.4g}); auto-normalised", target=jname,
fix=f'<axis xyz="{unit}"/>'))
lim = el.find("limit")
if jtype in ("revolute", "prismatic") and j.lower is not None and j.upper is not None:
if abs(j.upper - j.lower) < 1e-9:
- out.append(_f(Severity.WARN, f"joint '{jname}': lower == upper (joint cannot move)", target=jname,
+ out.append(_f(LintKind.URDF_JOINT, Severity.WARN, f"joint '{jname}': lower == upper (joint cannot move)", target=jname,
fix="Give the joint a range, or make it type=fixed."))
if jtype == "revolute" and j.upper - j.lower > 2 * math.pi + 1e-6:
- out.append(_f(Severity.WARN, f"joint '{jname}': revolute range > 2π — use type=continuous", target=jname))
+ out.append(_f(LintKind.URDF_JOINT, Severity.WARN, f"joint '{jname}': revolute range > 2π — use type=continuous", target=jname))
if lim is not None and (lim.get("effort") is None or lim.get("velocity") is None):
- out.append(_f(Severity.WARN, f"joint '{jname}': <limit> should carry effort and velocity", target=jname,
+ out.append(_f(LintKind.URDF_JOINT, Severity.WARN, f"joint '{jname}': <limit> should carry effort and velocity", target=jname,
fix='effort="10" velocity="1"'))
elif jtype == "continuous" and lim is not None and (lim.get("lower") is not None or lim.get("upper") is not None):
- out.append(_f(Severity.WARN, f"joint '{jname}': continuous joints have no lower/upper (ignored)", target=jname,
+ out.append(_f(LintKind.URDF_JOINT, Severity.WARN, f"joint '{jname}': continuous joints have no lower/upper (ignored)", target=jname,
fix='<limit effort="10" velocity="1"/> or use type=revolute'))
@@ -386,15 +386,15 @@ def lint_model_text(text: str, link_names: list[str], *, label: str = MODEL_REL)
if isinstance(node, ast.Constant) and isinstance(node.value, str):
strings.add(node.value)
elif isinstance(node, ast.Call) and (rule := LINK_SCRIPT_CALLS.get(dotted(node.func))):
- sev, why = rule
- out.append(_f(sev, f"line {node.lineno}: {dotted(node.func)}(): {why}", target=label,
+ sev, why, kind = rule
+ out.append(_f(kind, sev, f"line {node.lineno}: {dotted(node.func)}(): {why}", target=label,
fix="Remove the call." if sev == Severity.ERROR else "", line=node.lineno))
elif isinstance(node, ast.While) and isinstance(node.test, ast.Constant) and node.test.value is True:
- out.append(_f(Severity.WARN, f"line {node.lineno}: 'while True' in a build script risks a hang",
+ out.append(_f(LintKind.HANG_RISK, Severity.WARN, f"line {node.lineno}: 'while True' in a build script risks a hang",
target=label, line=node.lineno))
for link in link_names:
if not any(link in s for s in strings):
- out.append(_f(Severity.WARN, f"link '{link}' never appears as a string in {label} — the wrapper looks for an object named exactly '{link}'",
+ out.append(_f(LintKind.LINK_NAME, Severity.WARN, f"link '{link}' never appears as a string in {label} — the wrapper looks for an object named exactly '{link}'",
target=link, fix=f'obj.name = "{link}"'))
return out
@@ -407,12 +407,12 @@ def lint_workspace(ws: Workspace) -> GateReport:
model_p = ws.root / MODEL_REL
link_names: list[str] = []
if not urdf_p.is_file():
- findings.append(_f(Severity.ERROR, f"missing {URDF_REL}", target=URDF_REL, fix="Write src/robot.urdf (see the contract)."))
+ findings.append(_f(LintKind.MISSING_FILE, Severity.ERROR, f"missing {URDF_REL}", target=URDF_REL, fix="Write src/robot.urdf (see the contract)."))
else:
f, link_names = lint_urdf_text(urdf_p.read_text())
findings.extend(f)
if not model_p.is_file():
- findings.append(_f(Severity.ERROR, f"missing {MODEL_REL}", target=MODEL_REL, fix="Write src/model.py (pure bpy, one object per link)."))
+ findings.append(_f(LintKind.MISSING_FILE, Severity.ERROR, f"missing {MODEL_REL}", target=MODEL_REL, fix="Write src/model.py (pure bpy, one object per link)."))
else:
findings.extend(lint_model_text(model_p.read_text(), link_names))
return GateReport.of(GATE, findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse3d/skills/registry.py b/harness/codeverse3d/skills/registry.py
index 890bfd0a..090990b7 100644
--- a/harness/codeverse3d/skills/registry.py
+++ b/harness/codeverse3d/skills/registry.py
@@ -4,8 +4,9 @@ Two things live here and nowhere else:
**finding_kind()** — a finding's kind is ``"<gate>/<data.kind>"``, the kind the gate itself
wrote (``connectivity/penetration``, ``scene_frames/no_motion``); the ``lint:<language>``
-gates are one ``lint`` family. A finding whose gate writes no kind (the lints, motion_direction,
-render_console) is ``"<gate>/untyped"``, which only a family row (``lint/*``) answers. No
+gates are one ``lint`` family, typed by ``contracts.artifacts.LintKind``. Every gate now writes
+a kind; a finding recorded before its gate did (a lint or motion_direction round before
+2026-09-24) is ``"<gate>/untyped"``, which only a family row (``joint_sweep/*``) answers. No
message text is read: the regex this replaced left seven scene_frames kinds unrouted and R19
unreachable (audit 2026-09-24, N52), and every gate reword could unroute a skill. INFO lines
("all 7 parts are connected") are census, not defects, and have no kind.
@@ -22,6 +23,7 @@ import logging
from dataclasses import dataclass
from typing import Any
+from codeverse3d.contracts.artifacts import LintKind
from codeverse3d.skills.model import EVIDENCE_INHERITED, Selection, Skill
# --------------------------------------------------------------------------- finding kinds
@@ -45,7 +47,9 @@ SCENE_BLOWN = "scene_frames/blown_frame"
SCENE_NO_MOTION = "scene_frames/no_motion"
GL_FRAMES = "gl_frames/*"
SHADER_PREFLIGHT = "shader_preflight/*"
-LINT = f"lint/{UNTYPED}"
+MOTION_WRONG_DIRECTION = "motion_direction/wrong_direction"
+LINT = "lint/*"
+LINT_PART_NOT_IMPORTED = f"lint/{LintKind.PART_NOT_IMPORTED.value}"
def finding_kind(finding: Any) -> str | None:
@@ -146,8 +150,8 @@ ROUTES: tuple[Route, ...] = (
Route("R8", "c3d-blender-forms", 75, languages=BLENDER_LANGS, kinds=BUILD_KINDS,
why="blender authoring: the language of 47 of our graded runs"),
Route("R9", "c3d-blender-forms", 95, languages=BLENDER_LANGS, kinds=("repair",),
- findings=(LINT,),
- why="the lint flagged the build script (a part file never imported, a bpy trap)"),
+ findings=(LINT_PART_NOT_IMPORTED,),
+ why="a part file was written but never imported, so its geometry does not exist"),
Route("R10", "c3d-cadquery-forms", 75, languages=("cadquery",), kinds=BUILD_KINDS,
why="cadquery authoring (evidence: inherited-unverified — unranked by our corpus; routed by default "
"since 2026-09-22, C3D_SKILLS_UNVERIFIED=0 drops it)"),
@@ -158,8 +162,8 @@ ROUTES: tuple[Route, ...] = (
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", "c3d-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"),
+ findings=("joint_sweep/*", MOTION_WRONG_DIRECTION),
+ why="a joint_sweep finding, or a joint that moves against the plan, on the previous round"),
Route("R14", "c3d-scene-composition", 75, tracks=("scene",), languages=("scene_threejs",),
kinds=("baseline", "env", "zone", "refine"),
why="scene layout and camera framing"),
diff --git a/harness/codeverse3d/spatial/connectivity.py b/harness/codeverse3d/spatial/connectivity.py
index 4502e7a0..12ba22e3 100644
--- a/harness/codeverse3d/spatial/connectivity.py
+++ b/harness/codeverse3d/spatial/connectivity.py
@@ -410,7 +410,7 @@ def _island_findings(name: str, mesh: trimesh.Trimesh, islands: list[trimesh.Tri
gate=GATE, severity=Severity.WARN, target=name,
message=f"part '{name}' contains {len(tiny)} tiny disconnected island(s) (< {TINY_ISLAND_FRACTION:.0%} of the part size) — stray geometry",
fix_hint=f"remove the stray pieces or merge them into '{name}'; the part should be {len(islands) - len(tiny)} solid piece(s)",
- data={"islands": len(islands), "tiny_islands": len(tiny)},
+ data={"kind": "stray_islands", "islands": len(islands), "tiny_islands": len(tiny)},
))
return out
@@ -560,6 +560,7 @@ def check_connectivity(
support = min(comps, key=lambda c: (round(min(float(parts[n].bounds[0][1]) for n in c), 6),
-sum(len(parts[n].faces) for n in c))) if comps else set()
findings.append(GateFinding(gate=GATE, severity=Severity.WARN, message=f"no part touches the ground ({up}=0)",
+ data={"kind": "no_ground"},
fix_hint=f"move the whole object down so its lowest point sits on the ground ({up}=0, {frame_label(language)})"))
for n in big:
if n in support:
diff --git a/harness/codeverse3d/tracks/articulated_object.py b/harness/codeverse3d/tracks/articulated_object.py
index 6fa01c55..518218e3 100644
--- a/harness/codeverse3d/tracks/articulated_object.py
+++ b/harness/codeverse3d/tracks/articulated_object.py
@@ -154,6 +154,8 @@ def default_joint_sweep(ws: Workspace, plan: Plan | None, out_dir: Path) -> tupl
# ===================================================================== planned-motion gate
MOTION_GATE = "motion_direction"
+#: its findings' ``data.kind``: the joint moves the way the plan says / the other way / not measured
+MOTION_OK, MOTION_WRONG, MOTION_SKIPPED = "as_planned", "wrong_direction", "skipped"
#: phrase → direction key understood by ``spatial.joints_sweep.motion_direction_check``.
#: Longer phrases first so "pulls out" wins over "out"; explicit axes first of all.
@@ -356,7 +358,8 @@ def default_motion_checks(ws: Workspace, plan: Plan | None) -> GateReport | None
robot = load_urdf(urdf, ws.artifacts / "meshes")
except UrdfError as e:
return GateReport.of(MOTION_GATE, [GateFinding(
- gate=MOTION_GATE, severity=Severity.WARN, target="robot.urdf", message=f"motion checks skipped: {e}")])
+ gate=MOTION_GATE, severity=Severity.WARN, target="robot.urdf", message=f"motion checks skipped: {e}",
+ data={"kind": MOTION_SKIPPED})])
urdf_names = {to_snake(n): n for n in getattr(robot, "joints", {})}
for j, expected in wanted:
name = urdf_names.get(to_snake(j.name), j.name) # URDF joint named like the plan joint (any casing)
@@ -364,9 +367,9 @@ def default_motion_checks(ws: Workspace, plan: Plan | None) -> GateReport | None
chk = motion_direction_check(robot, name, expected)
except UrdfError as e:
findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.WARN, target=j.name,
- message=f"motion check skipped: {e}", data={"expected": expected}))
+ message=f"motion check skipped: {e}", data={"kind": MOTION_SKIPPED, "expected": expected}))
continue
- data = {"expected": expected, "observed_dir": list(chk.observed_dir), "motion": j.motion,
+ data = {"kind": MOTION_OK if chk.ok else MOTION_WRONG, "expected": expected, "observed_dir": list(chk.observed_dir), "motion": j.motion,
"cos": chk.cos, "suggested_axis": list(chk.suggested_axis) if chk.suggested_axis else None}
if chk.ok:
findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.INFO, target=j.name, message=chk.message, data=data))
diff --git a/harness/codeverse3d/tracks/scene.py b/harness/codeverse3d/tracks/scene.py
index ff8bac0e..26bb13c2 100644
--- a/harness/codeverse3d/tracks/scene.py
+++ b/harness/codeverse3d/tracks/scene.py
@@ -118,7 +118,7 @@ class ScenePipeline:
def post_render_gates(self, ctx: RunContext, round_index: int, renders: RenderSet) -> list[GateReport]:
errs = [e for e in renders.console_errors if e.strip()]
findings = [GateFinding(gate="render_console", severity=Severity.ERROR, target=_guess_target(e, ctx.plan), message=e[:300],
- fix_hint="open the named module, fix the thrown error; run the build/probe tool until no console errors")
+ data={"kind": "console_error"}, fix_hint="open the named module, fix the thrown error; run the build/probe tool until no console errors")
for e in errs[:MAX_CONSOLE_ERRORS]]
# `hardware_fps`, not `fps`: a number measured on SwiftShader is the box's, and
# telling the agent to merge geometry because the CPU rasteriser is slow sends it
@@ -126,7 +126,7 @@ class ScenePipeline:
# scenes_v1 measured 2-7 fps on SwiftShader while a fourth measured 11.5 on an
# RTX 6000 — four different renderers, one gate threshold).
if renders.hardware_fps is not None and renders.hardware_fps < 20:
- findings.append(GateFinding(gate="render_console", severity=Severity.WARN, target="overall",
+ findings.append(GateFinding(gate="render_console", severity=Severity.WARN, target="overall", data={"kind": "low_fps"},
message=f"low frame rate {renders.hardware_fps:.0f} fps" + perf_detail(renders),
fix_hint="merge static geometry "
"(BufferGeometryUtils.mergeGeometries) and put anything repeated > 5x in ONE "
diff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.md
index 67afba8a..efc2432a 100644
--- a/harness/docs/SKILLS.md
+++ b/harness/docs/SKILLS.md
@@ -218,9 +218,12 @@ cap and the order themselves come from `select`'s final sort and slice, pinned b
`finding_kind()` reads no message text (audit 2026-09-24, N52): the message regex it replaced
left seven `scene_frames` kinds unrouted and R19 unreachable, and any gate reword could unroute
-a skill. A gate that writes no `data.kind` (the lints, motion_direction, render_console) gives
-`<gate>/untyped`, which only a family row (`lint/*`, `motion_direction/*`) answers; the lint gates
-are one `lint` family. INFO findings are census, not defects, and have no kind — routing off
+a skill. Every gate writes a `data.kind` — the lints from one vocabulary
+(`contracts.artifacts.LintKind`), connectivity `stray_islands` / `no_ground`, motion_direction
+`wrong_direction` / `skipped`, render_console `console_error` / `low_fps` (2026-09-24) — so R9
+answers `lint/part_not_imported` and R13 `motion_direction/wrong_direction`, not every lint or
+motion line. A finding recorded before its gate wrote one is `<gate>/untyped`, which only a
+family row answers; the lint gates are one `lint` family. INFO findings are census, not defects, and have no kind — routing off
"all 7 parts are connected" would attach the penetration sheet to a run with none.
Adding a bundle means adding its rows in the same commit: an unroutable bundle pays the
diff --git a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py
index d360bfe3..9b08fc42 100644
--- a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py
+++ b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py
@@ -202,9 +202,11 @@ def test_default_motion_checks_on_real_urdf(tmp_path):
acceptance=[])
good = default_motion_checks(robot(tmp_path / "good", -1), plan)
assert good is not None and good.passed and good.findings[0].severity.value == "info"
+ assert good.findings[0].data["kind"] == "as_planned"
bad = default_motion_checks(robot(tmp_path / "bad", 1), plan)
assert bad is not None and not bad.passed and bad.errors[0].target == "DoorHinge"
assert "WRONG" in bad.errors[0].message and '<axis xyz="-0 -0 -1"/>' in bad.errors[0].fix_hint
+ assert bad.errors[0].data["kind"] == "wrong_direction"
# orthogonal (the swiss-knife class): a prismatic joint sliding +x when the plan says
# up — cos = 0 exactly, and the hint states the computed axis verbatim
import copy
diff --git a/harness/tests/skills/test_hook.py b/harness/tests/skills/test_hook.py
index 504a67fd..1427fb4a 100644
--- a/harness/tests/skills/test_hook.py
+++ b/harness/tests/skills/test_hook.py
@@ -62,9 +62,10 @@ def test_no_skill_failure_costs_the_round(ctx, monkeypatch):
def test_a_repair_names_the_sheet_that_answers_the_lint_it_is_fixing(ctx, monkeypatch):
- """The lint is found after the round attached its set: R9 (``lint/*``) points at the sheet."""
+ """The lint is found after the round attached its set: R9 points at the sheet."""
monkeypatch.setenv("C3D_SKILLS", "on")
assert H.attach_for_round(ctx, index=0, kind="repair")
lint = GateReport(gate="lint:blender", passed=True, findings=[GateFinding(
- gate="lint:blender", severity=Severity.WARN, message="src/parts/leg.py is never imported by src/model.py")])
+ gate="lint:blender", severity=Severity.WARN, message="src/parts/leg.py is never imported by src/model.py",
+ data={"kind": "part_not_imported"})])
assert "c3d-blender-forms" in H.repair_pointers(ctx, lint)
diff --git a/harness/tests/skills/test_registry.py b/harness/tests/skills/test_registry.py
index 7e6a24e8..ce92fb3f 100644
--- a/harness/tests/skills/test_registry.py
+++ b/harness/tests/skills/test_registry.py
@@ -19,9 +19,9 @@ def _f(gate, sev, message="", **data):
(_f("connectivity", W, "part 'X' contains 3 tiny disconnected island(s)", kind="penetration"),
"connectivity/penetration"),
(_f("scene_frames", E, "nothing moves: the largest change …", kind="no_motion"), "scene_frames/no_motion"),
- # a gate that writes no kind; the lint gates are one family
+ # the lint gates are one family; a finding recorded before its gate typed it is untyped
+ (_f("lint:urdf", W, "link 'lid' never appears as a string", kind="link_name"), "lint/link_name"),
(_f("lint:blender", W, "src/parts/leg.py is never imported by src/model.py"), "lint/untyped"),
- (_f("motion_direction", E, "shoulder_joint: … (WRONG — flip the axis sign)"), "motion_direction/untyped"),
# INFO is census: "all 7 parts are connected" must not attach the penetration sheet
(_f("connectivity", I, "contact ledger: 7 parts", kind="ledger"), None),
])
@@ -37,6 +37,38 @@ def test_finding_kinds_accepts_reports_and_findings_distinct_in_order():
assert finding_kinds([]) == [] and finding_kinds(None) == []
+_LEG = "import bpy\n\n\ndef build_leg():\n bpy.ops.mesh.primitive_cube_add(size=1)\n obj = bpy.context.object\n obj.name = 'Leg'\n return obj\n"
+_JOIN = "bpy.ops.object.join()\n"
+
+
[email protected](("model", "r9"), [
+ ("import bpy\n", True), # parts/leg.py never imported
+ ("import bpy\nfrom parts.leg import build_leg\n\nbuild_leg()\n" + _JOIN, False), # a bpy trap is not R9's
+])
+def test_r9_answers_a_part_file_never_imported_and_no_other_lint(tmp_ws, library, model, r9):
+ """R9 fired on ANY blender lint finding while the lints wrote no kind."""
+ from codeverse3d.languages.blender import lint_workspace
+
+ (tmp_ws.src / "parts").mkdir(parents=True, exist_ok=True)
+ (tmp_ws.src / "parts" / "leg.py").write_text(_LEG)
+ (tmp_ws.src / "model.py").write_text(model)
+ lint = lint_workspace(tmp_ws)
+ assert [f for f in lint.findings if f.severity != I], "the fixture must give the lint something to report"
+ got = select("static_object", "blender", "repair", findings=[lint], library=library)
+ assert ("R9" in next(s for s in got if s.name == "c3d-blender-forms").rules) is r9
+
+
+def test_r13_answers_a_joint_moving_against_the_plan_not_a_skipped_check(library):
+ from codeverse3d.tracks.articulated_object import MOTION_GATE, MOTION_SKIPPED, MOTION_WRONG
+
+ def rules(kind):
+ rep = GateReport(gate=MOTION_GATE, passed=False, findings=[_f(MOTION_GATE, E, "m", kind=kind)])
+ got = select("articulated_object", "urdf_blender", "repair", findings=[rep], library=library)
+ return next(s for s in got if s.name == "c3d-urdf-joints").rules
+
+ assert "R13" in rules(MOTION_WRONG) and "R13" not in rules(MOTION_SKIPPED)
+
+
def test_r19_answers_a_scene_with_nothing_moving(library):
"""N52: R19 keyed on a gl_frames-only regex, so a scene's no_motion ERROR routed nothing."""
nothing_moves = _f("scene_frames", E, "nothing moves: …", kind="no_motion")
diff --git a/harness/tests/skills/test_routing_property.py b/harness/tests/skills/test_routing_property.py
index eadd4519..6116b28b 100644
--- a/harness/tests/skills/test_routing_property.py
+++ b/harness/tests/skills/test_routing_property.py
@@ -22,8 +22,8 @@ SIGNAL_KEYS = tuple(plan_signals(None))
LIVE_KINDS = sorted({k for row in ROUTES for k in row.findings if not k.endswith("*")} |
{"connectivity/penetration", "connectivity/floating", "connectivity/untyped",
"contract/part_bbox", "contract/orientation", "joint_sweep/penetration",
- "motion_direction/untyped", "scene_frames/camera_low", "scene_frames/hero_unseen",
- "gl_frames/static", "shader_preflight/no_fog", "lint/untyped"})
+ "connectivity/stray_islands", "scene_frames/camera_low", "scene_frames/hero_unseen",
+ "gl_frames/static", "shader_preflight/no_fog"})
BASE_INPUTS = [(t, lang, kind) for t in TRACKS for lang in LANGUAGES for kind in KINDS]
diff --git a/harness/tests/spatial_tools/test_connectivity.py b/harness/tests/spatial_tools/test_connectivity.py
index 5fb33bfa..05cdbb42 100644
--- a/harness/tests/spatial_tools/test_connectivity.py
+++ b/harness/tests/spatial_tools/test_connectivity.py
@@ -52,7 +52,7 @@ def test_tiny_island_warns(tmp_path: Path) -> None:
sc.export(str(p))
r = check_connectivity(p)
warns = [f for f in r.findings if f.severity == Severity.WARN]
- assert warns and "tiny disconnected island" in warns[0].message
+ assert warns and "tiny disconnected island" in warns[0].message and warns[0].data["kind"] == "stray_islands"
def test_missing_glb_is_error(tmp_path: Path) -> None:
@@ -163,7 +163,7 @@ def test_a_model_authored_below_the_floor_still_reports_its_floating_part(tmp_pa
assert not sunk.passed, "a sunk model must not disable the floating check"
assert [(e.target, e.data["nearest"]) for e in sunk.errors] == [("hat", "body")]
# ... plus the ground warning, since nothing is on the floor any more
- assert any("touches the ground" in f.message for f in sunk.findings)
+ assert any("touches the ground" in f.message and f.data["kind"] == "no_ground" for f in sunk.findings)
def _scene(path: Path, **meshes: trimesh.Trimesh) -> Path:
diff --git a/harness/tests/threejs_render/test_lint.py b/harness/tests/threejs_render/test_lint.py
index 24f53ea8..3d032e3a 100644
--- a/harness/tests/threejs_render/test_lint.py
+++ b/harness/tests/threejs_render/test_lint.py
@@ -61,7 +61,7 @@ def test_part_export_name_dead_file_and_build_export(stool_ws: Workspace, no_nod
rep = lint_workspace(stool_ws)
warns = _msgs(rep, Severity.WARN)
assert any("expected `export function buildExtra(THREE)`" in m for m in warns)
- assert any("not imported by any module" in m for m in warns)
+ assert any("not imported by any module" in f.message and f.data["kind"] == "part_not_imported" for f in rep.findings)
assert not any("tv_stand.js: expected" in m for m in _msgs(rep))
(stool_ws.src / "parts" / "extra.js").write_text("export const nothing = 1;\n")
rep = lint_workspace(stool_ws)